Lines 85.71% 18 / 21
Methods 0.00% 0 / 2
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 runContainerChecks 85.71% 12 / 14 0.00% 0 / 1 9.24
 canBindUnixSocket 85.71% 6 / 7 0.00% 0 / 1 2.01
7final readonly class ContainerChecks
8{
9    private const array REQUIRED_EXTENSIONS = [
10        'pcntl' => 'signal handling; without it graceful shutdown is impossible',
11        'json' => 'Home Assistant wire format',
12        'ctype' => 'config and cpu-count parsing',
13    ];
14
15    private const string PROBE_SOCKET_PREFIX = '/stewart-doctor-';
16
17    /** @return list<DoctorFinding> */
18    public function runContainerChecks(): array
19    {
20        $findings = [];
21
22        foreach (self::REQUIRED_EXTENSIONS as $extension => $purpose) {
23            $findings[] = \extension_loaded($extension) ? new DoctorFinding($extension, DoctorOutcome::Pass) : new DoctorFinding($extension, DoctorOutcome::Fail, $purpose);
24        }
25
26        $findings[] = new DoctorFinding('zlib', DoctorOutcome::Pass, \extension_loaded('zlib') ? 'websocket compression on' : 'absent; websocket compression off');
27        $findings[] = new DoctorFinding('xdebug', DoctorOutcome::Pass, \extension_loaded('xdebug') ? 'loaded, mode=' . (\ini_get('xdebug.mode') ?: 'off') : 'absent (fine for production)');
28
29        $temporaryDirectory = sys_get_temp_dir();
30        $findings[] = is_dir($temporaryDirectory) && is_writable($temporaryDirectory)
31            ? new DoctorFinding('tmpdir', DoctorOutcome::Pass, $temporaryDirectory)
32            : new DoctorFinding('tmpdir', DoctorOutcome::Fail, $temporaryDirectory . ' is not writable');
33        $findings[] = $this->canBindUnixSocket($temporaryDirectory)
34            ? new DoctorFinding('unix sock', DoctorOutcome::Pass, 'can bind')
35            : new DoctorFinding('unix sock', DoctorOutcome::Fail, 'cannot bind; workers will not spawn');
36        $findings[] = new DoctorFinding('memory', DoctorOutcome::Pass, (string) \ini_get('memory_limit'));
37
38        return $findings;
39    }
40
41    private function canBindUnixSocket(string $directory): bool
42    {
43        $path = $directory . self::PROBE_SOCKET_PREFIX . getmypid() . '.sock';
44        $server = @stream_socket_server('unix://' . $path);
45
46        if ($server === false) {
47            return false;
48        }
49
50        fclose($server);
51        @unlink($path);
52
53        return true;
54    }
55}