Lines
100.00%
17 / 17
Functions and Methods
100.00%
3 / 3
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| HaClientSnapshotFetcher | 100.00% | 17 / 17 | 100.00% | 3 / 3 | 5 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| fetchSnapshot | 100.00% | 13 / 13 | 100.00% | 1 / 1 | 1 | |||||
| refuseUnlessRunning | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 3 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Codegen\Snapshot; | |
| 6 | ||
| 7 | use Psr\Log\LoggerInterface; | |
| 8 | use Stewart\Client\Connection\ConnectionConfig; | |
| 9 | use Stewart\Client\HaClientFactory; | |
| 10 | use Stewart\Client\HaConfig; | |
| 11 | use Stewart\Client\HaCoreState; | |
| 12 | use Stewart\Codegen\Exception\CodegenError; | |
| 13 | use Stewart\Codegen\Exception\CodegenException; | |
| 14 | ||
| 15 | final readonly class HaClientSnapshotFetcher implements SnapshotFetcher | |
| 16 | { | |
| 17 | public function __construct(private HaClientFactory $haClientFactory) {} | |
| 18 | ||
| 19 | public function fetchSnapshot(ConnectionConfig $connection, LoggerInterface $logger): Snapshot | |
| 20 | { | |
| 21 | $client = $this->haClientFactory->createClient($connection, $logger); | |
| 22 | $client->connect(); | |
| 23 | ||
| 24 | try { | |
| 25 | $this->refuseUnlessRunning($client->getConfig()); | |
| 26 | ||
| 27 | return Snapshot::fromParts( | |
| 28 | haVersion: $client->getHaVersion() ?? 'unknown', | |
| 29 | states: $client->getStates(), | |
| 30 | registry: $client->getEntityRegistry(), | |
| 31 | services: $client->getServices(), | |
| 32 | areas: $client->getAreaRegistry(), | |
| 33 | floors: $client->getFloorRegistry(), | |
| 34 | labels: $client->getLabelRegistry(), | |
| 35 | ); | |
| 36 | } finally { | |
| 37 | $client->close(); | |
| 38 | } | |
| 39 | } | |
| 40 | ||
| 41 | /** @throws CodegenException */ | |
| 42 | private function refuseUnlessRunning(HaConfig $config): void | |
| 43 | { | |
| 44 | $state = $config->coreState; | |
| 45 | ||
| 46 | if ($state !== null && $state !== HaCoreState::Running) { | |
| 47 | throw CodegenException::createForReason(CodegenError::HomeAssistantNotRunning, state: $state->value); | |
| 48 | } | |
| 49 | } | |
| 50 | } |