Lines 90.47% 19 / 21
Functions and Methods 50.00% 2 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
UpdateEntityRegistryEntry 90.47% 19 / 21 50.00% 2 / 4 14.17 0.00% 0 / 1
 __construct 100.00% 2 / 2 100.00% 1 / 1 2
 type 0.00% 0 / 1 0.00% 0 / 1 2
 describe 0.00% 0 / 1 0.00% 0 / 1 2
 toMessage 100.00% 17 / 17 100.00% 1 / 1 10
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Client\Connection\Command;
6
7use LogicException;
8use Stewart\Contracts\Entity\EntityId;
9use Stewart\Contracts\Registry\EntityAlias;
10use Stewart\Contracts\Registry\LabelId;
11use Stewart\Contracts\Registry\Update\EntityRegistryUpdate;
12
13final readonly class UpdateEntityRegistryEntry implements HaCommand
14{
15    public function __construct(
16        public EntityId $entityId,
17        public EntityRegistryUpdate $update,
18    ) {
19        if ($update->needsCurrentEntry()) {
20            throw new LogicException('Resolve added and removed labels and aliases against the current entry before sending.');
21        }
22    }
23
24    public function type(): string
25    {
26        return 'config/entity_registry/update';
27    }
28
29    public function describe(): string
30    {
31        return \sprintf('%s %s', $this->type(), $this->entityId->value);
32    }
33
34    public function toMessage(): array
35    {
36        $update = $this->update;
37        $message = ['type' => $this->type(), 'entity_id' => $this->entityId->value];
38
39        if ($update->name !== null) {
40            $message['name'] = $update->name->name;
41        }
42
43        if ($update->icon !== null) {
44            $message['icon'] = $update->icon->icon;
45        }
46
47        if ($update->area !== null) {
48            $message['area_id'] = $update->area->areaId?->value;
49        }
50
51        if ($update->labels?->replacement !== null) {
52            $message['labels'] = array_map(static fn(LabelId $labelId): string => $labelId->value, $update->labels->replacement);
53        }
54
55        if ($update->aliases?->replacement !== null) {
56            $message['aliases'] = array_map(static fn(EntityAlias $alias): ?string => $alias->phrase, $update->aliases->replacement);
57        }
58
59        if ($update->hidden !== null) {
60            $message['hidden_by'] = $update->hidden ? EntityRegistryUpdate::CHANGED_BY_USER : null;
61        }
62
63        if ($update->disabled !== null) {
64            $message['disabled_by'] = $update->disabled ? EntityRegistryUpdate::CHANGED_BY_USER : null;
65        }
66
67        return $message;
68    }
69}