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

keradus / PHP-CS-Fixer / 16839019843

06 Aug 2025 10:45PM UTC coverage: 94.73% (-0.02%) from 94.749%
16839019843

push

github

web-flow
feat: introduce `PER-CS3.0` rulsets (#8841)

21 of 21 new or added lines in 5 files covered. (100.0%)

241 existing lines in 18 files now uncovered.

28255 of 29827 relevant lines covered (94.73%)

45.87 hits per line

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

70.78
/src/Console/Command/DescribeCommand.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <fabien@symfony.com>
9
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14

15
namespace PhpCsFixer\Console\Command;
16

17
use PhpCsFixer\Config;
18
use PhpCsFixer\Console\Application;
19
use PhpCsFixer\Console\ConfigurationResolver;
20
use PhpCsFixer\Differ\DiffConsoleFormatter;
21
use PhpCsFixer\Differ\FullDiffer;
22
use PhpCsFixer\Documentation\FixerDocumentGenerator;
23
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
24
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
25
use PhpCsFixer\Fixer\ExperimentalFixerInterface;
26
use PhpCsFixer\Fixer\FixerInterface;
27
use PhpCsFixer\Fixer\InternalFixerInterface;
28
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
29
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
30
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
31
use PhpCsFixer\FixerDefinition\CodeSampleInterface;
32
use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
33
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
34
use PhpCsFixer\FixerFactory;
35
use PhpCsFixer\Preg;
36
use PhpCsFixer\RuleSet\DeprecatedRuleSetDescriptionInterface;
37
use PhpCsFixer\RuleSet\RuleSets;
38
use PhpCsFixer\StdinFileInfo;
39
use PhpCsFixer\Tokenizer\Tokens;
40
use PhpCsFixer\ToolInfo;
41
use PhpCsFixer\Utils;
42
use PhpCsFixer\WordMatcher;
43
use Symfony\Component\Console\Attribute\AsCommand;
44
use Symfony\Component\Console\Command\Command;
45
use Symfony\Component\Console\Formatter\OutputFormatter;
46
use Symfony\Component\Console\Input\InputArgument;
47
use Symfony\Component\Console\Input\InputInterface;
48
use Symfony\Component\Console\Input\InputOption;
49
use Symfony\Component\Console\Output\ConsoleOutputInterface;
50
use Symfony\Component\Console\Output\OutputInterface;
51

52
/**
53
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
54
 *
55
 * @internal
56
 */
57
#[AsCommand(name: 'describe', description: 'Describe rule / ruleset.')]
58
final class DescribeCommand extends Command
59
{
60
    /** @TODO PHP 8.0 - remove the property */
61
    protected static $defaultName = 'describe';
62

63
    /** @TODO PHP 8.0 - remove the property */
64
    protected static $defaultDescription = 'Describe rule / ruleset.';
65

66
    /**
67
     * @var ?list<string>
68
     */
69
    private ?array $setNames = null;
70

71
    private FixerFactory $fixerFactory;
72

73
    /**
74
     * @var null|array<string, FixerInterface>
75
     */
76
    private ?array $fixers = null;
77

78
    public function __construct(?FixerFactory $fixerFactory = null)
79
    {
80
        parent::__construct();
14✔
81

82
        if (null === $fixerFactory) {
14✔
83
            $fixerFactory = new FixerFactory();
14✔
84
            $fixerFactory->registerBuiltInFixers();
14✔
85
        }
86

87
        $this->fixerFactory = $fixerFactory;
14✔
88
    }
89

90
    protected function configure(): void
91
    {
92
        $this->setDefinition(
14✔
93
            [
14✔
94
                new InputArgument('name', InputArgument::REQUIRED, 'Name of rule / set.', null, fn () => array_merge($this->getSetNames(), array_keys($this->getFixers()))),
14✔
95
                new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'),
14✔
96
            ]
14✔
97
        );
14✔
98
    }
99

100
    protected function execute(InputInterface $input, OutputInterface $output): int
101
    {
102
        if ($output instanceof ConsoleOutputInterface) {
13✔
103
            $stdErr = $output->getErrorOutput();
×
UNCOV
104
            $stdErr->writeln(Application::getAboutWithRuntime(true));
×
105
        }
106

107
        $resolver = new ConfigurationResolver(
13✔
108
            new Config(),
13✔
109
            ['config' => $input->getOption('config')],
13✔
110
            getcwd(),
13✔
111
            new ToolInfo()
13✔
112
        );
13✔
113

114
        $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers());
13✔
115

116
        $name = $input->getArgument('name');
13✔
117

118
        try {
119
            if (str_starts_with($name, '@')) {
13✔
120
                $this->describeSet($output, $name);
1✔
121

UNCOV
122
                return 0;
×
123
            }
124

125
            $this->describeRule($output, $name);
12✔
126
        } catch (DescribeNameNotFoundException $e) {
3✔
127
            $matcher = new WordMatcher(
3✔
128
                'set' === $e->getType() ? $this->getSetNames() : array_keys($this->getFixers())
3✔
129
            );
3✔
130

131
            $alternative = $matcher->match($name);
3✔
132

133
            $this->describeList($output, $e->getType());
3✔
134

135
            throw new \InvalidArgumentException(\sprintf(
3✔
136
                '%s "%s" not found.%s',
3✔
137
                ucfirst($e->getType()),
3✔
138
                $name,
3✔
139
                null === $alternative ? '' : ' Did you mean "'.$alternative.'"?'
3✔
140
            ));
3✔
141
        }
142

143
        return 0;
10✔
144
    }
145

146
    private function describeRule(OutputInterface $output, string $name): void
147
    {
148
        $fixers = $this->getFixers();
12✔
149

150
        if (!isset($fixers[$name])) {
12✔
151
            throw new DescribeNameNotFoundException($name, 'rule');
2✔
152
        }
153

154
        $fixer = $fixers[$name];
10✔
155

156
        $definition = $fixer->getDefinition();
10✔
157

158
        $output->writeln(\sprintf('<fg=blue>Description of the <info>`%s`</info> rule.</>', $name));
10✔
159
        $output->writeln('');
10✔
160

161
        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
10✔
162
            $output->writeln(\sprintf('Fixer class: <comment>%s</comment>.', \get_class($fixer)));
1✔
163
            $output->writeln('');
1✔
164
        }
165

166
        if ($fixer instanceof DeprecatedFixerInterface) {
10✔
167
            $successors = $fixer->getSuccessorsNames();
3✔
168
            $message = [] === $successors
3✔
UNCOV
169
                ? \sprintf('it will be removed in version %d.0', Application::getMajorVersion() + 1)
×
170
                : \sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
3✔
171

172
            $endMessage = '. '.ucfirst($message);
3✔
173
            Utils::triggerDeprecation(new \RuntimeException(str_replace('`', '"', "Rule \"{$name}\" is deprecated{$endMessage}.")));
3✔
174
            $message = Preg::replace('/(`[^`]+`)/', '<info>$1</info>', $message);
3✔
175
            $output->writeln(\sprintf('<error>DEPRECATED</error>: %s.', $message));
3✔
176
            $output->writeln('');
3✔
177
        }
178

179
        $output->writeln($definition->getSummary());
10✔
180

181
        $description = $definition->getDescription();
10✔
182

183
        if (null !== $description) {
10✔
184
            $output->writeln($description);
7✔
185
        }
186

187
        $output->writeln('');
10✔
188

189
        if ($fixer instanceof ExperimentalFixerInterface) {
10✔
190
            $output->writeln('<error>Fixer applying this rule is EXPERIMENTAL.</error>.');
×
UNCOV
191
            $output->writeln('It is not covered with backward compatibility promise and may produce unstable or unexpected results.');
×
192

UNCOV
193
            $output->writeln('');
×
194
        }
195

196
        if ($fixer instanceof InternalFixerInterface) {
10✔
197
            $output->writeln('<error>Fixer applying this rule is INTERNAL.</error>.');
×
UNCOV
198
            $output->writeln('It is expected to be used only on PHP CS Fixer project itself.');
×
199

UNCOV
200
            $output->writeln('');
×
201
        }
202

203
        if ($fixer->isRisky()) {
10✔
204
            $output->writeln('<error>Fixer applying this rule is RISKY.</error>');
4✔
205

206
            $riskyDescription = $definition->getRiskyDescription();
4✔
207

208
            if (null !== $riskyDescription) {
4✔
209
                $output->writeln($riskyDescription);
3✔
210
            }
211

212
            $output->writeln('');
4✔
213
        }
214

215
        if ($fixer instanceof ConfigurableFixerInterface) {
10✔
216
            $configurationDefinition = $fixer->getConfigurationDefinition();
4✔
217
            $options = $configurationDefinition->getOptions();
4✔
218

219
            $output->writeln(\sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's'));
4✔
220

221
            foreach ($options as $option) {
4✔
222
                $line = '* <info>'.OutputFormatter::escape($option->getName()).'</info>';
4✔
223
                $allowed = HelpCommand::getDisplayableAllowedValues($option);
4✔
224

225
                if (null === $allowed) {
4✔
226
                    $allowed = array_map(
4✔
227
                        static fn (string $type): string => '<comment>'.$type.'</comment>',
4✔
228
                        $option->getAllowedTypes(),
4✔
229
                    );
4✔
230
                } else {
231
                    $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset
4✔
232
                        ? 'a subset of <comment>'.Utils::toString($value->getAllowedValues()).'</comment>'
3✔
233
                        : '<comment>'.Utils::toString($value).'</comment>', $allowed);
4✔
234
                }
235

236
                $line .= ' ('.Utils::naturalLanguageJoin($allowed, '').')';
4✔
237

238
                $description = Preg::replace('/(`.+?`)/', '<info>$1</info>', OutputFormatter::escape($option->getDescription()));
4✔
239
                $line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; ';
4✔
240

241
                if ($option->hasDefault()) {
4✔
242
                    $line .= \sprintf(
4✔
243
                        'defaults to <comment>%s</comment>',
4✔
244
                        Utils::toString($option->getDefault())
4✔
245
                    );
4✔
246
                } else {
UNCOV
247
                    $line .= '<comment>required</comment>';
×
248
                }
249

250
                if ($option instanceof DeprecatedFixerOption) {
4✔
251
                    $line .= '. <error>DEPRECATED</error>: '.Preg::replace(
3✔
252
                        '/(`.+?`)/',
3✔
253
                        '<info>$1</info>',
3✔
254
                        OutputFormatter::escape(lcfirst($option->getDeprecationMessage()))
3✔
255
                    );
3✔
256
                }
257

258
                if ($option instanceof AliasedFixerOption) {
4✔
259
                    $line .= '; <error>DEPRECATED</error> alias: <comment>'.$option->getAlias().'</comment>';
3✔
260
                }
261

262
                $output->writeln($line);
4✔
263
            }
264

265
            $output->writeln('');
4✔
266
        }
267

268
        $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample): bool {
10✔
269
            if ($codeSample instanceof VersionSpecificCodeSampleInterface) {
8✔
270
                return $codeSample->isSuitableFor(\PHP_VERSION_ID);
2✔
271
            }
272

273
            return true;
7✔
274
        });
10✔
275

276
        if (0 === \count($definition->getCodeSamples())) {
10✔
277
            $output->writeln([
2✔
278
                'Fixing examples are not available for this rule.',
2✔
279
                '',
2✔
280
            ]);
2✔
281
        } elseif (0 === \count($codeSamples)) {
8✔
282
            $output->writeln([
1✔
283
                'Fixing examples <error>cannot be</error> demonstrated on the current PHP version.',
1✔
284
                '',
1✔
285
            ]);
1✔
286
        } else {
287
            $output->writeln('Fixing examples:');
7✔
288

289
            $differ = new FullDiffer();
7✔
290
            $diffFormatter = new DiffConsoleFormatter(
7✔
291
                $output->isDecorated(),
7✔
292
                \sprintf(
7✔
293
                    '<comment>   ---------- begin diff ----------</comment>%s%%s%s<comment>   ----------- end diff -----------</comment>',
7✔
294
                    \PHP_EOL,
7✔
295
                    \PHP_EOL
7✔
296
                )
7✔
297
            );
7✔
298

299
            foreach ($codeSamples as $index => $codeSample) {
7✔
300
                $old = $codeSample->getCode();
7✔
301
                $tokens = Tokens::fromCode($old);
7✔
302

303
                $configuration = $codeSample->getConfiguration();
7✔
304

305
                if ($fixer instanceof ConfigurableFixerInterface) {
7✔
306
                    $fixer->configure($configuration ?? []);
4✔
307
                }
308

309
                $file = $codeSample instanceof FileSpecificCodeSampleInterface
7✔
UNCOV
310
                    ? $codeSample->getSplFileInfo()
×
311
                    : new StdinFileInfo();
7✔
312

313
                $fixer->fix($file, $tokens);
7✔
314

315
                $diff = $differ->diff($old, $tokens->generateCode());
7✔
316

317
                if ($fixer instanceof ConfigurableFixerInterface) {
7✔
318
                    if (null === $configuration) {
4✔
319
                        $output->writeln(\sprintf(' * Example #%d. Fixing with the <comment>default</comment> configuration.', $index + 1));
4✔
320
                    } else {
321
                        $output->writeln(\sprintf(' * Example #%d. Fixing with configuration: <comment>%s</comment>.', $index + 1, Utils::toString($codeSample->getConfiguration())));
4✔
322
                    }
323
                } else {
324
                    $output->writeln(\sprintf(' * Example #%d.', $index + 1));
3✔
325
                }
326

327
                $output->writeln([$diffFormatter->format($diff, '   %s'), '']);
7✔
328
            }
329
        }
330

331
        $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name);
10✔
332

333
        if ([] !== $ruleSetConfigs) {
10✔
334
            ksort($ruleSetConfigs);
1✔
335
            $plural = 1 !== \count($ruleSetConfigs) ? 's' : '';
1✔
336
            $output->writeln("Fixer is part of the following rule set{$plural}:");
1✔
337

338
            $ruleSetDefinitions = RuleSets::getSetDefinitions();
1✔
339

340
            foreach ($ruleSetConfigs as $set => $config) {
1✔
341
                \assert(isset($ruleSetDefinitions[$set]));
1✔
342
                $ruleSetDescription = $ruleSetDefinitions[$set];
1✔
343
                $deprecatedDesc = ($ruleSetDescription instanceof DeprecatedRuleSetDescriptionInterface) ? ' *(deprecated)*' : '';
1✔
344
                if (null !== $config) {
1✔
345
                    $output->writeln(\sprintf('* <info>%s</info> with config: <comment>%s</comment>', $set.$deprecatedDesc, Utils::toString($config)));
1✔
346
                } else {
347
                    $output->writeln(\sprintf('* <info>%s</info> with <comment>default</comment> config', $set.$deprecatedDesc));
1✔
348
                }
349
            }
350

351
            $output->writeln('');
1✔
352
        }
353
    }
354

355
    private function describeSet(OutputInterface $output, string $name): void
356
    {
357
        if (!\in_array($name, $this->getSetNames(), true)) {
1✔
358
            throw new DescribeNameNotFoundException($name, 'set');
1✔
359
        }
360

361
        $ruleSetDefinitions = RuleSets::getSetDefinitions();
×
362
        $ruleSetDescription = $ruleSetDefinitions[$name];
×
UNCOV
363
        $fixers = $this->getFixers();
×
364

365
        $output->writeln(\sprintf('<fg=blue>Description of the <info>`%s`</info> set.</>', $ruleSetDescription->getName()));
×
366
        $output->writeln('');
×
367

UNCOV
368
        $output->writeln($this->replaceRstLinks($ruleSetDescription->getDescription()));
×
369
        $output->writeln('');
×
370

371
        if ($ruleSetDescription instanceof DeprecatedRuleSetDescriptionInterface) {
×
372
            $successors = $ruleSetDescription->getSuccessorsNames();
×
373
            $message = [] === $successors
×
374
                ? \sprintf('it will be removed in version %d.0', Application::getMajorVersion() + 1)
×
375
                : \sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
×
376

377
            Utils::triggerDeprecation(new \RuntimeException(str_replace('`', '"', "Set \"{$name}\" is deprecated, {$message}.")));
×
378
            $message = Preg::replace('/(`[^`]+`)/', '<info>$1</info>', $message);
×
379
            $output->writeln(\sprintf('<error>DEPRECATED</error>: %s.', $message));
×
UNCOV
380
            $output->writeln('');
×
381
        }
382

UNCOV
383
        if ($ruleSetDescription->isRisky()) {
×
384
            $output->writeln('<error>This set contains risky rules.</error>');
×
UNCOV
385
            $output->writeln('');
×
386
        }
387

388
        $help = '';
×
389

390
        foreach ($ruleSetDescription->getRules() as $rule => $config) {
×
391
            if (str_starts_with($rule, '@')) {
×
392
                $set = $ruleSetDefinitions[$rule];
×
393
                $help .= \sprintf(
×
UNCOV
394
                    " * <info>%s</info>%s\n   | %s\n\n",
×
UNCOV
395
                    $rule,
×
396
                    $set->isRisky() ? ' <error>risky</error>' : '',
×
UNCOV
397
                    $this->replaceRstLinks($set->getDescription())
×
UNCOV
398
                );
×
399

UNCOV
400
                continue;
×
401
            }
402

UNCOV
403
            $fixer = $fixers[$rule];
×
404

UNCOV
405
            $definition = $fixer->getDefinition();
×
UNCOV
406
            $help .= \sprintf(
×
UNCOV
407
                " * <info>%s</info>%s\n   | %s\n%s\n",
×
UNCOV
408
                $rule,
×
UNCOV
409
                $fixer->isRisky() ? ' <error>risky</error>' : '',
×
UNCOV
410
                $definition->getSummary(),
×
UNCOV
411
                true !== $config ? \sprintf("   <comment>| Configuration: %s</comment>\n", Utils::toString($config)) : ''
×
UNCOV
412
            );
×
413
        }
414

UNCOV
415
        $output->write($help);
×
416
    }
417

418
    /**
419
     * @return array<string, FixerInterface>
420
     */
421
    private function getFixers(): array
422
    {
423
        if (null !== $this->fixers) {
12✔
424
            return $this->fixers;
2✔
425
        }
426

427
        $fixers = [];
12✔
428

429
        foreach ($this->fixerFactory->getFixers() as $fixer) {
12✔
430
            $fixers[$fixer->getName()] = $fixer;
12✔
431
        }
432

433
        $this->fixers = $fixers;
12✔
434
        ksort($this->fixers);
12✔
435

436
        return $this->fixers;
12✔
437
    }
438

439
    /**
440
     * @return list<string>
441
     */
442
    private function getSetNames(): array
443
    {
444
        if (null !== $this->setNames) {
1✔
445
            return $this->setNames;
1✔
446
        }
447

448
        $this->setNames = RuleSets::getSetDefinitionNames();
1✔
449

450
        return $this->setNames;
1✔
451
    }
452

453
    /**
454
     * @param string $type 'rule'|'set'
455
     */
456
    private function describeList(OutputInterface $output, string $type): void
457
    {
458
        if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
3✔
459
            return;
3✔
460
        }
461

UNCOV
462
        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'set' === $type) {
×
UNCOV
463
            $output->writeln('<comment>Defined sets:</comment>');
×
464

465
            $items = $this->getSetNames();
×
466
            foreach ($items as $item) {
×
467
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
468
            }
469
        }
470

471
        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'rule' === $type) {
×
472
            $output->writeln('<comment>Defined rules:</comment>');
×
473

UNCOV
474
            $items = array_keys($this->getFixers());
×
UNCOV
475
            foreach ($items as $item) {
×
UNCOV
476
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
477
            }
478
        }
479
    }
480

481
    private function replaceRstLinks(string $content): string
482
    {
UNCOV
483
        return Preg::replaceCallback(
×
UNCOV
484
            '/(`[^<]+<[^>]+>`_)/',
×
UNCOV
485
            static fn (array $matches) => Preg::replaceCallback(
×
UNCOV
486
                '/`(.*)<(.*)>`_/',
×
UNCOV
487
                static fn (array $matches): string => $matches[1].'('.$matches[2].')',
×
UNCOV
488
                $matches[1]
×
UNCOV
489
            ),
×
UNCOV
490
            $content
×
UNCOV
491
        );
×
492
    }
493
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc