Lines 100.00% 12 / 12
Functions and Methods 100.00% 5 / 5
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
EventContextConverter 100.00% 12 / 12 100.00% 5 / 5 9 100.00% 1 / 1
 handledClass 100.00% 1 / 1 100.00% 1 / 1 1
 keySuffix 100.00% 1 / 1 100.00% 1 / 1 1
 encodeValue 100.00% 2 / 2 100.00% 1 / 1 1
 decodeValue 100.00% 6 / 6 100.00% 1 / 1 3
 findString 100.00% 2 / 2 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Ipc\Wire;
6
7use Stewart\Contracts\State\EventContext;
8use Stewart\Runtime\Json\ValueConverter;
9use Stewart\Support\Exception\JsonShapeException;
10
11final readonly class EventContextConverter implements ValueConverter
12{
13    public function handledClass(): string
14    {
15        return EventContext::class;
16    }
17
18    public function keySuffix(): string
19    {
20        return '';
21    }
22
23    /** @return array{id: string, parent_id: string|null, user_id: string|null} */
24    public function encodeValue(object $value): array
25    {
26        \assert($value instanceof EventContext);
27
28        return ['id' => $value->id, 'parent_id' => $value->parentId, 'user_id' => $value->userId];
29    }
30
31    /** @throws JsonShapeException */
32    public function decodeValue(mixed $value, string $path): EventContext
33    {
34        if (!\is_array($value)) {
35            throw JsonShapeException::wrongType($path, 'an object', get_debug_type($value));
36        }
37
38        $id = $value['id'] ?? null;
39
40        if (!\is_string($id)) {
41            throw JsonShapeException::wrongType($path . '.id', 'a string', get_debug_type($id));
42        }
43
44        return new EventContext($id, $this->findString($value, 'parent_id', $path), $this->findString($value, 'user_id', $path));
45    }
46
47    /**
48     * @param array<array-key, mixed> $context
49     * @throws JsonShapeException
50     */
51    private function findString(array $context, string $key, string $path): ?string
52    {
53        $value = $context[$key] ?? null;
54
55        return $value === null || \is_string($value) ? $value : throw JsonShapeException::wrongType($path . '.' . $key, 'a string', get_debug_type($value));
56    }
57}