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

keradus / PHP-CS-Fixer / 16404146068

20 Jul 2025 08:55PM UTC coverage: 94.755% (-0.003%) from 94.758%
16404146068

push

github

web-flow
Merge branch 'master' into 701

35 of 35 new or added lines in 11 files covered. (100.0%)

1 existing line in 1 file now uncovered.

28184 of 29744 relevant lines covered (94.76%)

45.93 hits per line

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

73.36
/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\RuleSets;
37
use PhpCsFixer\StdinFileInfo;
38
use PhpCsFixer\Tokenizer\Tokens;
39
use PhpCsFixer\ToolInfo;
40
use PhpCsFixer\Utils;
41
use PhpCsFixer\WordMatcher;
42
use Symfony\Component\Console\Attribute\AsCommand;
43
use Symfony\Component\Console\Command\Command;
44
use Symfony\Component\Console\Formatter\OutputFormatter;
45
use Symfony\Component\Console\Input\InputArgument;
46
use Symfony\Component\Console\Input\InputInterface;
47
use Symfony\Component\Console\Input\InputOption;
48
use Symfony\Component\Console\Output\ConsoleOutputInterface;
49
use Symfony\Component\Console\Output\OutputInterface;
50

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

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

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

70
    private FixerFactory $fixerFactory;
71

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

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

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

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

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

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

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

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

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

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

121
                return 0;
×
122
            }
123

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

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

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

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

142
        return 0;
10✔
143
    }
144

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

337
            foreach ($ruleSetConfigs as $set => $config) {
1✔
338
                if (null !== $config) {
1✔
339
                    $output->writeln(\sprintf('* <info>%s</info> with config: <comment>%s</comment>', $set, Utils::toString($config)));
1✔
340
                } else {
341
                    $output->writeln(\sprintf('* <info>%s</info> with <comment>default</comment> config', $set));
1✔
342
                }
343
            }
344

345
            $output->writeln('');
1✔
346
        }
347
    }
348

349
    private function describeSet(OutputInterface $output, string $name): void
350
    {
351
        if (!\in_array($name, $this->getSetNames(), true)) {
1✔
352
            throw new DescribeNameNotFoundException($name, 'set');
1✔
353
        }
354

355
        $ruleSetDefinitions = RuleSets::getSetDefinitions();
×
356
        $fixers = $this->getFixers();
×
357

358
        $output->writeln(\sprintf('<fg=blue>Description of the <info>`%s`</info> set.</>', $ruleSetDefinitions[$name]->getName()));
×
359
        $output->writeln('');
×
360

361
        $output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription()));
×
362
        $output->writeln('');
×
363

364
        if ($ruleSetDefinitions[$name]->isRisky()) {
×
365
            $output->writeln('<error>This set contains risky rules.</error>');
×
366
            $output->writeln('');
×
367
        }
368

369
        $help = '';
×
370

371
        foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) {
×
372
            if (str_starts_with($rule, '@')) {
×
373
                $set = $ruleSetDefinitions[$rule];
×
374
                $help .= \sprintf(
×
375
                    " * <info>%s</info>%s\n   | %s\n\n",
×
376
                    $rule,
×
377
                    $set->isRisky() ? ' <error>risky</error>' : '',
×
378
                    $this->replaceRstLinks($set->getDescription())
×
379
                );
×
380

381
                continue;
×
382
            }
383

UNCOV
384
            $fixer = $fixers[$rule];
×
385

386
            $definition = $fixer->getDefinition();
×
387
            $help .= \sprintf(
×
388
                " * <info>%s</info>%s\n   | %s\n%s\n",
×
389
                $rule,
×
390
                $fixer->isRisky() ? ' <error>risky</error>' : '',
×
391
                $definition->getSummary(),
×
392
                true !== $config ? \sprintf("   <comment>| Configuration: %s</comment>\n", Utils::toString($config)) : ''
×
393
            );
×
394
        }
395

396
        $output->write($help);
×
397
    }
398

399
    /**
400
     * @return array<string, FixerInterface>
401
     */
402
    private function getFixers(): array
403
    {
404
        if (null !== $this->fixers) {
12✔
405
            return $this->fixers;
2✔
406
        }
407

408
        $fixers = [];
12✔
409

410
        foreach ($this->fixerFactory->getFixers() as $fixer) {
12✔
411
            $fixers[$fixer->getName()] = $fixer;
12✔
412
        }
413

414
        $this->fixers = $fixers;
12✔
415
        ksort($this->fixers);
12✔
416

417
        return $this->fixers;
12✔
418
    }
419

420
    /**
421
     * @return list<string>
422
     */
423
    private function getSetNames(): array
424
    {
425
        if (null !== $this->setNames) {
1✔
426
            return $this->setNames;
1✔
427
        }
428

429
        $this->setNames = RuleSets::getSetDefinitionNames();
1✔
430

431
        return $this->setNames;
1✔
432
    }
433

434
    /**
435
     * @param string $type 'rule'|'set'
436
     */
437
    private function describeList(OutputInterface $output, string $type): void
438
    {
439
        if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
3✔
440
            return;
3✔
441
        }
442

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

446
            $items = $this->getSetNames();
×
447
            foreach ($items as $item) {
×
448
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
449
            }
450
        }
451

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

455
            $items = array_keys($this->getFixers());
×
456
            foreach ($items as $item) {
×
457
                $output->writeln(\sprintf('* <info>%s</info>', $item));
×
458
            }
459
        }
460
    }
461

462
    private function replaceRstLinks(string $content): string
463
    {
464
        return Preg::replaceCallback(
×
465
            '/(`[^<]+<[^>]+>`_)/',
×
466
            static fn (array $matches) => Preg::replaceCallback(
×
467
                '/`(.*)<(.*)>`_/',
×
468
                static fn (array $matches): string => $matches[1].'('.$matches[2].')',
×
469
                $matches[1]
×
470
            ),
×
471
            $content
×
472
        );
×
473
    }
474
}
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