• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dg / dresscode / 42928114183

10 Nov 2026 11:30PM UTC coverage: 97.596% (+0.6%) from 97.024%
42928114183

push

github

dg
released version 1.4.0

27609 of 28289 relevant lines covered (97.6%)

0.98 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.44
/src/Measuring/ProcessProbeRunner.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the DressCode, a coding style and upgrade tool for PHP (https://dresscode.run)
5
 * Copyright (c) 2026 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace DressCode\Measuring;
9

10
use DressCode\Engine\{ProcessRunner, WorkerPool};
11
use Nette\Neon\Neon;
12
use Nette\Utils\FileSystem;
13
use function count, dirname, is_array;
14
use const PHP_OS_FAMILY;
15

16

17
/**
18
 * Runs the probes as processes of `check --format json`, as many at once as the machine has processors, the processors
19
 * shared among those running: a probe over a sample is cheaper alone in a process than with a pool of workers to start,
20
 * and a few probes over many files get the workers between them. The configurations lie in the system temp, never in
21
 * the project, and `--root` makes the project the root of the run. The script is always the one of this DressCode, and a
22
 * probe starts no probes of its own, so the processes never grow beyond one level, however the runner is called.
23
 * @internal
24
 */
25
final readonly class ProcessProbeRunner implements ProbeRunner
26
{
27
        /** how long the loop waits between two looks at the processes, in microseconds */
28
        private const PollInterval = 20_000;
29

30
        /** how long a probe may run, in seconds */
31
        private const Timeout = 1800;
32

33
        /** the variable of the environment a probe runs with */
34
        private const ProbeVariable = 'DRESSCODE_PROBE';
35

36

37
        public function __construct(
38
                private string $root,
1 ✔
39
                /** @var list<string>  the PHP and the script of DressCode */
40
                private array $command,
1 ✔
41
                private int $processors,
1 ✔
42
                /** @var ?\Closure(int, int): void  the probes done and all of them, told at every look while they run */
43
                private ?\Closure $onProgress = null,
1 ✔
44
        ) {
45
        }
1 ✔
46

47

48
        /**
49
         * @param  ?\Closure(int, int): void  $onProgress
50
         * @param  ?int  $processors  how many the probes share; all of the machine by default
51
         */
52
        public static function create(string $root, ?\Closure $onProgress = null, ?int $processors = null): self
53
        {
54
                $script = \Phar::running(returnPhar: false) ?: dirname(__DIR__, 2) . '/bin/dresscode';
1 ✔
55
                $command = [...WorkerPool::buildPhpCommand() ?? [PHP_BINARY], $script];
1 ✔
56
                return new self($root, $command, $processors ?? WorkerPool::detectCpuCount(), $onProgress);
1 ✔
57
        }
58

59

60
        public function run(array $probes): array
61
        {
62
                if (getenv(self::ProbeVariable) !== false) {
1 ✔
63
                        throw new \LogicException('A probe of `dresscode init` starts no probes of its own.');
1 ✔
64
                }
65

66
                $dir = sys_get_temp_dir() . '/dresscode-probes-' . uniqid(more_entropy: true);
1 ✔
67
                FileSystem::createDir($dir);
1 ✔
68
                $parallel = max(1, min($this->processors, count($probes)));
1 ✔
69
                $jobs = max(1, intdiv($this->processors, $parallel));
1 ✔
70
                $queue = array_keys($probes);
1 ✔
71
                $running = $results = [];
1 ✔
72
                try {
73
                        while ($queue || $running) {
1 ✔
74
                                while ($queue && count($running) < $parallel) {
1 ✔
75
                                        $key = array_shift($queue);
1 ✔
76
                                        $running[$key] = $this->start($probes[$key], $dir . '/' . md5((string) $key), $jobs);
1 ✔
77
                                }
78

79
                                foreach ($running as $key => [$process, $file, $started]) {
1 ✔
80
                                        // the exit code is told once, by the first look after the end, and proc_close() then has none
81
                                        $status = proc_get_status($process);
1 ✔
82
                                        if ($status['running'] && microtime(as_float: true) - $started > self::Timeout) {
1 ✔
83
                                                throw new \RuntimeException('A check of the measuring did not end within ' . self::Timeout / 60 . ' minutes.');
×
84
                                        } elseif ($status['running']) {
1 ✔
85
                                                continue;
1 ✔
86
                                        }
87

88
                                        proc_close($process);
1 ✔
89
                                        unset($running[$key]);
1 ✔
90
                                        $results[$key] = self::readResult($file, $status['exitcode']);
1 ✔
91
                                }
92

93
                                ($this->onProgress)?->__invoke(count($results), count($probes));
1 ✔
94
                                if ($running) {
1 ✔
95
                                        usleep(self::PollInterval);
1 ✔
96
                                }
97
                        }
98
                } finally {
1 ✔
99
                        foreach ($running as [$process]) {
1 ✔
100
                                ProcessRunner::killTree(proc_get_status($process)['pid']);
×
101
                                proc_close($process);
×
102
                        }
103

104
                        FileSystem::delete($dir);
1 ✔
105
                }
106

107
                return $results;
1 ✔
108
        }
109

110

111
        /**
112
         * @return array{resource, string, float}  the process, the base name of its files and when it started
113
         */
114
        private function start(Probe $probe, string $file, int $jobs): array
115
        {
116
                FileSystem::write("$file.neon", Neon::encode($probe->config, blockMode: true));
1 ✔
117
                $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';
1 ✔
118
                $process = proc_open(
1 ✔
119
                        [
120
                                ...$this->command,
1 ✔
121
                                'check',
1 ✔
122
                                '--format=json',
1 ✔
123
                                "--jobs=$jobs",
1 ✔
124
                                '--no-cache',
1 ✔
125
                                "--root=$this->root",
1 ✔
126
                                "--config=$file.neon",
1 ✔
127
                                ...array_map(fn(string $path) => "--only=$path", $probe->only),
1 ✔
128
                        ],
129
                        [0 => ['file', $null, 'r'], 1 => ['file', "$file.json", 'w'], 2 => ['file', "$file.err", 'w']],
1 ✔
130
                        $pipes,
131
                        $this->root,
1 ✔
132
                        [...getenv(), self::ProbeVariable => '1'],
1 ✔
133
                );
134
                if ($process === false) {
1 ✔
135
                        throw new \RuntimeException('A process of `check` could not be started.');
×
136
                }
137

138
                return [$process, $file, microtime(as_float: true)];
1 ✔
139
        }
140

141

142
        private static function readResult(string $file, int $exit): ProbeResult
143
        {
144
                $report = json_decode((string) @file_get_contents("$file.json"), associative: true); // @ written by the process
1 ✔
145
                if ($exit > 2 || !is_array($report) || !is_array($report['files'] ?? null)) { // 2 is a file a rule failed in, which the report carries
1 ✔
146
                        $error = trim((string) @file_get_contents("$file.err")); // @ written by the process
1 ✔
147
                        throw new \RuntimeException("A check of the measuring ended with exit code $exit: " . ($error ?: 'no output'));
1 ✔
148
                }
149

150
                return ProbeResult::fromJson($report);
1 ✔
151
        }
152
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc