Lines
100.00%
14 / 14
Functions and Methods
100.00%
2 / 2
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ComponentEventDecoder | 100.00% | 14 / 14 | 100.00% | 2 / 2 | 15 | 100.00% | 1 / 1 | |||
| decodeSessionEvent | 100.00% | 5 / 5 | 100.00% | 1 / 1 | 5 | |||||
| decodeCommand | 100.00% | 9 / 9 | 100.00% | 1 / 1 | 10 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Client\Component; | |
| 6 | ||
| 7 | use Stewart\Contracts\App\AppId; | |
| 8 | use Stewart\Contracts\Exposure\ExposedEntityKey; | |
| 9 | use Stewart\Contracts\State\EventContext; | |
| 10 | ||
| 11 | final readonly class ComponentEventDecoder | |
| 12 | { | |
| 13 | private const string SESSION_REPLACED = 'session_replaced'; | |
| 14 | ||
| 15 | private const string SESSION_ENDED = 'session_ended'; | |
| 16 | ||
| 17 | private const string COMMAND = 'command'; | |
| 18 | ||
| 19 | /** @param array<string, mixed> $event */ | |
| 20 | public function decodeSessionEvent(array $event): ?ComponentSessionEvent | |
| 21 | { | |
| 22 | return match ($event['type'] ?? null) { | |
| 23 | self::SESSION_REPLACED => new SessionReplaced(), | |
| 24 | self::SESSION_ENDED => new SessionEnded(), | |
| 25 | self::COMMAND => $this->decodeCommand($event), | |
| 26 | default => null, | |
| 27 | }; | |
| 28 | } | |
| 29 | ||
| 30 | /** @param array<string, mixed> $event */ | |
| 31 | private function decodeCommand(array $event): ?ComponentCommand | |
| 32 | { | |
| 33 | $commandId = $event['command_id'] ?? null; | |
| 34 | $appId = \is_string($event['app'] ?? null) ? AppId::tryFromString($event['app']) : null; | |
| 35 | $key = \is_string($event['key'] ?? null) ? ExposedEntityKey::tryFromString($event['key']) : null; | |
| 36 | $action = \is_string($event['action'] ?? null) ? ComponentCommandAction::tryFrom($event['action']) : null; | |
| 37 | $data = $event['data'] ?? null; | |
| 38 | $context = $event['context'] ?? null; | |
| 39 | ||
| 40 | if (!\is_string($commandId) || $appId === null || $key === null || $action === null || !\is_array($data) || !\is_array($context)) { | |
| 41 | return null; | |
| 42 | } | |
| 43 | ||
| 44 | /** @var array<string, mixed> $data */ | |
| 45 | return new ComponentCommand($commandId, $appId, $key, $action, $data, EventContext::fromArray($context)); | |
| 46 | } | |
| 47 | } |