Lines 90.00% 9 / 10
Functions and Methods 80.00% 4 / 5
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StateUpdatesFragment 90.00% 9 / 10 80.00% 4 / 5 6.04 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fromCollection 100.00% 1 / 1 100.00% 1 / 1 1
 fromEncodedUpdates 100.00% 4 / 4 100.00% 1 / 1 1
 fromDecodedValue 100.00% 1 / 1 100.00% 1 / 1 1
 encodeToJson 66.66% 2 / 3 0.00% 0 / 1 2.15
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Ipc\Wire;
6
7use Stewart\Runtime\Ipc\Wire\Collection\EncodedStateUpdateCollection;
8use Stewart\Runtime\Json\JsonFragment;
9use Stewart\Runtime\Json\WireMapper;
10use Stewart\Support\State\Collection\StateUpdateCollection;
11use Stewart\Support\State\StateUpdate;
12
13final readonly class StateUpdatesFragment implements JsonFragment
14{
15    private function __construct(
16        public StateUpdateCollection $collection,
17        private ?EncodedStateUpdateCollection $encodedUpdates,
18    ) {}
19
20    public static function fromCollection(StateUpdateCollection $updates): self
21    {
22        return self::fromEncodedUpdates(EncodedStateUpdateCollection::fromList($updates->mapToList(static fn(StateUpdate $update): EncodedStateUpdate => new EncodedStateUpdate($update))));
23    }
24
25    public static function fromEncodedUpdates(EncodedStateUpdateCollection $encodedUpdates): self
26    {
27        return new self(
28            StateUpdateCollection::fromList($encodedUpdates->mapToList(static fn(EncodedStateUpdate $encoded): StateUpdate => $encoded->update)),
29            $encodedUpdates,
30        );
31    }
32
33    public static function fromDecodedValue(mixed $value, string $path, WireMapper $mapper): static
34    {
35        return new self(StateUpdateCollection::fromList($mapper->decodeObjectList(StateUpdate::class, $value, $path)), null);
36    }
37
38    public function encodeToJson(WireMapper $mapper): string
39    {
40        if ($this->encodedUpdates === null) {
41            return $mapper->encodeObjectList($this->collection->listValues());
42        }
43
44        return '[' . implode(',', $this->encodedUpdates->mapToList(static fn(EncodedStateUpdate $encoded): string => $encoded->encodeToJson($mapper))) . ']';
45    }
46}