Lines 100.00% 9 / 9
Functions and Methods 100.00% 1 / 1
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ExposedEntitySnapshotReader 100.00% 9 / 9 100.00% 1 / 1 7 100.00% 1 / 1
 readUpsertResult 100.00% 9 / 9 100.00% 1 / 1 7
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Client\Component;
6
7use Stewart\Client\Exception\HaClientException;
8use Stewart\Contracts\Entity\EntityId;
9use Stewart\Contracts\Exception\IdentifierException;
10use Stewart\Contracts\Exposure\ExposedEntitySnapshot;
11use Stewart\Contracts\Exposure\ExposedState;
12use Stewart\Support\Json\JsonShape;
13
14final class ExposedEntitySnapshotReader
15{
16    /**
17     * @param array<array-key, mixed> $result
18     * @throws HaClientException
19     */
20    public static function readUpsertResult(array $result): ExposedEntitySnapshot
21    {
22        $entityId = $result['entity_id'] ?? null;
23        $state = $result['state'] ?? null;
24        $attributes = $result['attributes'] ?? null;
25        $available = $result['available'] ?? null;
26
27        if (!\is_string($entityId) || !\is_array($attributes) || !\is_bool($available) || !(\is_scalar($state) || $state === null)) {
28            throw HaClientException::protocolViolation('a stewart/entity/upsert result without entity_id, state, attributes and available');
29        }
30
31        try {
32            return new ExposedEntitySnapshot(new EntityId($entityId), new ExposedState($state), JsonShape::treatKeysAsStrings($attributes), $available);
33        } catch (IdentifierException $e) {
34            throw HaClientException::protocolViolation('a stewart/entity/upsert result with an invalid entity_id', $e);
35        }
36    }
37}