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

keradus / PHP-CS-Fixer / 17409000363

02 Sep 2025 03:52PM UTC coverage: 94.698% (+0.006%) from 94.692%
17409000363

push

github

keradus
move triggerDeprecation

22 of 28 new or added lines in 12 files covered. (78.57%)

4 existing lines in 2 files now uncovered.

28419 of 30010 relevant lines covered (94.7%)

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

53
/**
54
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
55
 *
56
 * @internal
57
 *
58
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
59
 */
60
#[AsCommand(name: 'describe', description: 'Describe rule / ruleset.')]
61
final class DescribeCommand extends Command
62
{
63
    /** @TODO PHP 8.0 - remove the property */
64
    protected static $defaultName = 'describe';
65

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

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

74
    private FixerFactory $fixerFactory;
75

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

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

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

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

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

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

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

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

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

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

125
                return 0;
×
126
            }
127

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

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

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

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

146
        return 0;
10✔
147
    }
148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

396
        $help = '';
×
397

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

408
                continue;
×
409
            }
410

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

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

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

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

435
        $fixers = [];
12✔
436

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

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

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

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

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

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

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

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

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

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

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

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