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

dg / dresscode / 42439021063

08 Nov 2026 02:24AM UTC coverage: 96.937% (-0.002%) from 96.939%
42439021063

push

github

dg
long lines: the head of a foreach too wide spreads what it iterates before what it assigns

Of two constructs on a line with no common one to spread the last spreads first, so a `foreach` iterating a long
array literal spread the destructuring after `as` and kept the array whole, `[…] as [` above `$location,`. What
a `foreach` iterates now spreads first, its measure not looking past the `as`, and what it assigns waits while the
iterated expression on its line has something to spread, spreading only where the line left, `] as [$a, $b]) {`, is
still too wide; what follows the iterated expression no longer keeps it from spreading, the destructuring spreading
next. The search for a split beginning at a token is shared, `NodeHelpers::beginsSplit()`.

b243d2e8-3e44-4152-8c16-82d9156e6db2

33 of 36 new or added lines in 1 file covered. (91.67%)

96 existing lines in 23 files now uncovered.

30032 of 30981 relevant lines covered (96.94%)

0.97 hits per line

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

94.19
/src/Measuring/Questions.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\ConfigurationException;
11
use DressCode\Engine\Helpers;
12
use DressCode\Interop\{FormatterConfig, Translation};
13
use DressCode\Rules\Classes\NameCasingRule;
14
use function count, sprintf, strlen;
15

16

17
/**
18
 * What `dresscode init` asks, where the measuring left the choice to the user: the standard first, then the decisions,
19
 * the costliest first, and then what the answers left to the user in turn. Every question carries an answer that leaves
20
 * the code as it is, which is recommended.
21
 * @internal
22
 */
23
final class Questions
24
{
25
        /** the questions of decisions asked at most, before any answer */
26
        private const MaxDecisions = 5;
27

28
        /** the names no rule fixes that must share a pattern for init to offer it */
29
        private const MinNames = 3;
30

31
        /** @var array<string, true>  the decisions a question was found about, asked or not */
32
        private array $found = [];
33

34

35
        public function __construct(
36
                /** the rules of the formatter of the project, which a value of the code may contradict */
37
                private readonly ?Translation $formatterRules = null,
1 ✔
38
        ) {
39
        }
1 ✔
40

41

42
        /** A close call of standards nothing of the project decided, asked before the verification, as an answer measures again. */
43
        public static function findStandardQuestion(Proposal $proposal): ?Question
44
        {
45
                $standard = $proposal->standard;
1 ✔
46
                if (!$standard->alternatives) {
1 ✔
47
                        return null;
1 ✔
48
                }
49

50
                $chosen = implode(', ', $standard->presets);
1 ✔
51
                $describe = fn(string $name) => sprintf('`%s`, a fix under it changes %d files', $name, $standard->changedFiles[$name] ?? 0);
1 ✔
52
                $answers = [new Answer($describe($chosen))];
1 ✔
53
                foreach ($standard->alternatives as $alternative) {
1 ✔
54
                        $answers[] = new Answer($describe($alternative), measureAgainst: [$alternative]);
1 ✔
55
                }
56

57
                $alternatives = array_map(fn(string $alternative) => "`$alternative`", $standard->alternatives);
1 ✔
58
                return new Question(
1 ✔
59
                        "Your code is as near to `$chosen` as to " . implode(' and ', $alternatives) . '; which standard should it follow?',
1 ✔
60
                        $answers,
61
                        "`dresscode init --use {$standard->alternatives[0]}` measures against $alternatives[0] instead, where there is no `dresscode.neon` yet",
1 ✔
62
                );
63
        }
64

65

66
        /**
67
         * Asks round after round what the verified proposal leaves to the user, and checks the configuration again after
68
         * a round whose answers changed it, until a round changes nothing or nothing is left to ask.
69
         * @param  \Closure(list<Question>, bool): list<Answer>  $answer  answers a round, told whether it follows from the
70
         *     answers to the rounds before
71
         * @return list<Question>  the questions asked
72
         * @throws ConfigurationException
73
         */
74
        public function askAll(Proposal $proposal, \Closure $answer): array
75
        {
76
                $asked = [];
1 ✔
77
                while ($round = $this->findNext($proposal)) {
1 ✔
78
                        $answers = $answer($round, $asked !== []);
1 ✔
79
                        $asked = [...$asked, ...$round];
1 ✔
80
                        if (!$proposal->applyAnswers(...$answers)) {
1 ✔
81
                                break;
1 ✔
82
                        }
83

84
                        $proposal->verify();
1 ✔
85
                }
86

87
                return $asked;
1 ✔
88
        }
89

90

91
        /**
92
         * The questions of decisions the verified proposal leaves to the user that no call before found, the costliest
93
         * first: at most `MaxDecisions` of them the first time, and one more about the rest the budget left unchecked, every
94
         * one later, as it follows from the answers given.
95
         * @return list<Question>
96
         */
97
        public function findNext(Proposal $proposal): array
98
        {
99
                $first = !$this->found;
1 ✔
100
                $questions = array_diff_key([
1 ✔
101
                        ...self::findOverBudget($proposal),
1 ✔
102
                        ...self::findConflicts($proposal, $this->formatterRules),
1 ✔
103
                        ...self::findNamePatterns($proposal),
1 ✔
104
                ], $this->found);
1 ✔
105
                uasort($questions, fn(Question $a, Question $b) => $b->files <=> $a->files);
1 ✔
106
                $this->found += array_fill_keys(array_keys($questions), true);
1 ✔
107
                if (!$first || count($questions) <= self::MaxDecisions) {
1 ✔
108
                        return array_values($questions);
1 ✔
109
                }
110

111
                $rest = array_filter(
1 ✔
112
                        array_slice($questions, self::MaxDecisions),
1 ✔
113
                        fn(string $path) => ($proposal->values[$path] ?? null)?->origin === ValueOrigin::OverBudget,
1 ✔
114
                        ARRAY_FILTER_USE_KEY,
1 ✔
115
                );
116
                return [
117
                        ...array_values(array_slice($questions, 0, self::MaxDecisions)),
1 ✔
118
                        ...match (count($rest)) {
1 ✔
119
                                0 => [],
×
120
                                1 => array_values($rest),
×
121
                                default => [self::createRestQuestion($proposal, array_keys($rest))],
1 ✔
122
                        },
123
                ];
124
        }
125

126

127
        /**
128
         * A value the code or the standard holds to whose fix would rewrite more files than the budget allows.
129
         * @return array<string, Question>  by the path of the decision
130
         */
131
        private static function findOverBudget(Proposal $proposal): array
132
        {
133
                $questions = [];
1 ✔
134
                foreach ($proposal->values as $path => $proposed) {
1 ✔
135
                        if ($proposed->origin === ValueOrigin::OverBudget) {
1 ✔
136
                                $wanted = $proposal->standard->formatValue($path, $proposed->wanted);
1 ✔
137
                                $cost = Helpers::formatCount($proposed->cost, 'file');
1 ✔
138
                                $questions[$path] = new Question(
1 ✔
139
                                        "Check `$path: $wanted`?",
1 ✔
140
                                        [
141
                                                new Answer("don't check it"),
1 ✔
142
                                                new Answer("`$wanted` everywhere, a fix rewrites $cost", [$path => $proposed->wanted]),
1 ✔
143
                                        ],
144
                                        "`$path: $wanted` in `dresscode.neon` checks it too; its fix changes $cost",
1 ✔
145
                                        $proposed->example,
1 ✔
146
                                        $proposed->cost,
1 ✔
147
                                        self::formatBudget($proposal),
1 ✔
148
                                        previewValues: [$path => $proposed->wanted],
1 ✔
149
                                );
150
                        }
151
                }
152

153
                return $questions;
1 ✔
154
        }
155

156

157
        /**
158
         * The decisions over the budget a round has no room for, all checked by one answer.
159
         * @param  list<string>  $paths
160
         */
161
        private static function createRestQuestion(Proposal $proposal, array $paths): Question
162
        {
163
                $values = $decisions = [];
1 ✔
164
                $files = 0;
1 ✔
165
                foreach ($paths as $path) {
1 ✔
166
                        $proposed = $proposal->values[$path];
1 ✔
167
                        $values[$path] = $proposed->wanted;
1 ✔
168
                        $decisions["`$path: " . $proposal->standard->formatValue($path, $proposed->wanted) . '`']
1 ✔
169
                                = 'a fix rewrites ' . Helpers::formatCount($proposed->cost, 'file');
1 ✔
170
                        $files += $proposed->cost;
1 ✔
171
                }
172

173
                $most = 'at most ' . Helpers::formatCount($files, 'file');
1 ✔
174
                return new Question(
1 ✔
175
                        'Check the ' . count($paths) . ' decisions left too?',
1 ✔
176
                        [new Answer("don't check them"), new Answer("check all of them, a fix rewrites $most", $values)],
1 ✔
177
                        implode(', ', array_keys($decisions)) . " in `dresscode.neon` check them too; their fixes change $most",
1 ✔
178
                        files: $files,
179
                        reason: self::formatBudget($proposal),
1 ✔
180
                        decisions: $decisions,
181
                );
182
        }
183

184

185
        /** What the budget is, in the words of someone who runs init for the first time. */
186
        private static function formatBudget(Proposal $proposal): string
187
        {
188
                $budget = $proposal->verification->budget ?? throw new \LogicException('The proposal is not verified.');
1 ✔
189
                return 'Without asking, init lets the first fix rewrite at most ' . Helpers::formatCount($budget, 'file') . ' (`--budget`).';
1 ✔
190
        }
191

192

193
        /**
194
         * A value the code holds to that the configuration of the formatter contradicts.
195
         * @return array<string, Question>  by the path of the decision
196
         */
197
        private static function findConflicts(Proposal $proposal, ?Translation $formatterRules): array
198
        {
199
                $config = $proposal->project->formatterConfig;
1 ✔
200
                if ($formatterRules === null || $config === null) {
1 ✔
201
                        return [];
1 ✔
202
                }
203

204
                $questions = [];
1 ✔
205
                foreach ($formatterRules->collectDecisions() as $path => $foreign) {
1 ✔
206
                        $proposed = $proposal->values[$path] ?? null;
1 ✔
207
                        $decision = $proposal->standard->decisions[$path]->decision ?? null;
1 ✔
208
                        if ($proposed === null || $decision === null || $proposed->origin !== ValueOrigin::Measured || $proposed->isKept()) {
1 ✔
209
                                continue;
1 ✔
210
                        }
211

212
                        try {
213
                                if ($decision->accept($foreign)->toData() === $decision->accept($proposed->value)->toData()) {
1 ✔
214
                                        continue;
1 ✔
215
                                }
216
                        } catch (ConfigurationException) {
×
217
                                continue;
×
218
                        }
219

220
                        $files = $proposal->estimateFiles($path, $foreign);
1 ✔
221
                        if ($files !== null) {
1 ✔
222
                                $questions[$path] = self::createConflict($proposal, $config, $path, $foreign, $files);
1 ✔
223
                        }
224
                }
225

226
                return $questions;
1 ✔
227
        }
228

229

230
        private static function createConflict(Proposal $proposal, FormatterConfig $config, string $path, mixed $foreign, int $files): Question
231
        {
232
                $proposed = $proposal->values[$path];
1 ✔
233
                $formatterValue = $proposal->standard->formatValue($path, $foreign);
1 ✔
234
                $measuredValue = $proposal->standard->formatValue($path, $proposed->value);
1 ✔
235
                $about = $proposal->isSampled() ? 'about ' : '';
1 ✔
236
                return new Question(
1 ✔
237
                        "`$config->file` wants `$path: $formatterValue`, your code writes `$measuredValue` ($proposed->comment); which should the file say?",
1 ✔
238
                        [
239
                                new Answer("`$measuredValue`, as your code writes it", [$path => $proposed->value], $proposed->comment),
1 ✔
240
                                new Answer(
1 ✔
241
                                        "`$formatterValue`, as `$config->file` says, a fix rewrites $about" . Helpers::formatCount($files, 'file'),
1 ✔
242
                                        [$path => $foreign],
1 ✔
243
                                ),
244
                        ],
245
                        "`$path: $formatterValue` in `dresscode.neon` says what `$config->file` says; its fix changes $about"
1 ✔
246
                                . Helpers::formatCount($files, 'file'),
1 ✔
247
                        files: $files,
248
                );
249
        }
250

251

252
        /**
253
         * Names written in another case that share a prefix or a suffix, which `naming.except` may let pass.
254
         * @return array<string, Question>  by the path of the decision
255
         */
256
        private static function findNamePatterns(Proposal $proposal): array
257
        {
258
                $verification = $proposal->verification ?? throw new \LogicException('The proposal is not verified.');
1 ✔
259
                $questions = [];
1 ✔
260
                $codes = [];
1 ✔
261
                foreach (NameCasingRule::getDecisions() as $decision) {
1 ✔
262
                        $path = $decision->path;
1 ✔
263
                        $names = $files = [];
1 ✔
264
                        foreach ($verification->result->findings[$path] ?? [] as $finding) {
1 ✔
265
                                if ($finding->fixable || $finding->span === null) {
1 ✔
266
                                        continue;
×
267
                                }
268

269
                                // what the rule reports begins with the name, a constant going on with its value
270
                                $file = $finding->file;
1 ✔
271
                                $codes[$file] ??= (string) @file_get_contents($proposal->project->root . "/$file"); // @ file may have been deleted meanwhile
1 ✔
272
                                if (preg_match('~\$?(\w+)~A', substr($codes[$file], ...$finding->span), $m)) {
1 ✔
273
                                        $names[] = $m[1];
1 ✔
274
                                        $files[$file] = true;
1 ✔
275
                                }
276
                        }
277

278
                        $pattern = count($names) < self::MinNames ? null : self::findPattern($names);
1 ✔
279
                        if ($pattern !== null) {
1 ✔
280
                                $questions[$path] = self::createNamePatternQuestion($proposal, $path, $names, $pattern, count($files));
1 ✔
281
                        }
282
                }
283

284
                return $questions;
1 ✔
285
        }
286

287

288
        /**
289
         * @param  list<string>  $names
290
         * @param  array{string, string}  $pattern  the regular expression, what it allows
291
         */
292
        private static function createNamePatternQuestion(Proposal $proposal, string $path, array $names, array $pattern, int $files): Question
293
        {
294
                [$regex, $allows] = $pattern;
1 ✔
295
                $kind = substr($path, strlen('naming.'));
1 ✔
296
                $except = (array) ($proposal->values['naming.except']->value
1 ✔
297
                        ?? $proposal->standard->decisions['naming.except']->value->toData()
1 ✔
298
                        ?? []);
1 ✔
299
                return new Question(
1 ✔
300
                        sprintf('%d %s names %s, which no rule renames; how should they be checked?', count($names), $kind, $allows),
1 ✔
301
                        [
302
                                new Answer('list them in the baseline'),
1 ✔
303
                                new Answer(
1 ✔
304
                                        "allow names that $allows, now and later",
1 ✔
305
                                        ['naming.except' => [...$except, $regex]],
1 ✔
306
                                        sprintf('the %d %s names that %s, which no rule renames', count($names), $kind, $allows),
1 ✔
307
                                ),
308
                                new Answer("don't check $kind names", [$path => 'keep']),
1 ✔
309
                        ],
310
                        "`naming.except: [$regex]` in `dresscode.neon` lets the $kind names that $allows pass now and later, rather than the baseline listing those of today",
1 ✔
311
                        $proposal->verification?->result->findExample($path),
1 ✔
312
                        $files,
313
                );
314
        }
315

316

317
        /**
318
         * The suffix or the prefix every name shares, cut at the boundary of a word, as the regular expression of
319
         * `naming.except` and what it allows: names that "end with `_`".
320
         * @param  list<string>  $names
321
         * @return ?array{string, string}
322
         */
323
        private static function findPattern(array $names): ?array
324
        {
325
                if (!$names) {
1 ✔
UNCOV
326
                        return null;
×
327
                }
328

329
                $shortest = min(array_map(strlen(...), $names));
1 ✔
330
                $suffix = $prefix = '';
1 ✔
331
                for ($i = 1; $i < $shortest; $i++) {
1 ✔
332
                        $tail = substr($names[0], -$i);
1 ✔
333
                        if (!array_all($names, fn(string $name) => str_ends_with($name, $tail))) {
1 ✔
334
                                break;
1 ✔
335
                        } elseif (array_all($names, fn(string $name) => self::isWordBoundary($name, strlen($name) - $i))) {
1 ✔
336
                                $suffix = $tail;
1 ✔
337
                        }
338
                }
339

340
                for ($i = 1; $i < $shortest; $i++) {
1 ✔
341
                        $head = substr($names[0], 0, $i);
1 ✔
342
                        if (!array_all($names, fn(string $name) => str_starts_with($name, $head))) {
1 ✔
343
                                break;
1 ✔
UNCOV
344
                        } elseif (array_all($names, fn(string $name) => self::isWordBoundary($name, $i))) {
×
UNCOV
345
                                $prefix = $head;
×
346
                        }
347
                }
348

349
                return match (true) {
350
                        strlen($suffix) >= strlen($prefix) && $suffix !== '' => ['~' . preg_quote($suffix, '~') . '$~', "end with `$suffix`"],
1 ✔
UNCOV
351
                        $prefix !== '' => ['~^' . preg_quote($prefix, '~') . '~', "start with `$prefix`"],
×
352
                        default => null,
1 ✔
353
                };
354
        }
355

356

357
        /** Whether a word of the name ends before the offset: at an underscore or where a capital follows a lowercase letter. */
358
        private static function isWordBoundary(string $name, int $at): bool
359
        {
360
                return $name[$at - 1] === '_' || $name[$at] === '_' || (ctype_upper($name[$at]) && !ctype_upper($name[$at - 1]));
1 ✔
361
        }
362
}
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