• 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

82.11
/src/Console/Command/FixCommand.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\ConfigInterface;
19
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
20
use PhpCsFixer\Console\Application;
21
use PhpCsFixer\Console\ConfigurationResolver;
22
use PhpCsFixer\Console\Output\ErrorOutput;
23
use PhpCsFixer\Console\Output\OutputContext;
24
use PhpCsFixer\Console\Output\Progress\ProgressOutputFactory;
25
use PhpCsFixer\Console\Output\Progress\ProgressOutputType;
26
use PhpCsFixer\Console\Report\FixReport\ReporterFactory;
27
use PhpCsFixer\Console\Report\FixReport\ReportSummary;
28
use PhpCsFixer\Error\ErrorsManager;
29
use PhpCsFixer\Fixer\FixerInterface;
30
use PhpCsFixer\FixerFactory;
31
use PhpCsFixer\RuleSet\RuleSets;
32
use PhpCsFixer\Runner\Event\FileProcessed;
33
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
34
use PhpCsFixer\Runner\Runner;
35
use PhpCsFixer\ToolInfoInterface;
36
use Symfony\Component\Console\Attribute\AsCommand;
37
use Symfony\Component\Console\Command\Command;
38
use Symfony\Component\Console\Formatter\OutputFormatter;
39
use Symfony\Component\Console\Input\InputArgument;
40
use Symfony\Component\Console\Input\InputInterface;
41
use Symfony\Component\Console\Input\InputOption;
42
use Symfony\Component\Console\Output\ConsoleOutputInterface;
43
use Symfony\Component\Console\Output\OutputInterface;
44
use Symfony\Component\Console\Terminal;
45
use Symfony\Component\EventDispatcher\EventDispatcher;
46
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
47
use Symfony\Component\Stopwatch\Stopwatch;
48

49
/**
50
 * @author Fabien Potencier <fabien@symfony.com>
51
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
52
 *
53
 * @final
54
 *
55
 * @internal
56
 *
57
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
58
 */
59
#[AsCommand(name: 'fix', description: 'Fixes a directory or a file.')]
60
/* final */ class FixCommand extends Command
61
{
62
    /** @TODO PHP 8.0 - remove the property */
63
    protected static $defaultName = 'fix';
64

65
    /** @TODO PHP 8.0 - remove the property */
66
    protected static $defaultDescription = 'Fixes a directory or a file.';
67

68
    private EventDispatcherInterface $eventDispatcher;
69

70
    private ErrorsManager $errorsManager;
71

72
    private Stopwatch $stopwatch;
73

74
    private ConfigInterface $defaultConfig;
75

76
    private ToolInfoInterface $toolInfo;
77

78
    private ProgressOutputFactory $progressOutputFactory;
79

80
    public function __construct(ToolInfoInterface $toolInfo)
81
    {
82
        parent::__construct();
5✔
83

84
        $this->eventDispatcher = new EventDispatcher();
5✔
85
        $this->errorsManager = new ErrorsManager();
5✔
86
        $this->stopwatch = new Stopwatch();
5✔
87
        $this->defaultConfig = new Config();
5✔
88
        $this->toolInfo = $toolInfo;
5✔
89
        $this->progressOutputFactory = new ProgressOutputFactory();
5✔
90
    }
91

92
    /**
93
     * {@inheritdoc}
94
     *
95
     * Override here to only generate the help copy when used.
96
     */
97
    public function getHelp(): string
98
    {
99
        return <<<'EOF'
×
100
            The <info>%command.name%</info> command tries to %command.name% as much coding standards
101
            problems as possible on a given file or files in a given directory and its subdirectories:
102

103
                <info>$ php %command.full_name% /path/to/dir</info>
104
                <info>$ php %command.full_name% /path/to/file</info>
105

106
            By default <comment>--path-mode</comment> is set to `override`, which means, that if you specify the path to a file or a directory via
107
            command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use <comment>--path-mode=intersection</comment>
108
            to merge paths from the config file and from the argument:
109

110
                <info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>
111

112
            The <comment>--format</comment> option for the output format. Supported formats are `@auto` (default one on v4+), `txt` (default one on v3), `json`, `xml`, `checkstyle`, `junit` and `gitlab`.
113

114
            * `@auto` aims to auto-select best reporter for given CI or local execution (resolution into best format is outside of BC promise and is future-ready)
115
              * `gitlab` for GitLab
116
            * `@auto,{format}` takes `@auto` under CI, and {format} otherwise
117

118
            NOTE: the output for the following formats are generated in accordance with schemas
119

120
            * `checkstyle` follows the common `"checkstyle" XML schema </doc/schemas/fix/checkstyle.xsd>`_
121
            * `gitlab` follows the `codeclimate JSON schema </doc/schemas/fix/codeclimate.json>`_
122
            * `json` follows the `own JSON schema </doc/schemas/fix/schema.json>`_
123
            * `junit` follows the `JUnit XML schema from Jenkins </doc/schemas/fix/junit-10.xsd>`_
124
            * `xml` follows the `own XML schema </doc/schemas/fix/xml.xsd>`_
125

126
            The <comment>--quiet</comment> Do not output any message.
127

128
            The <comment>--verbose</comment> option will show the applied rules. When using the `txt` format it will also display progress notifications.
129

130
            NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose
131

132
            * `-v`: verbose
133
            * `-vv`: very verbose
134
            * `-vvv`: debug
135

136
            The <comment>--rules</comment> option limits the rules to apply to the
137
            project:
138

139
            EOF. /* @TODO: 4.0 - change to @PER */ <<<'EOF'
×
140

141
                <info>$ php %command.full_name% /path/to/project --rules=@PSR12</info>
142

143
            By default the PSR-12 rules are used.
144

145
            The <comment>--rules</comment> option lets you choose the exact rules to
146
            apply (the rule names must be separated by a comma):
147

148
                <info>$ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type</info>
149

150
            You can also exclude the rules you don't want by placing a dash in front of the rule name, if this is more convenient,
151
            using <comment>-name_of_fixer</comment>:
152

153
                <info>$ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type</info>
154

155
            When using combinations of exact and exclude rules, applying exact rules along with above excluded results:
156

157
                <info>$ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison</info>
158

159
            Complete configuration for rules can be supplied using a `json` formatted string.
160

161
                <info>$ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}'</info>
162

163
            The <comment>--dry-run</comment> flag will run the fixer without making changes to your files.
164

165
            The <comment>--sequential</comment> flag will enforce sequential analysis even if parallel config is provided.
166

167
            The <comment>--diff</comment> flag can be used to let the fixer output all the changes it makes.
168

169
            The <comment>--allow-risky</comment> option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file.
170
            A rule is considered risky if it could change code behaviour. By default no risky rules are run.
171

172
            The <comment>--stop-on-violation</comment> flag stops the execution upon first file that needs to be fixed.
173

174
            The <comment>--show-progress</comment> option allows you to choose the way process progress is rendered:
175

176
            * <comment>none</comment>: disables progress output;
177
            * <comment>dots</comment>: multiline progress output with number of files and percentage on each line.
178
            * <comment>bar</comment>: single line progress output with number of files and calculated percentage.
179

180
            If the option is not provided, it defaults to <comment>bar</comment> unless a config file that disables output is used, in which case it defaults to <comment>none</comment>. This option has no effect if the verbosity of the command is less than <comment>verbose</comment>.
181

182
                <info>$ php %command.full_name% --verbose --show-progress=dots</info>
183

184
            By using <comment>--using-cache</comment> option with `yes` or `no` you can set if the caching
185
            mechanism should be used.
186

187
            The command can also read from standard input, in which case it won't
188
            automatically fix anything:
189

190
                <info>$ cat foo.php | php %command.full_name% --diff -</info>
191

192
            Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that
193
            would be default in next MAJOR release and to forbid using deprecated configuration:
194

195
                <info>$ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff</info>
196

197
            Exit code
198
            ---------
199

200
            Exit code of the `%command.name%` command is built using following bit flags:
201

202
            *  0 - OK.
203
            *  1 - General error (or PHP minimal requirement not matched).
204
            *  4 - Some files have invalid syntax (only in dry-run mode).
205
            *  8 - Some files need fixing (only in dry-run mode).
206
            * 16 - Configuration error of the application.
207
            * 32 - Configuration error of a Fixer.
208
            * 64 - Exception raised within the application.
209

210
            EOF;
×
211
    }
212

213
    protected function configure(): void
214
    {
215
        $reporterFactory = new ReporterFactory();
5✔
216
        $reporterFactory->registerBuiltInReporters();
5✔
217
        $formats = $reporterFactory->getFormats();
5✔
218
        array_unshift($formats, '@auto', '@auto,txt');
5✔
219

220
        $progessOutputTypes = ProgressOutputType::all();
5✔
221

222
        $this->setDefinition(
5✔
223
            [
5✔
224
                new InputArgument('path', InputArgument::IS_ARRAY, 'The path(s) that rules will be run against (each path can be a file or directory).'),
5✔
225
                new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Specify path mode (%s).', ConfigurationResolver::PATH_MODE_VALUES), ConfigurationResolver::PATH_MODE_OVERRIDE, ConfigurationResolver::PATH_MODE_VALUES),
5✔
226
                new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Are risky fixers allowed (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES),
5✔
227
                new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'),
5✔
228
                new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'),
5✔
229
                new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.', null, static function () {
5✔
230
                    $fixerFactory = new FixerFactory();
×
231
                    $fixerFactory->registerBuiltInFixers();
×
232
                    $fixers = array_map(static fn (FixerInterface $fixer) => $fixer->getName(), $fixerFactory->getFixers());
×
233

234
                    return array_merge(RuleSets::getSetDefinitionNames(), $fixers);
×
235
                }),
5✔
236
                new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should cache be used (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES),
5✔
237
                new InputOption('allow-unsupported-php-version', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should the command refuse to run on unsupported PHP version (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES),
5✔
238
                new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'),
5✔
239
                new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'),
5✔
240
                new InputOption('format', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('To output results in other formats (%s).', $formats), null, $formats),
5✔
241
                new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'),
5✔
242
                new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Type of progress indicator (%s).', $progessOutputTypes), null, $progessOutputTypes),
5✔
243
                new InputOption('sequential', '', InputOption::VALUE_NONE, 'Enforce sequential analysis.'),
5✔
244
            ]
5✔
245
        );
5✔
246
    }
247

248
    protected function execute(InputInterface $input, OutputInterface $output): int
249
    {
250
        $verbosity = $output->getVerbosity();
5✔
251

252
        $passedConfig = $input->getOption('config');
5✔
253
        $passedRules = $input->getOption('rules');
5✔
254

255
        if (null !== $passedConfig && null !== $passedRules) {
5✔
256
            throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.');
×
257
        }
258

259
        $resolver = new ConfigurationResolver(
5✔
260
            $this->defaultConfig,
5✔
261
            [
5✔
262
                'allow-risky' => $input->getOption('allow-risky'),
5✔
263
                'config' => $passedConfig,
5✔
264
                'dry-run' => $this->isDryRun($input),
5✔
265
                'rules' => $passedRules,
5✔
266
                'path' => $input->getArgument('path'),
5✔
267
                'path-mode' => $input->getOption('path-mode'),
5✔
268
                'using-cache' => $input->getOption('using-cache'),
5✔
269
                'allow-unsupported-php-version' => $input->getOption('allow-unsupported-php-version'),
5✔
270
                'cache-file' => $input->getOption('cache-file'),
5✔
271
                'format' => $input->getOption('format'),
5✔
272
                'diff' => $input->getOption('diff'),
5✔
273
                'stop-on-violation' => $input->getOption('stop-on-violation'),
5✔
274
                'verbosity' => $verbosity,
5✔
275
                'show-progress' => $input->getOption('show-progress'),
5✔
276
                'sequential' => $input->getOption('sequential'),
5✔
277
            ],
5✔
278
            getcwd(),
5✔
279
            $this->toolInfo
5✔
280
        );
5✔
281

282
        $reporter = $resolver->getReporter();
5✔
283

284
        $stdErr = $output instanceof ConsoleOutputInterface
5✔
285
            ? $output->getErrorOutput()
×
286
            : ('txt' === $reporter->getFormat() ? $output : null);
5✔
287

288
        if (null !== $stdErr) {
5✔
289
            $stdErr->writeln(Application::getAboutWithRuntime(true));
5✔
290

291
            if (version_compare(\PHP_VERSION, ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED.'.99', '>')) {
5✔
292
                $message = \sprintf(
×
293
                    'PHP CS Fixer currently supports PHP syntax only up to PHP %s, current PHP version: %s.',
×
294
                    ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED,
×
295
                    \PHP_VERSION
×
296
                );
×
297

298
                if (!$resolver->getUnsupportedPhpVersionAllowed()) {
×
299
                    $message .= ' Add Config::setUnsupportedPhpVersionAllowed(true) to allow executions on unsupported PHP versions. Such execution may be unstable and you may experience code modified in a wrong way.';
×
300
                    $stdErr->writeln(\sprintf(
×
301
                        $stdErr->isDecorated() ? '<bg=red;fg=white;>%s</>' : '%s',
×
302
                        $message
×
303
                    ));
×
304

305
                    return 1;
×
306
                }
307
                $message .= ' Execution may be unstable. You may experience code modified in a wrong way. Please report such cases at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. Remove Config::setUnsupportedPhpVersionAllowed(true) to allow executions only on supported PHP versions.';
×
308
                $stdErr->writeln(\sprintf(
×
309
                    $stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s',
×
310
                    $message
×
311
                ));
×
312
            }
313

314
            $isParallel = $resolver->getParallelConfig()->getMaxProcesses() > 1;
5✔
315

316
            $stdErr->writeln(\sprintf(
5✔
317
                'Running analysis on %d core%s.',
5✔
318
                $resolver->getParallelConfig()->getMaxProcesses(),
5✔
319
                $isParallel ? \sprintf(
5✔
320
                    's with %d file%s per process',
5✔
321
                    $resolver->getParallelConfig()->getFilesPerProcess(),
5✔
322
                    $resolver->getParallelConfig()->getFilesPerProcess() > 1 ? 's' : ''
5✔
323
                ) : ' sequentially'
5✔
324
            ));
5✔
325

326
            /** @TODO v4 remove warnings related to parallel runner */
327
            $availableMaxProcesses = ParallelConfigFactory::detect()->getMaxProcesses();
5✔
328
            if ($isParallel || $availableMaxProcesses > 1) {
5✔
329
                $usageDocs = 'https://cs.symfony.com/doc/usage.html';
5✔
330
                $stdErr->writeln(\sprintf(
5✔
331
                    $stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s',
5✔
332
                    $isParallel
5✔
333
                        ? 'Parallel runner is an experimental feature and may be unstable, use it at your own risk. Feedback highly appreciated!'
4✔
334
                        : \sprintf(
1✔
335
                            'You can enable parallel runner and speed up the analysis! Please see %s for more information.',
1✔
336
                            $stdErr->isDecorated()
1✔
337
                                ? \sprintf('<href=%s;bg=yellow;fg=red;bold>usage docs</>', OutputFormatter::escape($usageDocs))
×
338
                                : $usageDocs
5✔
339
                        )
1✔
340
                ));
5✔
341
            }
342

343
            $configFile = $resolver->getConfigFile();
5✔
344
            $stdErr->writeln(\sprintf('Loaded config <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"'));
5✔
345

346
            if ($resolver->getUsingCache()) {
5✔
347
                $cacheFile = $resolver->getCacheFile();
×
348

349
                if (is_file($cacheFile)) {
×
350
                    $stdErr->writeln(\sprintf('Using cache file "%s".', $cacheFile));
×
351
                }
352
            }
353
        }
354

355
        $finder = new \ArrayIterator(array_filter(
4✔
356
            iterator_to_array($resolver->getFinder()),
4✔
357
            static fn (\SplFileInfo $fileInfo) => false !== $fileInfo->getRealPath(),
4✔
358
        ));
4✔
359

360
        if (null !== $stdErr && $resolver->configFinderIsOverridden()) {
4✔
361
            $stdErr->writeln(
3✔
362
                \sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.')
3✔
363
            );
3✔
364
        }
365

366
        $progressType = $resolver->getProgressType();
4✔
367
        $progressOutput = $this->progressOutputFactory->create(
4✔
368
            $progressType,
4✔
369
            new OutputContext(
4✔
370
                $stdErr,
4✔
371
                (new Terminal())->getWidth(),
4✔
372
                \count($finder)
4✔
373
            )
4✔
374
        );
4✔
375

376
        $runner = new Runner(
4✔
377
            $finder,
4✔
378
            $resolver->getFixers(),
4✔
379
            $resolver->getDiffer(),
4✔
380
            ProgressOutputType::NONE !== $progressType ? $this->eventDispatcher : null,
4✔
381
            $this->errorsManager,
4✔
382
            $resolver->getLinter(),
4✔
383
            $resolver->isDryRun(),
4✔
384
            $resolver->getCacheManager(),
4✔
385
            $resolver->getDirectory(),
4✔
386
            $resolver->shouldStopOnViolation(),
4✔
387
            $resolver->getParallelConfig(),
4✔
388
            $input,
4✔
389
            $resolver->getConfigFile()
4✔
390
        );
4✔
391

392
        $this->eventDispatcher->addListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']);
3✔
393
        $this->stopwatch->start('fixFiles');
3✔
394
        $changed = $runner->fix();
3✔
395
        $this->stopwatch->stop('fixFiles');
3✔
396
        $this->eventDispatcher->removeListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']);
3✔
397

398
        $progressOutput->printLegend();
3✔
399

400
        $fixEvent = $this->stopwatch->getEvent('fixFiles');
3✔
401

402
        $reportSummary = new ReportSummary(
3✔
403
            $changed,
3✔
404
            \count($finder),
3✔
405
            $fixEvent->getDuration(),
3✔
406
            $fixEvent->getMemory(),
3✔
407
            OutputInterface::VERBOSITY_VERBOSE <= $verbosity,
3✔
408
            $resolver->isDryRun(),
3✔
409
            $output->isDecorated()
3✔
410
        );
3✔
411

412
        $output->isDecorated()
3✔
413
            ? $output->write($reporter->generate($reportSummary))
×
414
            : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW);
3✔
415

416
        $invalidErrors = $this->errorsManager->getInvalidErrors();
3✔
417
        $exceptionErrors = $this->errorsManager->getExceptionErrors();
3✔
418
        $lintErrors = $this->errorsManager->getLintErrors();
3✔
419

420
        if (null !== $stdErr) {
3✔
421
            $errorOutput = new ErrorOutput($stdErr);
3✔
422

423
            if (\count($invalidErrors) > 0) {
3✔
424
                $errorOutput->listErrors('linting before fixing', $invalidErrors);
×
425
            }
426

427
            if (\count($exceptionErrors) > 0) {
3✔
428
                $errorOutput->listErrors('fixing', $exceptionErrors);
×
429
            }
430

431
            if (\count($lintErrors) > 0) {
3✔
432
                $errorOutput->listErrors('linting after fixing', $lintErrors);
×
433
            }
434
        }
435

436
        $exitStatusCalculator = new FixCommandExitStatusCalculator();
3✔
437

438
        return $exitStatusCalculator->calculate(
3✔
439
            $resolver->isDryRun(),
3✔
440
            \count($changed) > 0,
3✔
441
            \count($invalidErrors) > 0,
3✔
442
            \count($exceptionErrors) > 0,
3✔
443
            \count($lintErrors) > 0
3✔
444
        );
3✔
445
    }
446

447
    protected function isDryRun(InputInterface $input): bool
448
    {
449
        return $input->getOption('dry-run'); // @phpstan-ignore symfonyConsole.optionNotFound (Because PHPStan doesn't recognise the method is overridden in the child class and this parameter is _not_ used in the child class.)
5✔
450
    }
451
}
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