Lines 100.00% 13 / 13
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
DoctorCommand 100.00% 13 / 13 100.00% 3 / 3 8 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 configure 100.00% 2 / 2 100.00% 1 / 1 1
 execute 100.00% 10 / 10 100.00% 1 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console;
6
7use Stewart\Runtime\Console\Doctor\ConnectionChecks;
8use Stewart\Runtime\Console\Doctor\ContainerChecks;
9use Stewart\Runtime\Console\Doctor\DoctorOutcome;
10use Symfony\Component\Console\Attribute\AsCommand;
11use Symfony\Component\Console\Command\Command;
12use Symfony\Component\Console\Input\InputInterface;
13use Symfony\Component\Console\Input\InputOption;
14use Symfony\Component\Console\Output\OutputInterface;
15
16#[AsCommand(name: self::NAME, description: 'Check that this PHP can run Stewart, and that it reaches Home Assistant and the store')]
17final class DoctorCommand extends StewartCommand
18{
19    public const string NAME = 'doctor';
20
21    private const string OFFLINE_OPTION = 'offline';
22
23    public function __construct(
24        private readonly ContainerChecks $containerChecks,
25        private readonly ConnectionChecks $connectionChecks,
26    ) {
27        parent::__construct();
28    }
29
30    protected function configure(): void
31    {
32        parent::configure();
33        $this->addOption(self::OFFLINE_OPTION, null, InputOption::VALUE_NONE, 'Check only this container, not the settings and connections');
34    }
35
36    protected function execute(InputInterface $input, OutputInterface $output): int
37    {
38        // Composer's platform check already refused an older PHP before this command could load.
39        $output->writeln(\sprintf('PHP %s (%s)', \PHP_VERSION, \PHP_BINARY));
40        $findings = $this->containerChecks->runContainerChecks();
41
42        if ($input->getOption(self::OFFLINE_OPTION) !== true) {
43            array_push($findings, ...$this->connectionChecks->runConnectionChecks($this->findConfigOption($input)));
44        }
45
46        $healthy = true;
47
48        foreach ($findings as $finding) {
49            $output->writeln(rtrim(\sprintf('  %-12s %s  %s', $finding->label, $finding->outcome->getMark(), $finding->detail)));
50            $healthy = $healthy && $finding->outcome !== DoctorOutcome::Fail;
51        }
52
53        $output->writeln($healthy ? 'All good.' : 'Problems found.');
54
55        return $healthy ? Command::SUCCESS : Command::FAILURE;
56    }
57}