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

keradus / PHP-CS-Fixer / 17319949156

29 Aug 2025 09:20AM UTC coverage: 94.696% (-0.05%) from 94.744%
17319949156

push

github

keradus
CS

28333 of 29920 relevant lines covered (94.7%)

45.63 hits per line

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

71.14
/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
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
58
 */
59
#[AsCommand(name: 'describe', description: 'Describe rule / ruleset.')]
60
final class DescribeCommand extends Command
61
{
62
    /** @TODO PHP 8.0 - remove the property */
63
    protected static $defaultName = 'describe';
64

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

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

73
    private FixerFactory $fixerFactory;
74

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

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

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

89
        $this->fixerFactory = $fixerFactory;
14✔
90
    }
91

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

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

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

116
        $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers());
13✔
117

118
        $name = $input->getArgument('name');
13✔
119

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

124
                return 0;
×
125
            }
126

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

133
            $alternative = $matcher->match($name);
3✔
134

135
            $this->describeList($output, $e->getType());
3✔
136

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

145
        return 0;
10✔
146
    }
147

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

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

156
        $fixer = $fixers[$name];
10✔
157

158
        $definition = $fixer->getDefinition();
10✔
159

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

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

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

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

181
        $output->writeln($definition->getSummary());
10✔
182

183
        $description = $definition->getDescription();
10✔
184

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

189
        $output->writeln('');
10✔
190

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

195
            $output->writeln('');
×
196
        }
197

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

202
            $output->writeln('');
×
203
        }
204

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

208
            $riskyDescription = $definition->getRiskyDescription();
4✔
209

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

214
            $output->writeln('');
4✔
215
        }
216

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

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

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

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

241
                if (null !== $allowed) {
4✔
242
                    $line .= ' ('.Utils::naturalLanguageJoin($allowed, '').')';
4✔
243
                }
244

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

248
                if ($option->hasDefault()) {
4✔
249
                    $line .= \sprintf(
4✔
250
                        'defaults to <comment>%s</comment>',
4✔
251
                        Utils::toString($option->getDefault())
4✔
252
                    );
4✔
253
                } else {
254
                    $line .= '<comment>required</comment>';
×
255
                }
256

257
                if ($option instanceof DeprecatedFixerOption) {
4✔
258
                    $line .= '. <error>DEPRECATED</error>: '.Preg::replace(
3✔
259
                        '/(`.+?`)/',
3✔
260
                        '<info>$1</info>',
3✔
261
                        OutputFormatter::escape(lcfirst($option->getDeprecationMessage()))
3✔
262
                    );
3✔
263
                }
264

265
                if ($option instanceof AliasedFixerOption) {
4✔
266
                    $line .= '; <error>DEPRECATED</error> alias: <comment>'.$option->getAlias().'</comment>';
3✔
267
                }
268

269
                $output->writeln($line);
4✔
270
            }
271

272
            $output->writeln('');
4✔
273
        }
274

275
        $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample): bool {
10✔
276
            if ($codeSample instanceof VersionSpecificCodeSampleInterface) {
8✔
277
                return $codeSample->isSuitableFor(\PHP_VERSION_ID);
2✔
278
            }
279

280
            return true;
7✔
281
        });
10✔
282

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

296
            $differ = new FullDiffer();
7✔
297
            $diffFormatter = new DiffConsoleFormatter(
7✔
298
                $output->isDecorated(),
7✔
299
                \sprintf(
7✔
300
                    '<comment>   ---------- begin diff ----------</comment>%s%%s%s<comment>   ----------- end diff -----------</comment>',
7✔
301
                    \PHP_EOL,
7✔
302
                    \PHP_EOL
7✔
303
                )
7✔
304
            );
7✔
305

306
            foreach ($codeSamples as $index => $codeSample) {
7✔
307
                $old = $codeSample->getCode();
7✔
308
                $tokens = Tokens::fromCode($old);
7✔
309

310
                $configuration = $codeSample->getConfiguration();
7✔
311

312
                if ($fixer instanceof ConfigurableFixerInterface) {
7✔
313
                    $fixer->configure($configuration ?? []);
4✔
314
                }
315

316
                $file = $codeSample instanceof FileSpecificCodeSampleInterface
7✔
317
                    ? $codeSample->getSplFileInfo()
×
318
                    : new StdinFileInfo();
7✔
319

320
                $fixer->fix($file, $tokens);
7✔
321

322
                $diff = $differ->diff($old, $tokens->generateCode());
7✔
323

324
                if ($fixer instanceof ConfigurableFixerInterface) {
7✔
325
                    if (null === $configuration) {
4✔
326
                        $output->writeln(\sprintf(' * Example #%d. Fixing with the <comment>default</comment> configuration.', $index + 1));
4✔
327
                    } else {
328
                        $output->writeln(\sprintf(' * Example #%d. Fixing with configuration: <comment>%s</comment>.', $index + 1, Utils::toString($codeSample->getConfiguration())));
4✔
329
                    }
330
                } else {
331
                    $output->writeln(\sprintf(' * Example #%d.', $index + 1));
3✔
332
                }
333

334
                $output->writeln([$diffFormatter->format($diff, '   %s'), '']);
7✔
335
            }
336
        }
337

338
        $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name);
10✔
339

340
        if ([] !== $ruleSetConfigs) {
10✔
341
            ksort($ruleSetConfigs);
1✔
342
            $plural = 1 !== \count($ruleSetConfigs) ? 's' : '';
1✔
343
            $output->writeln("Fixer is part of the following rule set{$plural}:");
1✔
344

345
            $ruleSetDefinitions = RuleSets::getSetDefinitions();
1✔
346

347
            foreach ($ruleSetConfigs as $set => $config) {
1✔
348
                \assert(isset($ruleSetDefinitions[$set]));
1✔
349
                $ruleSetDescription = $ruleSetDefinitions[$set];
1✔
350
                $deprecatedDesc = ($ruleSetDescription instanceof DeprecatedRuleSetDescriptionInterface) ? ' *(deprecated)*' : '';
1✔
351
                if (null !== $config) {
1✔
352
                    $output->writeln(\sprintf('* <info>%s</info> with config: <comment>%s</comment>', $set.$deprecatedDesc, Utils::toString($config)));
1✔
353
                } else {
354
                    $output->writeln(\sprintf('* <info>%s</info> with <comment>default</comment> config', $set.$deprecatedDesc));
1✔
355
                }
356
            }
357

358
            $output->writeln('');
1✔
359
        }
360
    }
361

362
    private function describeSet(OutputInterface $output, string $name): void
363
    {
364
        if (!\in_array($name, $this->getSetNames(), true)) {
1✔
365
            throw new DescribeNameNotFoundException($name, 'set');
1✔
366
        }
367

368
        $ruleSetDefinitions = RuleSets::getSetDefinitions();
×
369
        $ruleSetDescription = $ruleSetDefinitions[$name];
×
370
        $fixers = $this->getFixers();
×
371

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

375
        $output->writeln($this->replaceRstLinks($ruleSetDescription->getDescription()));
×
376
        $output->writeln('');
×
377

378
        if ($ruleSetDescription instanceof DeprecatedRuleSetDescriptionInterface) {
×
379
            $successors = $ruleSetDescription->getSuccessorsNames();
×
380
            $message = [] === $successors
×
381
                ? \sprintf('it will be removed in version %d.0', Application::getMajorVersion() + 1)
×
382
                : \sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
×
383

384
            Utils::triggerDeprecation(new \RuntimeException(str_replace('`', '"', "Set \"{$name}\" is deprecated, {$message}.")));
×
385
            $message = Preg::replace('/(`[^`]+`)/', '<info>$1</info>', $message);
×
386
            $output->writeln(\sprintf('<error>DEPRECATED</error>: %s.', $message));
×
387
            $output->writeln('');
×
388
        }
389

390
        if ($ruleSetDescription->isRisky()) {
×
391
            $output->writeln('<error>This set contains risky rules.</error>');
×
392
            $output->writeln('');
×
393
        }
394

395
        $help = '';
×
396

397
        foreach ($ruleSetDescription->getRules() as $rule => $config) {
×
398
            if (str_starts_with($rule, '@')) {
×
399
                $set = $ruleSetDefinitions[$rule];
×
400
                $help .= \sprintf(
×
401
                    " * <info>%s</info>%s\n   | %s\n\n",
×
402
                    $rule,
×
403
                    $set->isRisky() ? ' <error>risky</error>' : '',
×
404
                    $this->replaceRstLinks($set->getDescription())
×
405
                );
×
406

407
                continue;
×
408
            }
409

410
            $fixer = $fixers[$rule];
×
411

412
            $definition = $fixer->getDefinition();
×
413
            $help .= \sprintf(
×
414
                " * <info>%s</info>%s\n   | %s\n%s\n",
×
415
                $rule,
×
416
                $fixer->isRisky() ? ' <error>risky</error>' : '',
×
417
                $definition->getSummary(),
×
418
                true !== $config ? \sprintf("   <comment>| Configuration: %s</comment>\n", Utils::toString($config)) : ''
×
419
            );
×
420
        }
421

422
        $output->write($help);
×
423
    }
424

425
    /**
426
     * @return array<string, FixerInterface>
427
     */
428
    private function getFixers(): array
429
    {
430
        if (null !== $this->fixers) {
12✔
431
            return $this->fixers;
2✔
432
        }
433

434
        $fixers = [];
12✔
435

436
        foreach ($this->fixerFactory->getFixers() as $fixer) {
12✔
437
            $fixers[$fixer->getName()] = $fixer;
12✔
438
        }
439

440
        $this->fixers = $fixers;
12✔
441
        ksort($this->fixers);
12✔
442

443
        return $this->fixers;
12✔
444
    }
445

446
    /**
447
     * @return list<string>
448
     */
449
    private function getSetNames(): array
450
    {
451
        if (null !== $this->setNames) {
1✔
452
            return $this->setNames;
1✔
453
        }
454

455
        $this->setNames = RuleSets::getSetDefinitionNames();
1✔
456

457
        return $this->setNames;
1✔
458
    }
459

460
    /**
461
     * @param string $type 'rule'|'set'
462
     */
463
    private function describeList(OutputInterface $output, string $type): void
464
    {
465
        if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
3✔
466
            return;
3✔
467
        }
468

469
        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'set' === $type) {
×
470
            $output->writeln('<comment>Defined sets:</comment>');
×
471

472
            $items = $this->getSetNames();
×
473
            foreach ($items as $item) {
×
474
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
475
            }
476
        }
477

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

481
            $items = array_keys($this->getFixers());
×
482
            foreach ($items as $item) {
×
483
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
484
            }
485
        }
486
    }
487

488
    private function replaceRstLinks(string $content): string
489
    {
490
        return Preg::replaceCallback(
×
491
            '/(`[^<]+<[^>]+>`_)/',
×
492
            static fn (array $matches) => Preg::replaceCallback(
×
493
                '/`(.*)<(.*)>`_/',
×
494
                static fn (array $matches): string => $matches[1].'('.$matches[2].')',
×
495
                $matches[1]
×
496
            ),
×
497
            $content
×
498
        );
×
499
    }
500
}
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