• 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

98.61
/src/Config/DecisionResolver.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\Config;
9

10
use DressCode\{Config, ConfigurationException, Decision, DecisionKind, Domain, Rule, RuleInfo, Value, Values};
11
use DressCode\Domains\{Count, Flag, Map, Names, Words};
12
use DressCode\Interop\Translator;
13
use Nette\Utils\Helpers;
14
use function count, is_array, is_bool, is_int, is_string, strlen;
15

16

17
/**
18
 * Lays the layers of the decisions one over another: each layer writes a tree of sections, whose every path is
19
 * checked against the catalogue and normalized by the decision it reaches, and the values of one path merge by
20
 * the law of its domain. `keep` on a section or a structure is a tombstone for every key under it, which a later
21
 * layer brings back one key at a time: a requirement becomes `keep` and a parameter, which takes no `keep`, its
22
 * default, so that nothing a layer below said comes back from under the tombstone.
23
 * @internal
24
 */
25
final readonly class DecisionResolver
26
{
27
        private const PresenceWords = ['required', 'forbidden', 'optional'];
28

29

30
        public function __construct(
31
                public Catalogue $catalogue,
1 ✔
32
                /** the versions of PHP the code is written for, as a Composer constraint */
33
                private string $phpTarget = Config::DefaultPhpVersion,
1 ✔
34
                /** the packages the project stands on, which decide whether a rule requiring one runs; null runs it whatever they are */
35
                private ?ProjectPackages $project = new ProjectPackages,
1 ✔
36
                /** whether the run has the types of the code */
37
                private bool $typesAnalyzed = false,
1 ✔
38
                /** whether the namespaces of the configuration are complete, which turns on their guard */
39
                private bool $certainNames = false,
1 ✔
40
                /** knows the names of the rules of other tools and the decisions that cover them */
41
                private Translator $translator = new Translator,
1 ✔
42
        ) {
43
        }
1 ✔
44

45

46
        /**
47
         * Every decision of the catalogue with what the layers came to.
48
         * @param  list<array{Layer, array<string, mixed>}>  $layers  who says it and the tree of sections it writes, from the bottom up
49
         * @return array<string, ResolvedDecision>
50
         * @throws ConfigurationException
51
         */
52
        public function resolve(array $layers): array
53
        {
54
                $said = $cascaded = [];
1 ✔
55
                foreach ($layers as [$origin, $tree]) {
1 ✔
56
                        foreach ($this->flatten($tree, '', $origin->kind === LayerKind::CommandLine) as $path => [$value, $tombstone, $inherited]) {
1 ✔
57
                                $said[$path][] = [$value->withOrigin($origin), $tombstone];
1 ✔
58
                                $cascaded[$path] = $inherited;
1 ✔
59
                        }
60
                }
61

62
                $resolved = [];
1 ✔
63
                foreach ($this->catalogue->getDecisions() as $path => $decision) {
1 ✔
64
                        $merged = null;
1 ✔
65
                        foreach ($said[$path] ?? [] as [$value, $tombstone]) {
1 ✔
66
                                $merged = match (true) {
1 ✔
67
                                        $tombstone => $value,
1 ✔
68
                                        $merged !== null => $decision->domain->merge($merged, $value, $path),
1 ✔
69
                                        // the first list holding `...` stands on the default
70
                                        in_array(Domain::Spread, is_array($value->content) ? $value->content : [], true) => $decision->domain->merge(
1 ✔
71
                                                $decision->getDefault(),
1 ✔
72
                                                $value,
73
                                                $path,
74
                                        ),
75
                                        default => $value,
1 ✔
76
                                };
77
                        }
78

79
                        $merged ??= $decision->getDefault();
1 ✔
80
                        $resolved[$path] = new ResolvedDecision(
1 ✔
81
                                $decision,
82
                                $this->catalogue->getRulesOf($path),
1 ✔
83
                                $merged,
84
                                array_column($said[$path] ?? [], 0),
1 ✔
85
                                match (true) {
86
                                        $decision->kind === DecisionKind::Fact => $this->certainNames ? null : InactiveReason::NameResolution,
1 ✔
87
                                        $decision->isRequirement() && $merged->isKept() => InactiveReason::Keep,
1 ✔
88
                                        default => null,
1 ✔
89
                                },
90
                                $cascaded[$path] ?? false,
1 ✔
91
                        );
92
                }
93

94
                foreach ($resolved as $path => $decision) {
1 ✔
95
                        $reasons = array_map($this->findRuleReason(...), $decision->rules);
1 ✔
96
                        if ($reasons !== [] && !in_array(null, $reasons, true)) {
1 ✔
97
                                $resolved[$path] = $decision->withInactive($reasons[0]);
1 ✔
98
                        }
99
                }
100

101
                return $resolved;
1 ✔
102
        }
103

104

105
        /**
106
         * The values of one layer by the paths of their decisions, checked against the catalogue; for the caller to
107
         * tell which layer an error is in.
108
         * @param  array<string, mixed>  $tree
109
         * @throws ConfigurationException
110
         */
111
        public function checkLayer(array $tree, Layer $layer): void
112
        {
113
                $this->flatten($tree, '', $layer->kind === LayerKind::CommandLine);
1 ✔
114
        }
1 ✔
115

116

117
        /**
118
         * The values a rule reads, with the mask of the run.
119
         * @param  array<string, ResolvedDecision>  $resolved
120
         * @param  ?list<string>  $selection  the paths and prefixes the run is narrowed to; null for all
121
         */
122
        public function createValues(array $resolved, ?array $selection = null): Values
123
        {
124
                return new Values(
1 ✔
125
                        $this->catalogue->getDecisions(),
1 ✔
126
                        array_map(fn(ResolvedDecision $decision) => $decision->value, $resolved),
1 ✔
127
                        $selection,
128
                );
129
        }
130

131

132
        /**
133
         * Why the rule does not run whatever the values of its decisions: a target older than the rule needs, a package the
134
         * project does not meet, or types the run does not have.
135
         * @param  class-string<Rule>  $rule
136
         */
137
        public function findRuleReason(string $rule): ?InactiveReason
138
        {
139
                $info = RuleInfo::fromRule($rule);
1 ✔
140
                $php = $info->requires['php'] ?? null;
1 ✔
141
                return match (true) {
1 ✔
142
                        $php !== null && !Versions::isSubset($this->phpTarget, $php) => InactiveReason::Php,
1 ✔
143
                        $this->project?->findUnmetRequirement($info->getRequiredPackages()) !== null => InactiveReason::Package,
1 ✔
144
                        $info->typesRequired && !$this->typesAnalyzed => InactiveReason::Types,
1 ✔
145
                        default => null,
1 ✔
146
                };
147
        }
148

149

150
        /**
151
         * The values of a tree by the paths of their decisions, each with whether it replaces what the layers below said,
152
         * the tombstone of a `keep` on a section or a structure and a map written with `!` after its key, and whether it was
153
         * written on a group above the decision. A key with nothing under it, a section or a group `null` or empty and a list
154
         * of names or a map `null`, is the shape of a block commented out and says nothing, except on the command line.
155
         * @param  array<mixed>  $tree
156
         * @return array<string, array{Value, bool, bool}>
157
         * @throws ConfigurationException
158
         */
159
        private function flatten(array $tree, string $prefix, bool $commandLine): array
160
        {
161
                // a kind of places goes first, so that a place the same map names wins over it
162
                $kinds = array_intersect_key($tree, Catalogue::PlaceKinds);
1 ✔
163
                $values = [];
1 ✔
164
                foreach ($kinds + $tree as $key => $raw) {
1 ✔
165
                        $path = $prefix === '' ? (string) $key : "$prefix.$key";
1 ✔
166
                        if (is_string($key) && str_contains($key, '.')) {
1 ✔
167
                                throw new ConfigurationException("Key `$path` holds dots; write its links nested, each a key of its own.");
1 ✔
168
                        }
169

170
                        $replacing = is_string($key) && str_ends_with($key, '!');
1 ✔
171
                        $path = $replacing ? substr($path, 0, -1) : $path;
1 ✔
172
                        $decision = is_int($key) ? null : $this->catalogue->find($path);
1 ✔
173
                        if ($replacing && (!$decision?->domain instanceof Map || !is_array($raw) || $raw === [])) {
1 ✔
174
                                throw new ConfigurationException("Key `$path!` replaces a map of the layers below with the entries it writes, and `$path` is no such map or gives none; write `$path` without `!`, or `keep` to withdraw the map.");
1 ✔
175
                        } elseif ($raw === null && !$commandLine && ($decision?->domain instanceof Names || $decision?->domain instanceof Map)) {
1 ✔
176
                                continue;
1 ✔
177
                        } elseif ($decision !== null) {
1 ✔
178
                                $values[$path] = [$decision->accept($raw), $replacing, false];
1 ✔
179
                                continue;
1 ✔
180
                        }
181

182
                        $under = is_int($key) ? [] : $this->catalogue->getDecisionsUnder($path);
1 ✔
183
                        if ($under === [] && $prefix !== '' && isset(Catalogue::PlaceKinds[$key])) {
1 ✔
184
                                $under = array_filter(
1 ✔
185
                                        $this->catalogue->getDecisionsUnder($prefix),
1 ✔
186
                                        fn(Decision $decision) => in_array(substr($decision->path, strlen($prefix) + 1), Catalogue::PlaceKinds[$key], true),
1 ✔
187
                                );
188
                        }
189

190
                        if ($under === []) {
1 ✔
191
                                $this->refuseKey($path, $prefix);
1 ✔
192
                        } elseif ($raw === 'keep') {
1 ✔
193
                                foreach ($under as $inner => $decision) {
1 ✔
194
                                        $values[$inner] = [$decision->takesKeep() ? Value::keep($decision->domain) : $decision->getDefault(), true, true];
1 ✔
195
                                }
196
                        } elseif (($raw === null || $raw === []) && !$commandLine) {
1 ✔
197
                                continue;
1 ✔
198
                        } elseif ($raw === []) {
1 ✔
199
                                throw new ConfigurationException("Key `$path` holds keys of its own, and an empty list or map says nothing of them; write the keys, or `keep`.");
1 ✔
200
                        } elseif (is_array($raw) && !array_is_list($raw)) {
1 ✔
201
                                $values = $this->flatten($raw, $path, $commandLine) + $values;
1 ✔
202
                        } elseif ($prefix !== '' && (is_string($raw) || is_int($raw) || is_bool($raw) || is_array($raw))) {
1 ✔
203
                                $values = $this->inherit($raw, $path, $under) + $values;
1 ✔
204
                        } elseif ($prefix === '') {
1 ✔
205
                                throw new ConfigurationException("Key `$path` is a section, which takes `keep` alone; write the values at its keys.");
1 ✔
206
                        } else {
207
                                throw new ConfigurationException("Key `$path` holds keys of its own; write a map of them or `keep`.");
1 ✔
208
                        }
209
                }
210

211
                return $values;
1 ✔
212
        }
213

214

215
        /**
216
         * The value written on a structure or a kind of places as the value of each decision it covers, `operatorPosition:
217
         * lineStart`: a word, a count or a flag goes to the decisions of a closed vocabulary that take it, and a list to each
218
         * of them as the words of it that decision takes, the others left out there; a text, a list of names, a map and an
219
         * example are never given that way. A word no decision takes, one only parameters take among requirements, a word of
220
         * presence a requirement does not take or given to a group of one thing, a list leaving a decision none, and `keep`
221
         * or `...` in a list are errors.
222
         * @param  string|int|bool|array<mixed>  $raw
223
         * @param  non-empty-array<string, Decision>  $decisions
224
         * @return array<string, array{Value, bool, bool}>
225
         * @throws ConfigurationException
226
         */
227
        private function inherit(string|int|bool|array $raw, string $path, array $decisions): array
228
        {
229
                $takes = function (Decision $decision, mixed $word): bool {
1 ✔
230
                        try {
231
                                $decision->accept($word);
1 ✔
232
                                return true;
1 ✔
233
                        } catch (ConfigurationException) {
1 ✔
234
                                return false;
1 ✔
235
                        }
236
                };
237
                $words = is_array($raw) ? $raw : [$raw];
1 ✔
238
                if (is_array($raw) && !array_is_list($raw)) {
1 ✔
UNCOV
239
                        throw new ConfigurationException("Key `$path` holds keys of its own; write a map of them or `keep`.");
×
240
                } elseif (is_array($raw) && in_array('keep', $raw, true)) {
1 ✔
241
                        throw new ConfigurationException("Key `$path` holds `keep` in a list; `keep` stands alone.");
1 ✔
242
                } elseif (is_array($raw) && in_array(Domain::Spread, $raw, true)) {
1 ✔
243
                        throw new ConfigurationException("Key `$path` holds `...` in a list, which every decision under it would read as another list; write it at the decision.");
1 ✔
244
                }
245

246
                $presence = array_intersect($words, self::PresenceWords);
1 ✔
247
                if ($presence !== [] && in_array($path, Catalogue::QuestionGroups, true)) {
1 ✔
248
                        throw new ConfigurationException('Key `' . $path . '` names one thing several decisions ask about, so `' . reset($presence) . '` would read as one about the thing itself; write it at the decisions, or `keep` at the key.');
1 ✔
249
                }
250

251
                $closed = array_filter(
1 ✔
252
                        $decisions,
253
                        fn(Decision $decision) => $decision->domain instanceof Words
1 ✔
254
                                || $decision->domain instanceof Count
1 ✔
255
                                || $decision->domain instanceof Flag,
1 ✔
256
                );
257
                $requirements = array_filter($closed, fn(Decision $decision) => $decision->isRequirement());
1 ✔
258
                foreach ($words as $word) {
1 ✔
259
                        if (!array_any($closed, fn(Decision $decision) => $takes($decision, $word))) {
1 ✔
260
                                $decision = reset($closed) ?: reset($decisions);
1 ✔
261
                                $decision->accept($word); // refused, with what the domain expects
1 ✔
UNCOV
262
                                throw new ConfigurationException("Key `$path` gives `$word`, which a group gives no decision under it; write it at the decision.");
×
263
                        } elseif ($requirements !== [] && !array_any($requirements, fn(Decision $decision) => $takes($decision, $word))) {
1 ✔
264
                                throw new ConfigurationException("Key `$path` gives `$word`, which only a parameter under it takes; write it at the parameter.");
1 ✔
265
                        }
266
                }
267

268
                foreach ($presence as $word) {
1 ✔
269
                        $refusing = array_find_key(
1 ✔
270
                                array_filter($decisions, fn(Decision $decision) => $decision->isRequirement()),
1 ✔
271
                                fn(Decision $decision) => !$takes($decision, $word),
1 ✔
272
                        );
273
                        if ($refusing !== null) {
1 ✔
274
                                throw new ConfigurationException("Key `$path` gives `$word`, which `$refusing` does not take; a word of presence on a group holds for every decision under it, so write the decisions one by one.");
1 ✔
275
                        }
276
                }
277

278
                $values = [];
1 ✔
279
                foreach ($closed as $inner => $decision) {
1 ✔
280
                        $taken = array_values(array_filter($words, fn($word) => $takes($decision, $word)));
1 ✔
281
                        if ($taken === [] && is_array($raw) && $decision->isRequirement()) {
1 ✔
282
                                throw new ConfigurationException("Key `$path` leaves `$inner` none of its values; write a value for `$inner` of its own.");
1 ✔
283
                        } elseif ($taken !== []) {
1 ✔
284
                                $value = match (true) {
1 ✔
285
                                        !is_array($raw) => $raw,
1 ✔
286
                                        count($taken) === 1 && !$takes($decision, $taken) => $taken[0], // a decision of one word
1 ✔
287
                                        default => $taken,
1 ✔
288
                                };
289
                                $values[$inner] = [$decision->accept($value), false, true];
1 ✔
290
                        }
291
                }
292

293
                return $values;
1 ✔
294
        }
295

296

297
        /** @throws ConfigurationException */
298
        private function refuseKey(string $path, string $prefix): never
299
        {
300
                $known = [];
1 ✔
301
                foreach (array_keys($this->catalogue->getDecisions()) as $decision) {
1 ✔
302
                        if ($prefix === '' || str_starts_with($decision, "$prefix.")) {
1 ✔
303
                                $rest = $prefix === '' ? $decision : substr($decision, strlen($prefix) + 1);
1 ✔
304
                                $known[($prefix === '' ? '' : "$prefix.") . explode('.', $rest, 2)[0]] = true;
1 ✔
305
                        }
306
                }
307

308
                $covered = $prefix === '' ? $this->translator->findPaths($path) : [];
1 ✔
309
                $hint = Helpers::getSuggestion(array_keys($known), $path);
1 ✔
310
                throw new ConfigurationException("Key `$path` is unknown" . match (true) {
1 ✔
311
                        $covered !== [] => '. It is the name of a rule of another tool, covered by `'
312
                                . implode('` and `', $covered)
1 ✔
313
                                . '`; `dresscode migrate config` translates a configuration of another tool.',
1 ✔
314
                        $hint !== null => "; write `$hint`.",
1 ✔
315
                        default => '.',
1 ✔
316
                }, docs: $covered !== [] ? 'migration#migrate-config' : null);
1 ✔
317
        }
318
}
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