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

dg / dresscode / 41044778467

30 Oct 2026 10:08AM UTC coverage: 97.234% (-0.3%) from 97.495%
41044778467

push

github

dg
upgrade: a decision only the data of the target version turn on belongs to the jump, the project as it is today resolved without narrowing, so that the plan no longer fixes it in the bridge, where nothing runs it

837123ff-7353-45e9-8cd7-ba68b373e93e

5 of 5 new or added lines in 1 file covered. (100.0%)

160 existing lines in 33 files now uncovered.

27315 of 28092 relevant lines covered (97.23%)

0.97 hits per line

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

98.67
/src/Measuring/Scope.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\Config;
11
use DressCode\Config\{ComposerJson, RunnerFactory};
12
use DressCode\Engine\Helpers;
13
use DressCode\Interop\FormatterConfig;
14
use Nette\Utils\Finder;
15
use function count;
16
use const PHP_OS_FAMILY;
17

18

19
/**
20
 * The files `dresscode init` measures and writes the configuration for, as `dresscode import` writes it too, and those
21
 * it leaves out with the reason. With git the scope is what the repository tracks under the root, or under the paths
22
 * the formatter of the project checks; without it, what the autoload and the usual directories hold. Either way a file
23
 * a generator wrote and the data of tests are left out, and whatever the defaults exclude.
24
 * @internal
25
 */
26
final class Scope
27
{
28
        /**
29
         * Where the code of a project usually is, beside what the autoload says: the test suites the autoload-dev
30
         * rarely names and the entry points it cannot name at all. A name with a `*` is a pattern of the root.
31
         */
32
        public const Paths = ['src', 'tests', 'test', 'app', 'lib', 'bin', 'cron', 'www*'];
33

34
        /** the extensions of the code of a project, a test in the format PHPT being left out by its head */
35
        public const Extensions = ['php', 'phpt'];
36

37
        /** directories of the data of tests, which carry the style a test needs; a name stands for a segment at any depth */
38
        public const TestDataDirs = ['fixtures', 'Fixtures', 'expected'];
39

40
        /** @var ?array<string, string>  what `listExcludePaths()` gives, until the scope changes */
41
        private ?array $excluded = null;
42

43

44
        private function __construct(
45
                /** @var list<string>  sorted, relative to the root */
46
                public private(set) array $files,
1 ✔
47
                /** @var array<string, LeftOutReason>  file or directory relative to the root => why it is left out */
48
                public private(set) array $leftOut,
1 ✔
49
                /** @var ?list<string>  the paths the scope is written as; null for the entries of the root that hold its files */
50
                private readonly ?array $paths,
1 ✔
51
        ) {
52
        }
1 ✔
53

54

55
        /**
56
         * The files of the extensions the repository tracks under the root, those the default exclusions name dropped without a
57
         * word, and the directories and files git ignores that hold PHP; null where there is no git, the root lies in no
58
         * repository or the repository tracks none of its code, as a project in a directory another repository ignores. With
59
         * the paths given, only what lies under them, the scope written as those paths.
60
         * @param  list<string>  $extensions
61
         * @param  ?list<string>  $paths
62
         */
63
        public static function fromGit(string $root, array $extensions, ?array $paths = null): ?self
64
        {
65
                $tracked = self::runGit($root, ['ls-files', '-z', '--', ...array_map(fn(string $ext) => "*.$ext", $extensions)]);
1 ✔
66
                if ($tracked === null || $tracked === '') {
1 ✔
67
                        return null;
1 ✔
68
                }
69

70
                $under = fn(string $file) => $paths === null
1 ✔
71
                        || array_any($paths, fn(string $path) => $file === $path || str_starts_with($file, "$path/"));
1 ✔
72
                $files = array_values(array_filter(
1 ✔
73
                        explode("\0", $tracked),
1 ✔
74
                        fn(string $file) => $file !== ''
1 ✔
75
                                && $under($file)
1 ✔
76
                                && !Helpers::matchesAny(Config::DefaultExcludePaths, $file)
1 ✔
77
                                && is_file("$root/$file"),
1 ✔
78
                ));
79
                sort($files, SORT_STRING);
1 ✔
80
                [$files, $leftOut] = self::sortOut($root, $files, self::findGeneratedAttribute($root, $files));
1 ✔
81

82
                $ignored = self::runGit($root, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']) ?? '';
1 ✔
83
                foreach (explode("\0", $ignored) as $entry) {
1 ✔
84
                        $entry = rtrim($entry, '/');
1 ✔
85
                        if (
86
                                $entry !== ''
1 ✔
87
                                && $under($entry)
1 ✔
88
                                && !Helpers::matchesAny(Config::DefaultExcludePaths, $entry)
1 ✔
89
                                && self::holdsCode("$root/$entry", $extensions)
1 ✔
90
                        ) {
91
                                $leftOut[$entry] = LeftOutReason::Ignored;
1 ✔
92
                        }
93
                }
94

95
                return new self($files, $leftOut, $paths);
1 ✔
96
        }
97

98

99
        /**
100
         * The files of the extensions in the directories the autoload of the project names and in the usual ones beside them,
101
         * for a project without git.
102
         * @param  list<string>  $extensions
103
         */
104
        public static function fromAutoload(string $root, array $extensions): self
105
        {
106
                return self::fromPaths($root, self::findAutoloadPaths($root), $extensions);
1 ✔
107
        }
108

109

110
        /**
111
         * The scope of a project: what its formatter checks where its configuration names the paths, else what git tracks,
112
         * else what the autoload names, without what the formatter leaves out.
113
         */
114
        public static function fromProject(string $root, ?FormatterConfig $formatterConfig): self
115
        {
116
                $paths = $formatterConfig?->paths ?: null;
1 ✔
117
                $scope = self::fromGit($root, self::Extensions, $paths)
1 ✔
118
                        ?? ($paths === null ? self::fromAutoload($root, self::Extensions) : self::fromPaths($root, $paths, self::Extensions));
1 ✔
119
                if ($formatterConfig !== null) {
1 ✔
120
                        $scope->leaveOut(fn(string $file) => $formatterConfig->excludes($file));
1 ✔
121
                }
122

123
                return $scope;
1 ✔
124
        }
125

126

127
        /**
128
         * The files of the extensions under the paths given.
129
         * @param  list<string>  $paths
130
         * @param  list<string>  $extensions
131
         */
132
        public static function fromPaths(string $root, array $paths, array $extensions): self
133
        {
134
                $factory = new RunnerFactory;
1 ✔
135
                $runner = $factory->createRunner($factory->resolve(new Config(fileExtensions: $extensions), $root), cache: false);
1 ✔
136
                [$files, $leftOut] = self::sortOut($root, $runner->findFiles($paths), []);
1 ✔
137
                return new self($files, $leftOut, $paths);
1 ✔
138
        }
139

140

141
        /**
142
         * The directories the autoload of the project names, the usual ones the root has besides them, and the root itself
143
         * when neither says anything. A directory that lies in another one is already in the scope, and one that does not
144
         * exist would only make the run throw.
145
         * @return list<string>
146
         */
147
        private static function findAutoloadPaths(string $root): array
148
        {
149
                $paths = ComposerJson::detectAutoloadPaths(ComposerJson::findFile($root), $root);
1 ✔
150
                foreach (self::Paths as $name) {
1 ✔
151
                        // a pattern is matched against the names of the root, never against a path of its own, or a root
152
                        // holding a bracket or a star would be part of the pattern and quietly match nothing
153
                        $found = str_contains($name, '*')
1 ✔
154
                                ? array_values(array_filter(scandir($root) ?: [], fn(string $entry) => fnmatch($name, $entry) && is_dir("$root/$entry")))
1 ✔
155
                                : (is_dir("$root/$name") ? [$name] : []);
1 ✔
156
                        $paths = [...$paths, ...$found];
1 ✔
157
                }
158

159
                $scope = [];
1 ✔
160
                foreach (array_unique($paths) as $path) {
1 ✔
161
                        foreach ($paths as $other) {
1 ✔
162
                                if ($other !== $path && ($other === '.' || str_starts_with("$path/", "$other/"))) {
1 ✔
163
                                        continue 2;
1 ✔
164
                                }
165
                        }
166

167
                        $scope[] = $path;
1 ✔
168
                }
169

170
                sort($scope, SORT_STRING);
1 ✔
171
                return $scope ?: ['.'];
1 ✔
172
        }
173

174

175
        /**
176
         * The files of the scope and those left out of it for being a test in the format PHPT, which is no PHP, the data of
177
         * tests or written by a generator.
178
         * @param  list<string>  $files
179
         * @param  array<string, true>  $generated  the files `.gitattributes` marks as generated
180
         * @return array{list<string>, array<string, LeftOutReason>}
181
         */
182
        private static function sortOut(string $root, array $files, array $generated): array
183
        {
184
                $kept = $leftOut = [];
1 ✔
185
                foreach ($files as $file) {
1 ✔
186
                        $reason = match (true) {
1 ✔
187
                                str_ends_with($file, '.phpt') && self::isPhptTest("$root/$file") => LeftOutReason::PhptTest,
1 ✔
188
                                array_intersect(self::TestDataDirs, explode('/', $file)) !== [] => LeftOutReason::TestData,
1 ✔
189
                                isset($generated[$file]) || FileSample::isGenerated("$root/$file") => LeftOutReason::Generated,
1 ✔
190
                                default => null,
1 ✔
191
                        };
192
                        if ($reason === null) {
1 ✔
193
                                $kept[] = $file;
1 ✔
194
                        } else {
195
                                $leftOut[$file] = $reason;
1 ✔
196
                        }
197
                }
198

199
                return [$kept, $leftOut];
1 ✔
200
        }
201

202

203
        /** Whether the head of the file has a line of a section of PHPT, `--FILE--`, which no PHP file starts with. */
204
        private static function isPhptTest(string $file): bool
205
        {
206
                $head = @file_get_contents($file, length: 1024); // @ file may have been deleted meanwhile
1 ✔
207
                return $head !== false && preg_match('~^--[A-Z][A-Z_]*--\r?$~m', $head) === 1;
1 ✔
208
        }
209

210

211
        /**
212
         * The extensions of the files of the scope, `php` first.
213
         * @return list<string>
214
         */
215
        public function listExtensions(): array
216
        {
217
                $extensions = array_unique(['php', ...array_map(fn(string $file) => pathinfo($file, PATHINFO_EXTENSION), $this->files)]);
1 ✔
218
                return array_values($extensions);
1 ✔
219
        }
220

221

222
        /** Whether the scope is all git tracks under the root, not narrowed to the paths of a formatter or of the autoload. */
223
        public function isTracked(): bool
224
        {
225
                return $this->paths === null;
1 ✔
226
        }
227

228

229
        /**
230
         * Leaves out the files the configuration of the formatter of the project leaves out.
231
         * @param  \Closure(string): bool  $excludes
232
         */
233
        public function leaveOut(\Closure $excludes): void
234
        {
235
                $foreign = array_filter($this->files, $excludes);
1 ✔
236
                $this->files = array_values(array_diff($this->files, $foreign));
1 ✔
237
                $this->leftOut += array_fill_keys($foreign, LeftOutReason::Foreign);
1 ✔
238
                $this->excluded = null;
1 ✔
239
        }
1 ✔
240

241

242
        /**
243
         * The files of the scope given as the paths a configuration names: the highest directory of which every file of the
244
         * scope is given, and a file where its directory holds others too.
245
         * @param  list<string>  $files
246
         * @return list<string>
247
         */
248
        public function collapse(array $files): array
249
        {
250
                $all = $given = [];
1 ✔
251
                $set = array_flip($files);
1 ✔
252
                foreach ($this->files as $file) {
1 ✔
253
                        for ($dir = dirname($file); $dir !== '.'; $dir = dirname($dir)) {
1 ✔
254
                                $all[$dir] = ($all[$dir] ?? 0) + 1;
1 ✔
255
                                $given[$dir] = ($given[$dir] ?? 0) + (int) isset($set[$file]);
1 ✔
256
                        }
257
                }
258

259
                $collapsed = [];
1 ✔
260
                foreach ($files as $entry) {
1 ✔
261
                        while (($dir = dirname($entry)) !== '.' && $given[$dir] === $all[$dir]) {
1 ✔
262
                                $entry = $dir;
1 ✔
263
                        }
264

265
                        $collapsed[$entry] = true;
1 ✔
266
                }
267

268
                $collapsed = array_keys($collapsed);
1 ✔
269
                sort($collapsed, SORT_STRING);
1 ✔
270
                return $collapsed;
1 ✔
271
        }
272

273

274
        /** Leaves out the files that do not parse, which a check of them tells. */
275
        public function markUnparsed(string ...$files): void
276
        {
277
                $unparsed = array_intersect($this->files, $files);
1 ✔
278
                $this->files = array_values(array_diff($this->files, $unparsed));
1 ✔
279
                $this->leftOut += array_fill_keys($unparsed, LeftOutReason::Unparsed);
1 ✔
280
                $this->excluded = null;
1 ✔
281
        }
1 ✔
282

283

284
        /**
285
         * The paths the configuration names: the entries of the root that hold a file of the scope, directories and files
286
         * alike, or what the autoload named.
287
         * @return list<string>
288
         */
289
        public function listPaths(): array
290
        {
291
                if ($this->paths !== null) {
1 ✔
292
                        return $this->paths;
1 ✔
293
                }
294

295
                $entries = array_values(array_unique(array_map(fn(string $file) => explode('/', $file, 2)[0], $this->files)));
1 ✔
296
                sort($entries, SORT_STRING);
1 ✔
297
                return $entries ?: ['.'];
1 ✔
298
        }
299

300

301
        /**
302
         * What the configuration excludes inside its paths, each with the reason: a directory of the data of tests by its
303
         * name, which stands for it at any depth, a directory where everything in it is generated, and a file otherwise.
304
         * @return array<string, string>  pattern => why
305
         */
306
        public function listExcludePaths(): array
307
        {
308
                if ($this->excluded !== null) {
1 ✔
309
                        return $this->excluded;
1 ✔
310
                }
311

312
                // the files below each directory, all and by reason; the ignored entries hold files git does not list
313
                $files = $byReason = [];
1 ✔
314
                foreach ([...$this->files, ...array_keys($this->leftOut)] as $file) {
1 ✔
315
                        $reason = $this->leftOut[$file] ?? null;
1 ✔
316
                        for ($dir = dirname($file); $reason !== LeftOutReason::Ignored && $dir !== '.'; $dir = dirname($dir)) {
1 ✔
317
                                $files[$dir] = ($files[$dir] ?? 0) + 1;
1 ✔
318
                                $key = $reason->name ?? '';
1 ✔
319
                                $byReason[$dir][$key] = ($byReason[$dir][$key] ?? 0) + 1;
1 ✔
320
                        }
321
                }
322

323
                $paths = $this->listPaths();
1 ✔
324
                $extensions = $this->listExtensions();
1 ✔
325
                $isInside = fn(string $path) => array_any($paths, fn(string $listed) => $listed === '.' || str_starts_with($path, "$listed/"));
1 ✔
326
                $excluded = [];
1 ✔
327
                foreach ($this->leftOut as $entry => $reason) {
1 ✔
328
                        // a file of an extension the configuration does not take needs no exclusion
329
                        $extension = pathinfo($entry, PATHINFO_EXTENSION);
1 ✔
330
                        if (!$isInside($entry) || ($extension !== '' && !in_array($extension, $extensions, true))) {
1 ✔
331
                                continue;
1 ✔
332
                        } elseif ($reason === LeftOutReason::TestData) {
1 ✔
333
                                $entry = array_find(explode('/', $entry), fn(string $segment) => in_array($segment, self::TestDataDirs, true)) ?? $entry;
1 ✔
334
                        }
335

336
                        // a file generated or left out by the formatter stands for the highest directory inside the paths whose every
337
                        // file is left out for the same reason
338
                        while (
339
                                ($reason === LeftOutReason::Generated || $reason === LeftOutReason::Foreign)
1 ✔
340
                                && $isInside($dir = dirname($entry))
1 ✔
341
                                && ($byReason[$dir][$reason->name] ?? 0) === $files[$dir]
1 ✔
342
                        ) {
343
                                $entry = $dir;
1 ✔
344
                        }
345

346
                        $excluded[$entry] = $reason->value;
1 ✔
347
                }
348

349
                ksort($excluded, SORT_STRING);
1 ✔
350
                return $this->excluded = $excluded;
1 ✔
351
        }
352

353

354
        /**
355
         * The files `linguist-generated` of the attributes of git marks.
356
         * @param  list<string>  $files
357
         * @return array<string, true>
358
         */
359
        private static function findGeneratedAttribute(string $root, array $files): array
360
        {
361
                $output = self::runGit($root, ['check-attr', '-z', '--stdin', 'linguist-generated'], implode("\0", $files));
1 ✔
362
                $fields = explode("\0", (string) $output);
1 ✔
363
                $generated = [];
1 ✔
364
                for ($i = 0; $i + 2 < count($fields); $i += 3) { // path, attribute, value
1 ✔
365
                        if ($fields[$i + 2] === 'set' || $fields[$i + 2] === 'true') {
1 ✔
366
                                $generated[$fields[$i]] = true;
1 ✔
367
                        }
368
                }
369

370
                return $generated;
1 ✔
371
        }
372

373

374
        /**
375
         * Whether the file is code of the extensions, or the directory holds some below the directories the defaults
376
         * exclude.
377
         * @param  list<string>  $extensions
378
         */
379
        private static function holdsCode(string $path, array $extensions): bool
380
        {
381
                if (is_file($path)) {
1 ✔
382
                        return in_array(pathinfo($path, PATHINFO_EXTENSION), $extensions, true);
1 ✔
383
                }
384

385
                $finder = Finder::findFiles(array_map(fn(string $ext) => "*.$ext", $extensions))
1 ✔
386
                        ->from($path)
1 ✔
387
                        ->descentFilter(fn(\SplFileInfo $dir) => !Helpers::matchesAny(Config::DefaultExcludePaths, $dir->getFilename()));
1 ✔
388
                foreach ($finder as $ignored) {
1 ✔
389
                        return true;
1 ✔
390
                }
391

UNCOV
392
                return false;
×
393
        }
394

395

396
        /**
397
         * What git writes for the command run in the root; null where it fails, the root lying in no repository or git
398
         * missing.
399
         * @param  list<string>  $args
400
         */
401
        private static function runGit(string $root, array $args, string $input = ''): ?string
402
        {
403
                $in = tmpfile();
1 ✔
404
                $out = tmpfile();
1 ✔
405
                if ($in === false || $out === false) {
1 ✔
UNCOV
406
                        return null;
×
407
                }
408

409
                fwrite($in, $input);
1 ✔
410
                rewind($in);
1 ✔
411
                $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';
1 ✔
412
                $process = @proc_open(['git', '-C', $root, ...$args], [0 => $in, 1 => $out, 2 => ['file', $null, 'w']], $pipes); // @ no git then
1 ✔
413
                if ($process === false || proc_close($process) !== 0) {
1 ✔
414
                        return null;
1 ✔
415
                }
416

417
                rewind($out);
1 ✔
418
                return (string) stream_get_contents($out);
1 ✔
419
        }
420
}
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