Lines
85.71%
6 / 7
Functions and Methods
75.00%
3 / 4
Classes and Traits
0.00%
0 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| HistoryRequestHandler | 85.71% | 6 / 7 | 75.00% | 3 / 4 | 5.07 | 0.00% | 0 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| handledMessageClass | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | |||||
| handle | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| fetchFromHomeAssistant | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Broker\Message; | |
| 6 | ||
| 7 | use Stewart\Client\HaClient; | |
| 8 | use Stewart\Contracts\Exception\HistoryException; | |
| 9 | use Stewart\Runtime\Broker\HaCallSlots; | |
| 10 | use Stewart\Runtime\Broker\HaSession; | |
| 11 | use Stewart\Runtime\Broker\WorkerHandle; | |
| 12 | use Stewart\Runtime\Ipc\Message\HistoryRequest; | |
| 13 | use Stewart\Runtime\Ipc\Message\HistoryResult; | |
| 14 | use Stewart\Runtime\Ipc\Message\WorkerMessage; | |
| 15 | use Stewart\Runtime\Ipc\Wire\HistoricalStatesFragment; | |
| 16 | ||
| 17 | /** @implements WorkerMessageHandler<HistoryRequest> */ | |
| 18 | final readonly class HistoryRequestHandler implements WorkerMessageHandler | |
| 19 | { | |
| 20 | public function __construct( | |
| 21 | private HaSession $session, | |
| 22 | private HaClient $client, | |
| 23 | private HaCallSlots $slots, | |
| 24 | ) {} | |
| 25 | ||
| 26 | public function handledMessageClass(): string | |
| 27 | { | |
| 28 | return HistoryRequest::class; | |
| 29 | } | |
| 30 | ||
| 31 | /** @param HistoryRequest $message */ | |
| 32 | public function handle(WorkerHandle $handle, WorkerMessage $message): void | |
| 33 | { | |
| 34 | $this->slots->runBounded($handle, $message, fn(): HistoryResult => $this->fetchFromHomeAssistant($message), metered: false); | |
| 35 | } | |
| 36 | ||
| 37 | /** @throws HistoryException */ | |
| 38 | private function fetchFromHomeAssistant(HistoryRequest $request): HistoryResult | |
| 39 | { | |
| 40 | if (!$this->session->isConnected()) { | |
| 41 | throw $request->createUnreachableFailure('Home Assistant is disconnected'); | |
| 42 | } | |
| 43 | ||
| 44 | $history = $this->client->fetchHistory($request->entityId, $request->window, $request->detail); | |
| 45 | ||
| 46 | return new HistoryResult($request->correlationId, HistoricalStatesFragment::fromCollection($history->states)); | |
| 47 | } | |
| 48 | } |