Lines 100.00% 15 / 15
Functions and Methods 100.00% 4 / 4
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
TriggerSpecConverter 100.00% 15 / 15 100.00% 4 / 4 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% 11 / 11 100.00% 1 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Ipc\Wire;
6
7use Stewart\Contracts\Exception\TriggerException;
8use Stewart\Runtime\Json\ValueConverter;
9use Stewart\Support\Exception\JsonShapeException;
10use Stewart\Support\Wire\TriggerSpec;
11
12final readonly class TriggerSpecConverter implements ValueConverter
13{
14    public function handledClass(): string
15    {
16        return TriggerSpec::class;
17    }
18
19    public function keySuffix(): string
20    {
21        return '';
22    }
23
24    /** @return array{triggers: list<array<string, mixed>>, variables: array<string, mixed>} */
25    public function encodeValue(object $value): array
26    {
27        \assert($value instanceof TriggerSpec);
28
29        return ['triggers' => $value->listTriggerConfigs(), 'variables' => $value->variables];
30    }
31
32    /** @throws JsonShapeException */
33    public function decodeValue(mixed $value, string $path): TriggerSpec
34    {
35        if (!\is_array($value)) {
36            throw JsonShapeException::wrongType($path, 'an object', get_debug_type($value));
37        }
38
39        $triggers = $value['triggers'] ?? null;
40        $variables = $value['variables'] ?? null;
41
42        if (!\is_array($triggers) || !array_is_list($triggers)) {
43            throw JsonShapeException::wrongType($path . '.triggers', 'a list', get_debug_type($triggers));
44        }
45
46        if (!\is_array($variables)) {
47            throw JsonShapeException::wrongType($path . '.variables', 'an object', get_debug_type($variables));
48        }
49
50        try {
51            return TriggerSpec::fromSpec($triggers, $variables);
52        } catch (TriggerException $e) {
53            throw JsonShapeException::unexpectedValue($path, 'valid Home Assistant triggers', $e->getMessage());
54        }
55    }
56}