Lines 80.00% 8 / 10
Functions and Methods 75.00% 3 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ExposedStateConverter 80.00% 8 / 10 75.00% 3 / 4 8.51 0.00% 0 / 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 66.66% 4 / 6 0.00% 0 / 1 5.93
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Ipc\Wire;
6
7use Stewart\Contracts\Exposure\ExposedState;
8use Stewart\Runtime\Json\ValueConverter;
9use Stewart\Support\Exception\JsonShapeException;
10
11// Wrapped in an object so an unknown state stays apart from a missing one.
12final readonly class ExposedStateConverter implements ValueConverter
13{
14    public function handledClass(): string
15    {
16        return ExposedState::class;
17    }
18
19    public function keySuffix(): string
20    {
21        return '';
22    }
23
24    /** @return array{value: int|float|string|bool|null} */
25    public function encodeValue(object $value): array
26    {
27        \assert($value instanceof ExposedState);
28
29        return ['value' => $value->value];
30    }
31
32    /** @throws JsonShapeException */
33    public function decodeValue(mixed $value, string $path): ExposedState
34    {
35        if (!\is_array($value) || !\array_key_exists('value', $value)) {
36            throw JsonShapeException::wrongType($path, 'an object with a value', get_debug_type($value));
37        }
38
39        $state = $value['value'];
40
41        if (!\is_scalar($state) && $state !== null) {
42            throw JsonShapeException::wrongType($path . '.value', 'a scalar or null', get_debug_type($state));
43        }
44
45        return new ExposedState($state);
46    }
47}