• 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.75
/src/Engine/Baseline.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\{Config, ConfigurationException, FileResult};
11
use DressCode\Config\Loader;
12
use Nette\Neon\{Exception as NeonException, Neon};
13
use function is_array, is_string;
14

15

16
/**
17
 * The violations a run holds back instead of recording, by file and fingerprint; generated from a run and kept in a
18
 * .neon or a .php file, as its extension says. A run marks the entries it matched, so the unmatched ones can be reported.
19
 * @internal
20
 */
21
final class Baseline
22
{
23
        /** the name of the file a run finds by itself, with the extension of the format of the configuration */
24
        private const DefaultName = 'dresscode-baseline';
25

26
        /** the version of the file, a new one where the fingerprints are made otherwise */
27
        private const Version = 2;
28

29
        /** @var array<string, array<string, array{decision: string, message: string}>>  path => fingerprint => entry */
30
        private array $entries = [];
31

32
        /** @var array<string, array<string, true>>  path => fingerprints no violation matched yet */
33
        private array $unmatched = [];
34

35
        private int $matched = 0;
36

37

38
        /**
39
         * The baseline the run holds violations back by, which must exist where the configuration names it.
40
         * @throws ConfigurationException
41
         */
42
        public static function open(Config $config, string $root): ?self
43
        {
44
                $file = self::findFile($config, $root);
1 ✔
45
                return $file === null ? null : self::load($file, required: $config->baseline !== null);
1 ✔
46
        }
47

48

49
        /**
50
         * The baseline file the configuration names, else the one of the default name in the root where there is one; null
51
         * before the first `dresscode baseline`.
52
         */
53
        public static function findFile(Config $config, string $root): ?string
54
        {
55
                if ($config->baseline !== null) {
1 ✔
56
                        return Helpers::toAbsolutePath($config->baseline, $root);
1 ✔
57
                }
58

59
                $files = array_map(fn(string $format) => "$root/" . self::DefaultName . ".$format", ['neon', 'php']);
1 ✔
60
                return array_find($files, fn(string $file) => is_file($file));
1 ✔
61
        }
62

63

64
        /** The name a baseline the configuration names none is written under, in the format of the configuration. */
65
        public static function getDefaultName(?string $configFile): string
66
        {
67
                return self::DefaultName . '.' . (Loader::detectFormat($configFile ?? '') ?? 'neon');
1 ✔
68
        }
69

70

71
        /**
72
         * The baseline of the file, or null before the first generation unless it is required; the name is judged either way.
73
         * @throws ConfigurationException
74
         */
75
        public static function load(string $file, bool $required = false): ?self
76
        {
77
                $format = self::resolveFormat($file);
1 ✔
78
                if (!is_file($file)) {
1 ✔
79
                        return $required
1 ✔
80
                                ? throw new ConfigurationException("Baseline file `$file` does not exist; `dresscode baseline` writes it.")
1 ✔
81
                                : null;
1 ✔
82
                }
83

84
                try {
85
                        $data = match ($format) {
1 ✔
86
                                'neon' => Neon::decode((string) @file_get_contents($file)), // @ a file that vanished meanwhile decodes as empty
1 ✔
87
                                'php' => require $file,
1 ✔
88
                        };
89
                } catch (NeonException $e) {
1 ✔
90
                        throw new ConfigurationException("Baseline file `$file` is not valid NEON: {$e->getMessage()}", previous: $e);
1 ✔
91
                }
92

93
                if ($data === null) {
1 ✔
94
                        return new self;
1 ✔
95
                } elseif (!is_array($data) || ($data['version'] ?? null) !== self::Version) {
1 ✔
96
                        throw new ConfigurationException(
1 ✔
97
                                "Baseline file `$file` is not of the version this DressCode writes; generate it again with `dresscode baseline`.",
1 ✔
98
                                'suppressing#baseline',
1 ✔
99
                        );
100
                }
101

102
                $baseline = new self;
1 ✔
103
                foreach (is_array($data['files'] ?? null) ? $data['files'] : [] as $path => $violations) {
1 ✔
104
                        foreach (is_array($violations) ? $violations : [] as $violation) {
1 ✔
105
                                if (
106
                                        !is_string($path)
1 ✔
107
                                        || !is_array($violation)
1 ✔
108
                                        || !is_string($violation['fingerprint'] ?? null)
1 ✔
109
                                        || !is_string($violation['decision'] ?? null)
1 ✔
110
                                        || !is_string($violation['message'] ?? null)
1 ✔
111
                                ) {
112
                                        throw new ConfigurationException("Baseline file `$file` has an unexpected shape.");
1 ✔
113
                                }
114

115
                                $baseline->add($path, $violation['fingerprint'], $violation['decision'], $violation['message']);
1 ✔
116
                        }
117
                }
118

119
                return $baseline;
1 ✔
120
        }
121

122

123
        /** @param list<FileResult|FileSummary> $results */
124
        public static function fromResults(array $results): self
125
        {
126
                $baseline = new self;
1 ✔
127
                foreach ($results as $result) {
1 ✔
128
                        foreach ($result->violations as $violation) {
1 ✔
129
                                // a refused risky fix that is only uncertain waits for what the project can tell, not for the baseline
130
                                if (!$violation->refused || !$violation->risk?->isResolvable()) {
1 ✔
131
                                        $baseline->add($result->path, $violation->fingerprint, $violation->decision, $violation->message);
1 ✔
132
                                }
133
                        }
134
                }
135

136
                return $baseline;
1 ✔
137
        }
138

139

140
        private function add(string $path, string $fingerprint, string $decision, string $message): void
141
        {
142
                $this->entries[$path][$fingerprint] = ['decision' => $decision, 'message' => $message];
1 ✔
143
                $this->unmatched[$path][$fingerprint] = true;
1 ✔
144
        }
1 ✔
145

146

147
        /**
148
         * Writes the entries in the format the extension of the file names.
149
         * @throws ConfigurationException
150
         */
151
        public function save(string $file): void
152
        {
153
                $files = [];
1 ✔
154
                ksort($this->entries, SORT_STRING);
1 ✔
155
                foreach ($this->entries as $path => $violations) {
1 ✔
156
                        foreach ($violations as $fingerprint => $entry) {
1 ✔
157
                                // a fingerprint of nothing but digits came back from the array key as an int, and NEON
158
                                // would then write it unquoted and read it back as a number the loader refuses
159
                                $files[$path][] = $entry + ['fingerprint' => (string) $fingerprint];
1 ✔
160
                        }
161
                }
162

163
                $content = match (self::resolveFormat($file)) {
1 ✔
164
                        'neon' => Neon::encode(['version' => self::Version, 'files' => $files], blockMode: true),
1 ✔
165
                        'php' => "<?php declare(strict_types=1);\n\nreturn "
166
                                . self::export(['version' => self::Version, 'files' => $files], "\n")
1 ✔
167
                                . ";\n",
1 ✔
168
                };
169
                if (@file_put_contents($file, $content) === false) { // @ is escalated to exception
1 ✔
UNCOV
170
                        throw new \RuntimeException("Cannot write the baseline file `$file`.");
×
171
                }
172
        }
1 ✔
173

174

175
        /**
176
         * The format the name of the file says, as it does for the configuration; anything else is a typo in the
177
         * configured name, not a format to guess at.
178
         * @return 'neon'|'php'
179
         * @throws ConfigurationException
180
         */
181
        private static function resolveFormat(string $file): string
182
        {
183
                return match (strtolower(pathinfo($file, PATHINFO_EXTENSION))) {
1 ✔
184
                        'neon' => 'neon',
1 ✔
185
                        'php' => 'php',
1 ✔
186
                        default => throw new ConfigurationException("Baseline file `$file` must be a `.neon` or a `.php` file."),
1 ✔
187
                };
188
        }
189

190

191
        /** @param array<int|string, mixed> $value */
192
        private static function export(array $value, string $indent): string
193
        {
194
                $items = [];
1 ✔
195
                foreach ($value as $key => $item) {
1 ✔
196
                        $items[] = $indent . "\t" . (is_string($key) ? var_export($key, return: true) . ' => ' : '')
1 ✔
197
                                . (is_array($item) ? self::export($item, $indent . "\t") : var_export($item, return: true)) . ',';
1 ✔
198
                }
199

200
                return $items ? '[' . implode('', $items) . "$indent]" : '[]';
1 ✔
201
        }
202

203

204
        public function count(): int
205
        {
206
                return array_sum(array_map(count(...), $this->entries));
1 ✔
207
        }
208

209

210
        /** Identity of the entries, for whatever caches a result that depends on them. */
211
        public function getHash(): string
212
        {
213
                return hash('xxh128', serialize($this->entries));
1 ✔
214
        }
215

216

217
        /** Whether the baseline holds this violation of the file, which is then not recorded. */
218
        public function has(string $path, string $fingerprint): bool
219
        {
220
                return isset($this->entries[$path][$fingerprint]);
1 ✔
221
        }
222

223

224
        /**
225
         * Records the entries a run matched; the run tells the baseline, because a file may have been
226
         * processed by a worker with a baseline of its own.
227
         * @param list<string> $fingerprints
228
         */
229
        public function markMatched(string $path, array $fingerprints): void
230
        {
231
                foreach ($fingerprints as $fingerprint) {
1 ✔
232
                        if (isset($this->unmatched[$path][$fingerprint])) {
1 ✔
233
                                unset($this->unmatched[$path][$fingerprint]);
1 ✔
234
                                $this->matched++;
1 ✔
235
                        }
236
                }
237
        }
1 ✔
238

239

240
        /** Violations of the run the baseline matched. */
241
        public function countMatched(): int
242
        {
243
                return $this->matched;
1 ✔
244
        }
245

246

247
        /**
248
         * Entries of the files of the run that no violation matched. An entry of a file the run did not process says
249
         * nothing, and neither does one of a decision the run was narrowed away from.
250
         * @param array<string, ?list<string>> $scope  path of a processed file => the decisions reported on it, null for any
251
         */
252
        public function countUnmatched(array $scope): int
253
        {
254
                $count = 0;
1 ✔
255
                foreach ($scope as $path => $decisions) {
1 ✔
256
                        foreach (array_keys($this->unmatched[$path] ?? []) as $fingerprint) {
1 ✔
257
                                if ($decisions === null || in_array($this->entries[$path][$fingerprint]['decision'], $decisions, true)) {
1 ✔
258
                                        $count++;
1 ✔
259
                                }
260
                        }
261
                }
262

263
                return $count;
1 ✔
264
        }
265
}
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