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

keradus / PHP-CS-Fixer / 17253231013

26 Aug 2025 11:46PM UTC coverage: 94.753% (+0.01%) from 94.741%
17253231013

push

github

keradus
chore: fix CS, somehow it missed the CI of .php-cs-fixer.well-defined-arrays.php

28316 of 29884 relevant lines covered (94.75%)

45.64 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
#[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();
×
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

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✔
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>.');
×
191
            $output->writeln('It is not covered with backward compatibility promise and may produce unstable or unexpected results.');
×
192

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

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

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

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

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

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

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

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

267
                $output->writeln($line);
4✔
268
            }
269

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

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

278
            return true;
7✔
279
        });
10✔
280

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

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

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

308
                $configuration = $codeSample->getConfiguration();
7✔
309

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

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

318
                $fixer->fix($file, $tokens);
7✔
319

320
                $diff = $differ->diff($old, $tokens->generateCode());
7✔
321

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

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

336
        $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name);
10✔
337

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

343
            $ruleSetDefinitions = RuleSets::getSetDefinitions();
1✔
344

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

356
            $output->writeln('');
1✔
357
        }
358
    }
359

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

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

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

373
        $output->writeln($this->replaceRstLinks($ruleSetDescription->getDescription()));
×
374
        $output->writeln('');
×
375

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

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

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

393
        $help = '';
×
394

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

405
                continue;
×
406
            }
407

408
            $fixer = $fixers[$rule];
×
409

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

420
        $output->write($help);
×
421
    }
422

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

432
        $fixers = [];
12✔
433

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

438
        $this->fixers = $fixers;
12✔
439
        ksort($this->fixers);
12✔
440

441
        return $this->fixers;
12✔
442
    }
443

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

453
        $this->setNames = RuleSets::getSetDefinitionNames();
1✔
454

455
        return $this->setNames;
1✔
456
    }
457

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

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

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

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

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

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