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

dg / dresscode / 42040857956

05 Nov 2026 12:36PM UTC coverage: 97.783% (+0.7%) from 97.051%
42040857956

push

github

dg
PhpStan: the types take the extensions of the project

The extensions were those phpstan/extension-installer registered in the installation DressCode runs from, so the types
depended on how DressCode was installed. A global one saw none, and reported a null from preg_replace() that the PHPStan
of a project with nette/phpstan-rules does not see, where the fix it offers fails that PHPStan; one made by
composer create-project brought its own nette/phpstan-rules into every project.

Now they are what the installer of the project includes, read from its installed.json, and only the classes of the
extensions are loaded from its vendor, the process keeping the packages of its own installation. This also lets an
extension that phpstan.neon includes by a path into vendor start.

1a3eaac4-d0da-4312-8c24-b7fb27c7b977

34 of 34 new or added lines in 3 files covered. (100.0%)

188 existing lines in 44 files now uncovered.

23290 of 23818 relevant lines covered (97.78%)

0.98 hits per line

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

98.18
/src/Engine/PassLoop.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\Engine;
9

10
use DressCode\{
11
        Analyses, ConfigurationException, ConvergenceException, NodeRule, Rule,
12
        RuleContext, RuleException, RuleInfo, Severity, Stage, Style, Violation,
13
};
14
use DressCode\Engine\Gaps\{Fixer, Resolver};
15
use PhpSyntax\{Node, Printer, Token, Traverser, Trivia};
16
use PhpSyntax\Nodes\FileNode;
17
use function count, strlen;
18

19

20
/**
21
 * Runs the rules over a file in passes until nothing mutates: each pass is one pre-order traversal per stage,
22
 * rules are dispatched by the type of the node or token, every mutation is paired with a report.
23
 * @internal
24
 */
25
final class PassLoop
26
{
27
        private const MaxPasses = 10;
28

29
        /**
30
         * @var array<string, array<class-string, list<array{NodeRule, RuleContext, class-string<NodeRule>}>>>  stage => node class =>
31
         * rules entering it, with their contexts and names
32
         */
33
        private array $entering = [];
34

35
        /** @var array<string, array<class-string, list<array{NodeRule, RuleContext, class-string<NodeRule>}>>>  the same for `leave()` */
36
        private array $leaving = [];
37

38
        /** @var array<class-string<Rule>, RuleContext> */
39
        private array $contexts = [];
40

41
        /** the gap rules, applied together along the traversal of the formatting stage */
42
        private readonly Resolver $gaps;
43

44
        /** @var array<class-string<Rule>, true>  rules that mutated the file in the current pass */
45
        private array $mutatedRules = [];
46

47
        /** @var array<string, Violation>  by fingerprint, so that a pass repeating a report adds nothing */
48
        private array $violations = [];
49

50
        /**
51
         * @var \WeakMap<Token, string>  a token whose line the fixer opened or closed => the fingerprint of the violation
52
         * it did it for, the first of its chain
53
         */
54
        private \WeakMap $opened;
55

56
        /** @var \WeakMap<Token, string>  a token whose line a rule moved => the fingerprint of the violation the move follows from */
57
        private \WeakMap $moved;
58

59
        /** @var list<array{string, Report, Severity}>  the reports of violations of the current pass: the rule, the report, its severity */
60
        private array $reported = [];
61

62
        /** @var list<string> */
63
        private array $warnings = [];
64

65
        private Fingerprints $fingerprints;
66

67
        /** @var list<int>  byte offset of the start of each line of the original code */
68
        private array $lineOffsets = [];
69
        private string $code = '';
70

71
        private FileNode $file;
72
        private string $path = '';
73

74

75
        public function __construct(
76
                private readonly RulePlan $plan,
1 ✔
77
                private readonly Analyses\Registry $analyses,
1 ✔
78
                private readonly ReportPolicy $policy = new ReportPolicy,
1 ✔
79
        ) {
80
                $this->gaps = new Resolver($plan->claims);
1 ✔
81
        }
1 ✔
82

83

84
        /**
85
         * @param  array<string, true>  $acceptedRisks  fingerprints of the occurrences whose fix that may change what the code does is allowed
86
         * @throws RuleException|ConvergenceException|ConfigurationException
87
         */
88
        public function run(FileNode $file, string $code, string $path, Style $style, string $phpVersion, array $acceptedRisks = []): PassResult
89
        {
90
                $this->file = $file;
1 ✔
91
                $this->path = $path;
1 ✔
92
                $this->code = $code;
1 ✔
93
                $split = (array) preg_split('~\r\n|\r|\n~', $code, -1, PREG_SPLIT_OFFSET_CAPTURE);
1 ✔
94
                $lines = array_column($split, 0);
1 ✔
95
                $this->lineOffsets = array_column($split, 1);
1 ✔
96
                $this->violations = $this->warnings = $this->contexts = $this->entering = $this->leaving = [];
1 ✔
97
                $this->opened = new \WeakMap;
1 ✔
98
                $this->moved = new \WeakMap;
1 ✔
99
                $this->fingerprints = new Fingerprints($lines, $path, $this->policy->baseline);
1 ✔
100
                $suppression = Suppression::fromFile($file, $this->policy->expandName, $code, $this->policy->suppressionComments);
1 ✔
101
                foreach ($suppression->getUnknownNames() as $name => $comment) {
1 ✔
UNCOV
102
                        $this->warnings[] = 'Comment '
×
103
                                . Violation::formatCode($comment)
×
104
                                . " names `$name`, which is no decision, section or rule, so it silences nothing.";
×
105
                }
106

107
                $spans = new Spans($code);
1 ✔
108
                foreach ($this->plan->rules as $rule) {
1 ✔
109
                        $ruleClass = $rule::class;
1 ✔
110
                        $this->contexts[$ruleClass] = new RuleContext(
1 ✔
111
                                $file,
1 ✔
112
                                $path,
113
                                $style,
114
                                $phpVersion,
115
                                $this->analyses,
1 ✔
116
                                $suppression,
117
                                $this->fingerprints,
1 ✔
118
                                $acceptedRisks,
119
                                $this->policy,
1 ✔
120
                                $this->plan->gates[$ruleClass],
1 ✔
121
                                RuleInfo::fromRule($rule),
1 ✔
122
                                $spans,
123
                        );
124
                }
125

126
                $seen = [hash('xxh3', $code) => true];
1 ✔
127
                $last = $code;
1 ✔
128
                $passes = 0;
1 ✔
129
                $mutated = false;
1 ✔
130
                $mutatedRules = [];
1 ✔
131
                while (true) {
1 ✔
132
                        if ($passes++ === self::MaxPasses) {
1 ✔
133
                                throw new ConvergenceException($path, array_keys($this->mutatedRules), '');
1 ✔
134
                        }
135

136
                        $this->mutatedRules = $this->reported = [];
1 ✔
137
                        $this->fingerprints->beginPass();
1 ✔
138
                        foreach ($this->contexts as $context) {
1 ✔
139
                                $context->passStorage = [];
1 ✔
140
                        }
141

142
                        $this->analyses->beginPass($file);
1 ✔
143
                        $revision = $file->revision;
1 ✔
144
                        foreach ($this->plan->stages as $stage => $rules) {
1 ✔
145
                                $this->runStage($stage, $rules, $style);
1 ✔
146
                        }
147

148
                        $failure = $this->analyses->findCreated($file, Analyses\Types::class)?->failure;
1 ✔
149
                        if ($failure !== null) {
1 ✔
150
                                $warning = "PHPStan fails on the file, so the rules asking for its types see none where it stopped: $failure";
1 ✔
151
                                $this->warnings = array_values(array_unique([...$this->warnings, $warning]));
1 ✔
152
                        }
153

154
                        if ($file->revision === $revision) {
1 ✔
155
                                $this->checkUnfixed();
1 ✔
156
                                break;
1 ✔
157
                        }
158

159
                        $mutated = true;
1 ✔
160
                        $mutatedRules += $this->mutatedRules;
1 ✔
161
                        $output = Printer::print($file);
1 ✔
162
                        $hash = hash('xxh3', $output);
1 ✔
163
                        if (isset($seen[$hash])) { // a state seen before: the rules cycle
1 ✔
164
                                throw new ConvergenceException($path, array_keys($this->mutatedRules), Diff::unified($last, $output, $path));
1 ✔
165
                        }
166

167
                        $seen[$hash] = true;
1 ✔
168
                        $last = $output;
1 ✔
169
                }
170

171
                $this->analyses->endFile($file);
1 ✔
172
                return new PassResult(
1 ✔
173
                        self::sortByPosition(array_values($this->violations)),
1 ✔
174
                        $this->warnings,
1 ✔
175
                        $passes,
176
                        $mutated,
177
                        $this->fingerprints->getBaselined(),
1 ✔
178
                        array_keys($mutatedRules),
1 ✔
179
                        // what the baseline holds is decided by the lines of the fixed text, which only another run has
180
                        remaining: $mutated && $this->policy->baseline === null ? $this->collectRemaining($last) : null,
1 ✔
181
                        output: $mutated ? $last : null,
1 ✔
182
                        removedImports: array_merge(
1 ✔
183
                                ...array_values(array_map(fn(RuleContext $context) => $context->takeRemovedImports(), $this->contexts)),
1 ✔
184
                        ),
185
                );
186
        }
187

188

189
        /**
190
         * The violations of the fixed text: what the last pass, which changed nothing, reported, identified by the lines
191
         * of that text as a run over it would identify them.
192
         * @return list<Violation>
193
         */
194
        private function collectRemaining(string $text): array
195
        {
196
                $fingerprints = new Fingerprints(preg_split('~\r\n|\r|\n~', $text) ?: [], $this->path);
1 ✔
197
                /** @var \WeakMap<Token, string> $opened */
198
                $opened = new \WeakMap;
1 ✔
199
                /** @var \WeakMap<Token, string> $moved */
200
                $moved = new \WeakMap;
1 ✔
201
                $violations = [];
1 ✔
202
                $spans = new Spans;
1 ✔
203
                foreach ($this->reported as [, $report, $severity]) {
1 ✔
204
                        $token = $report->at->getFirstToken();
1 ✔
205
                        $line = self::findCurrentLine($token, $report->trivia) + $report->lineInTrivia;
1 ✔
206
                        $fingerprint = $report->construct === null
1 ✔
207
                                ? $fingerprints->create($report->decision, $report->message, $line)
1 ✔
208
                                : $fingerprints->createFor($report->construct, $report->decision, $report->message, $line);
1 ✔
209
                        $violation = self::createViolation(
1 ✔
210
                                $report,
211
                                $fingerprint,
212
                                $line,
213
                                $token?->getCurrentColumn(),
1 ✔
214
                                $spans->find($report->at, $report->trivia, $report->lineInTrivia, $report->gap, $report->follows),
1 ✔
215
                                $this->findOriginalLines($report),
1 ✔
216
                                $severity,
217
                                $opened,
218
                                $moved,
219
                        );
220
                        $violations[$fingerprint] ??= $violation;
1 ✔
221
                }
222

223
                return self::sortByPosition(array_values($violations));
1 ✔
224
        }
225

226

227
        /**
228
         * The violation of the report, derived from what opened, closed or moved its line, and the line its fix opens
229
         * or closes marked for what follows.
230
         * @param ?array{int, int} $span  the offset and the length of what was reported
231
         * @param array{int, int} $originalLines  the first and the last line of what was reported in the original file
232
         * @param \WeakMap<Token, string> $opened
233
         * @param \WeakMap<Token, string> $moved
234
         */
235
        private static function createViolation(
236
                Report $report,
237
                string $fingerprint,
238
                int $line,
239
                ?int $column,
240
                ?array $span,
241
                array $originalLines,
242
                Severity $severity,
243
                \WeakMap $opened,
244
                \WeakMap $moved,
245
        ): Violation
246
        {
247
                $derivedFrom = self::findAncestor($report, $opened, $moved);
1 ✔
248
                self::markLine($report, $derivedFrom ?? $fingerprint, $opened, $moved);
1 ✔
249
                return new Violation(
1 ✔
250
                        $report->decision,
1 ✔
251
                        $report->message,
1 ✔
252
                        $line,
253
                        $report->trivia === null ? $column : null,
1 ✔
254
                        $severity,
255
                        fingerprint: $fingerprint,
256
                        fixable: $report->fixable,
1 ✔
257
                        risk: $report->risk,
1 ✔
258
                        refused: $report->refused,
1 ✔
259
                        because: $report->because,
1 ✔
260
                        derivedFrom: $derivedFrom === $fingerprint ? null : $derivedFrom,
1 ✔
261
                        offset: $span[0] ?? null,
1 ✔
262
                        length: $span[1] ?? null,
1 ✔
263
                        originalLines: $originalLines,
264
                );
265
        }
266

267

268
        /**
269
         * The line of the token or of its trivia in the current text; the trivia is counted back from the token, whose
270
         * line the index follows.
271
         */
272
        private static function findCurrentLine(?Token $token, ?Trivia $trivia): int
273
        {
274
                $line = $token?->getCurrentLine() ?? 1;
1 ✔
275
                if ($token === null || $trivia === null) {
1 ✔
276
                        return $line;
1 ✔
277
                }
278

279
                $leading = array_search($trivia, $token->leadingTrivia, strict: true);
1 ✔
280
                if ($leading !== false) {
1 ✔
281
                        foreach (array_slice($token->leadingTrivia, $leading) as $item) {
1 ✔
282
                                $line -= substr_count($item->text, "\n");
1 ✔
283
                        }
284

285
                        return $line;
1 ✔
286
                }
287

288
                $line += substr_count($token->text, "\n");
1 ✔
289
                foreach ($token->trailingTrivia as $item) {
1 ✔
290
                        if ($item === $trivia) {
1 ✔
291
                                break;
1 ✔
292
                        }
293

294
                        $line += substr_count($item->text, "\n");
1 ✔
295
                }
296

297
                return $line;
1 ✔
298
        }
299

300

301
        /**
302
         * The passes report by rule, the reader reads by position.
303
         * @param list<Violation> $violations
304
         * @return list<Violation>
305
         */
306
        private static function sortByPosition(array $violations): array
307
        {
308
                usort($violations, fn(Violation $a, Violation $b) => [$a->line, $a->column ?? 0] <=> [$b->line, $b->column ?? 0]);
1 ✔
309
                return $violations;
1 ✔
310
        }
311

312

313
        /** @param list<NodeRule> $rules */
314
        private function runStage(string $stage, array $rules, Style $style): void
315
        {
316
                // the gap rules ride along the traversal of the formatting stage and report under their decisions;
317
                // a rule is accounted for when it reported, the revision before the traversal standing for the whole of it
318
                $gaps = $stage === Stage::Formatting->name && !$this->plan->claims->isEmpty() ? $this->gaps : null;
1 ✔
319
                if ($rules === [] && $gaps === null) {
1 ✔
320
                        return;
1 ✔
321
                }
322

323
                foreach ($rules as $rule) {
1 ✔
324
                        $this->invoke($rule, fn(RuleContext $context) => $rule->beforePass($context));
1 ✔
325
                }
326

327
                // every gap holds the closure, which therefore must not hold the loop: through it a gap would reach and keep in
328
                // cycles everything the pass made
329
                [$analyses, $file, $path, $strict] = [$this->analyses, $this->file, $this->path, $this->policy->strict];
1 ✔
330
                $gaps?->beginPass(
1 ✔
331
                        $style,
332
                        new Fixer($this->contexts, stripos($this->code, '__LINE__') !== false),
1 ✔
333
                        static function (string $class, Rule $rule) use ($analyses, $file, $path, $strict): ?object {
1 ✔
334
                                if ($strict) {
1 ✔
335
                                        try {
336
                                                RuleInfo::fromRule($rule)->checkAnalysis($class);
1 ✔
337
                                        } catch (\LogicException $e) {
1 ✔
338
                                                throw new RuleException($rule::class, $path, $e);
1 ✔
339
                                        }
340
                                }
341

342
                                return $analyses->find($file, $class, $path);
1 ✔
343
                        },
1 ✔
344
                );
345
                $before = $this->file->revision;
1 ✔
346
                $enter = function (Node|Token $node) use ($stage, $gaps): void {
1 ✔
347
                        if (($this->entering[$stage][$node::class] ?? null) !== []) {
1 ✔
348
                                $this->visit($stage, $node, enter: true);
1 ✔
349
                        }
350

351
                        // a node a rule has just taken out of the tree has no gaps to decide
352
                        if ($gaps === null || ($node->parent === null && !$node instanceof FileNode)) {
1 ✔
353
                                return;
1 ✔
354
                        }
355

356
                        try {
357
                                $node instanceof Token ? $gaps->enterToken($node) : $gaps->enterNode($node);
1 ✔
358
                        } catch (ConfigurationException|RuleException $e) { // two claims deciding one gap, or a claim of the rule named failing
1 ✔
359
                                throw $e;
1 ✔
UNCOV
360
                        } catch (\Throwable $e) {
×
UNCOV
361
                                throw new RuleException(null, $this->path, $e);
×
362
                        }
363
                };
1 ✔
364
                // the traverser leaves every node it entered, a replaced one included; a rule sees only what is still in the tree
365
                $leave = fn(Node|Token $node) => ($this->leaving[$stage][$node::class] ?? null) === []
1 ✔
366
                        || ($node->parent === null && $node !== $this->file)
1 ✔
367
                        ? null
1 ✔
368
                        : $this->visit($stage, $node, enter: false);
1 ✔
369
                Traverser::traverse($this->file, $enter, $this->plan->leaves[$stage] ? $leave : null);
1 ✔
370

371
                if ($gaps !== null) {
1 ✔
372
                        foreach ($this->contexts as $ruleClass => $context) {
1 ✔
373
                                if ($context->hasReports()) {
1 ✔
374
                                        // the whitespace of a gap is written by the engine, always after a report of its own, so a mutation
375
                                        // without a report or after a denied one belongs to another rule of the same traversal
376
                                        $this->account($ruleClass, $context, $before, checkRevisions: false);
1 ✔
377
                                }
378
                        }
379
                }
380

381
                foreach ($rules as $rule) {
1 ✔
382
                        $this->invoke($rule, fn(RuleContext $context) => $rule->afterPass($context));
1 ✔
383
                }
384
        }
1 ✔
385

386

387
        private function visit(string $stage, Node|Token $node, bool $enter): void
388
        {
389
                $class = $node::class;
1 ✔
390
                $rules = ($enter ? $this->entering : $this->leaving)[$stage][$class] ?? $this->resolveRules($stage, $node, $enter);
1 ✔
391
                if ($rules === []) {
1 ✔
392
                        return;
1 ✔
393
                }
394

395
                $parent = $node->parent;
1 ✔
396
                $file = $this->file;
1 ✔
397
                foreach ($rules as [$rule, $context, $ruleClass]) {
1 ✔
398
                        $before = $file->revision;
1 ✔
399
                        try {
400
                                $enter ? $rule->enter($node, $context) : $rule->leave($node, $context);
1 ✔
401
                        } catch (\Throwable $e) {
1 ✔
402
                                throw new RuleException($ruleClass, $this->path, $e);
1 ✔
403
                        }
404

405
                        if ($file->revision !== $before || $context->hasReports()) {
1 ✔
406
                                $this->account($ruleClass, $context, $before);
1 ✔
407
                        }
408

409
                        if ($node->parent !== $parent) { // replaced or removed: the rest of the chain never sees it
1 ✔
410
                                return;
1 ✔
411
                        }
412
                }
413
        }
1 ✔
414

415

416
        /**
417
         * The rules the plan dispatches the class of the node to, with their contexts in this file.
418
         * @return list<array{NodeRule, RuleContext, class-string<NodeRule>}>
419
         */
420
        private function resolveRules(string $stage, Node|Token $node, bool $enter): array
421
        {
422
                $rules = [];
1 ✔
423
                foreach ($this->plan->getRulesVisiting($stage, $node::class, $enter) as $rule) {
1 ✔
424
                        $ruleClass = $rule::class;
1 ✔
425
                        $rules[] = [$rule, $this->contexts[$ruleClass], $ruleClass];
1 ✔
426
                }
427

428
                if ($enter) {
1 ✔
429
                        $this->entering[$stage][$node::class] = $rules;
1 ✔
430
                } else {
431
                        $this->leaving[$stage][$node::class] = $rules;
1 ✔
432
                }
433

434
                return $rules;
1 ✔
435
        }
436

437

438
        /**
439
         * Calls a per-file callback of a rule and accounts for what it did.
440
         * @param \Closure(RuleContext): void $callback
441
         */
442
        private function invoke(NodeRule $rule, \Closure $callback): void
443
        {
444
                $ruleClass = $rule::class;
1 ✔
445
                $context = $this->contexts[$ruleClass];
1 ✔
446
                $before = $this->file->revision;
1 ✔
447
                try {
448
                        $callback($context);
1 ✔
449
                } catch (\Throwable $e) {
1 ✔
450
                        throw new RuleException($ruleClass, $this->path, $e);
1 ✔
451
                }
452

453
                $this->account($ruleClass, $context, $before);
1 ✔
454
        }
1 ✔
455

456

457
        /**
458
         * Turns the reports of a callback into violations and checks that every mutation follows a report that returned
459
         * true; what the rule wrote after a denied report, up to its next one, it wrote for that report. After the last
460
         * report the rule may be fixing any of those it was allowed earlier, so that one is judged only where none was. A
461
         * report the baseline holds is not denied, only not recorded.
462
         * @param class-string<Rule> $ruleClass
463
         * @param int $before  the revision of the file before the callback
464
         * @param bool $checkRevisions  whether the revisions are the rule's doing, which along the gap traversal they need
465
         *                              not be, because they then cover every rule
466
         */
467
        private function account(string $ruleClass, RuleContext $context, int $before, bool $checkRevisions = true): void
468
        {
469
                $after = $this->file->revision;
1 ✔
470
                $reported = $allowed = false;
1 ✔
471
                $reports = $context->takeReports();
1 ✔
472
                foreach ($reports as $i => $report) {
1 ✔
473
                        $fingerprint = $report->fingerprint;
1 ✔
474
                        $denied = !$report->fixable || $report->silenced || $report->refused || $report->left;
1 ✔
475
                        $end = $reports[$i + 1]->revision ?? ($allowed ? null : $after);
1 ✔
476
                        if ($checkRevisions && $denied && $end !== null && $end > $report->revision) {
1 ✔
477
                                $this->violateContract($ruleClass, $report->fixable
1 ✔
478
                                        ? 'it changed the file although `report()` returned `false`'
1 ✔
479
                                        : 'it changed the file after a report with `fixable: false`');
1 ✔
480
                        }
481

482
                        $allowed = $allowed || !$denied;
1 ✔
483

484
                        if (!str_ends_with($report->message, '.')) {
1 ✔
485
                                $this->violateContract(
1 ✔
486
                                        $ruleClass,
487
                                        'it reported a message not ending with a period, ' . Violation::formatCode($report->message),
1 ✔
488
                                );
489
                        }
490

491
                        if ($report->silenced || $fingerprint === null) { // and then there is no violation to record
1 ✔
492
                                continue;
1 ✔
493
                        }
494

495
                        $reported = true;
1 ✔
496
                        $severity = isset($this->policy->warningDecisions[$report->decision]) || ($report->refused && $report->risk?->isResolvable())
1 ✔
497
                                ? Severity::Warning
1 ✔
498
                                : Severity::Error;
1 ✔
499
                        $this->reported[] = [$ruleClass, $report, $severity];
1 ✔
500
                        $violation = self::createViolation(
1 ✔
501
                                $report,
1 ✔
502
                                $fingerprint,
1 ✔
503
                                $report->line,
1 ✔
504
                                $this->findOriginalColumn($report->at),
1 ✔
505
                                $report->span,
1 ✔
506
                                $this->findOriginalLines($report),
1 ✔
507
                                $severity,
1 ✔
508
                                $this->opened,
1 ✔
509
                                $this->moved,
1 ✔
510
                        );
511
                        if (!$report->baselined) { // what the baseline holds is not recorded, though the rule may have fixed it
1 ✔
512
                                $this->violations[$fingerprint] ??= $violation;
1 ✔
513
                        }
514
                }
515

516
                // the lines of code a fix wrote anew are placed by it, as the lines of a gap the fixer broke are
517
                foreach ($context->takeRewritten() as [$fingerprint, $node]) {
1 ✔
518
                        $origin = $this->violations[$fingerprint]->derivedFrom ?? $fingerprint;
1 ✔
519
                        foreach ($node->getTokens() as $i => $token) {
1 ✔
520
                                if ($i === 0 || $token->startsLine()) {
1 ✔
521
                                        $this->moved[$token] ??= $origin;
1 ✔
522
                                }
523
                        }
524
                }
525

526
                if ($after > $before) {
1 ✔
527
                        $this->mutatedRules[$ruleClass] = true;
1 ✔
528
                        if (!$reported && $checkRevisions) {
1 ✔
529
                                $this->violateContract($ruleClass, 'it changed the file without reporting a violation');
1 ✔
530
                        }
531
                }
532
        }
1 ✔
533

534

535
        /**
536
         * The violation the report follows from: the one the fixer opened or closed the line of the reported gap
537
         * for, else the one that opened, closed or moved the line the reported whitespace is counted from. A report
538
         * about the shape of the line it stands on asks who opened or closed that line, and nothing about whitespace.
539
         * @param \WeakMap<Token, string> $opened
540
         * @param \WeakMap<Token, string> $moved
541
         */
542
        private static function findAncestor(Report $report, \WeakMap $opened, \WeakMap $moved): ?string
543
        {
544
                if ($report->byLine) {
1 ✔
545
                        $token = $report->at->getFirstToken();
1 ✔
546
                        return $token === null ? null : $opened[$token] ?? null;
1 ✔
547
                }
548

549
                if ($report->gap !== null && isset($opened[$report->gap])) {
1 ✔
550
                        return $opened[$report->gap];
1 ✔
551
                }
552

553
                $follows = $report->follows;
1 ✔
554
                return $follows === null ? null : $opened[$follows] ?? $moved[$follows] ?? null;
1 ✔
555
        }
556

557

558
        /**
559
         * What is placed by the line of the reported gap follows from what opened, closed or moved it, the first of the chain.
560
         * @param \WeakMap<Token, string> $opened
561
         * @param \WeakMap<Token, string> $moved
562
         */
563
        private static function markLine(Report $report, string $origin, \WeakMap $opened, \WeakMap $moved): void
564
        {
565
                if ($report->gap === null || $report->refused || $report->left) {
1 ✔
566
                        return;
1 ✔
567
                } elseif ($report->breaks) {
1 ✔
568
                        $opened[$report->gap] ??= $origin;
1 ✔
569
                } elseif ($report->follows !== null) {
1 ✔
570
                        $moved[$report->gap] ??= $origin;
1 ✔
571
                }
572
        }
1 ✔
573

574

575
        /**
576
         * A pass that changed nothing left every occurrence it reported as it was, so the rule had no fix for one it did not
577
         * report with `fixable: false`, refused as risky, or left as the file writes it.
578
         */
579
        private function checkUnfixed(): void
580
        {
581
                $rules = [];
1 ✔
582
                foreach ($this->reported as [$ruleClass, $report]) {
1 ✔
583
                        if ($report->fixable && !$report->refused && !$report->left && $report->gap === null) { // a gap is the engine's to fix, and a comment may keep it from that
1 ✔
584
                                $rules[$ruleClass] = true;
1 ✔
585
                        }
586
                }
587

588
                foreach (array_keys($rules) as $ruleClass) {
1 ✔
589
                        $this->violateContract($ruleClass, 'it reported an occurrence it then left unfixed without saying `fixable: false`');
1 ✔
590
                }
591
        }
1 ✔
592

593

594
        /** @param  string  $breach  what the rule did, as a clause */
595
        private function violateContract(string $ruleClass, string $breach): void
596
        {
597
                if ($this->policy->strict) {
1 ✔
598
                        throw new RuleException($ruleClass, $this->path, new \LogicException(ucfirst($breach) . '.'));
1 ✔
599
                }
600

601
                $this->warnings[] = "Rule `$ruleClass` is faulty: $breach.";
1 ✔
602
        }
1 ✔
603

604

605
        /**
606
         * Column in characters of the token in the original file, from its original offset and the start of its line.
607
         */
608
        private function findOriginalColumn(Node|Token $at): ?int
609
        {
610
                $token = $at->getFirstToken();
1 ✔
611
                if ($token === null || $token->pos < 0 || $token->line < 0) {
1 ✔
612
                        return null;
1 ✔
613
                }
614

615
                $lineStart = $this->lineOffsets[$token->line - 1] ?? 0;
1 ✔
616
                $before = substr($this->code, $lineStart, $token->pos - $lineStart);
1 ✔
617
                return strlen($before) - preg_match_all('~[\x80-\xBF]~', $before) + 1;
1 ✔
618
        }
619

620

621
        /**
622
         * The first and the last line of the original file the span of the report covers, or the line of the report where
623
         * it has no span.
624
         * @return array{int, int}
625
         */
626
        private function findOriginalLines(Report $report): array
627
        {
628
                if ($report->span === null) {
1 ✔
629
                        return [$report->line, $report->line];
1 ✔
630
                }
631

632
                [$offset, $length] = $report->span;
1 ✔
633
                return [$this->findOriginalLineAt($offset), $this->findOriginalLineAt($offset + max($length - 1, 0))];
1 ✔
634
        }
635

636

637
        /** The line of the original file the byte offset stands on, from 1. */
638
        private function findOriginalLineAt(int $offset): int
639
        {
640
                [$low, $high] = [0, count($this->lineOffsets) - 1];
1 ✔
641
                while ($low < $high) {
1 ✔
642
                        $middle = intdiv($low + $high + 1, 2);
1 ✔
643
                        if ($this->lineOffsets[$middle] <= $offset) {
1 ✔
644
                                $low = $middle;
1 ✔
645
                        } else {
646
                                $high = $middle - 1;
1 ✔
647
                        }
648
                }
649

650
                return $low + 1;
1 ✔
651
        }
652
}
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