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

keradus / PHP-CS-Fixer / 16018263876

02 Jul 2025 06:58AM UTC coverage: 94.846% (-0.002%) from 94.848%
16018263876

push

github

keradus
debug2

28193 of 29725 relevant lines covered (94.85%)

45.34 hits per line

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

92.57
/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\ReportSummary;
27
use PhpCsFixer\Error\ErrorsManager;
28
use PhpCsFixer\Runner\Event\FileProcessed;
29
use PhpCsFixer\Runner\Runner;
30
use PhpCsFixer\ToolInfoInterface;
31
use Symfony\Component\Console\Attribute\AsCommand;
32
use Symfony\Component\Console\Command\Command;
33
use Symfony\Component\Console\Formatter\OutputFormatter;
34
use Symfony\Component\Console\Input\InputArgument;
35
use Symfony\Component\Console\Input\InputInterface;
36
use Symfony\Component\Console\Input\InputOption;
37
use Symfony\Component\Console\Output\ConsoleOutputInterface;
38
use Symfony\Component\Console\Output\OutputInterface;
39
use Symfony\Component\Console\Terminal;
40
use Symfony\Component\EventDispatcher\EventDispatcher;
41
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
42
use Symfony\Component\Stopwatch\Stopwatch;
43

44
/**
45
 * @author Fabien Potencier <fabien@symfony.com>
46
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
47
 *
48
 * @final
49
 *
50
 * @internal
51
 */
52
#[AsCommand(name: 'fix', description: 'Fixes a directory or a file.')]
53
/* final */ class FixCommand extends Command
54
{
55
    protected static $defaultName = 'fix';
56

57
    protected static $defaultDescription = 'Fixes a directory or a file.';
58

59
    private EventDispatcherInterface $eventDispatcher;
60

61
    private ErrorsManager $errorsManager;
62

63
    private Stopwatch $stopwatch;
64

65
    private ConfigInterface $defaultConfig;
66

67
    private ToolInfoInterface $toolInfo;
68

69
    private ProgressOutputFactory $progressOutputFactory;
70

71
    public function __construct(ToolInfoInterface $toolInfo)
72
    {
73
        parent::__construct();
7✔
74

75
        $this->eventDispatcher = new EventDispatcher();
7✔
76
        $this->errorsManager = new ErrorsManager();
7✔
77
        $this->stopwatch = new Stopwatch();
7✔
78
        $this->defaultConfig = new Config();
7✔
79
        $this->toolInfo = $toolInfo;
7✔
80
        $this->progressOutputFactory = new ProgressOutputFactory();
7✔
81
    }
82

83
    /**
84
     * {@inheritdoc}
85
     *
86
     * Override here to only generate the help copy when used.
87
     */
88
    public function getHelp(): string
89
    {
90
        return <<<'EOF'
×
91
            The <info>%command.name%</info> command tries to %command.name% as much coding standards
92
            problems as possible on a given file or files in a given directory and its subdirectories:
93

94
                <info>$ php %command.full_name% /path/to/dir</info>
95
                <info>$ php %command.full_name% /path/to/file</info>
96

97
            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
98
            command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use <comment>--path-mode=intersection</comment>
99
            to merge paths from the config file and from the argument:
100

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

103
            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`.
104

105
            * `@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)
106
              * `gitlab` for GitLab
107
            * `@auto,{format}` takes `@auto` under CI, and {format} otherwise
108

109
            NOTE: the output for the following formats are generated in accordance with schemas
110

111
            * `checkstyle` follows the common `"checkstyle" XML schema </doc/schemas/fix/checkstyle.xsd>`_
112
            * `gitlab` follows the `codeclimate JSON schema </doc/schemas/fix/codeclimate.json>`_
113
            * `json` follows the `own JSON schema </doc/schemas/fix/schema.json>`_
114
            * `junit` follows the `JUnit XML schema from Jenkins </doc/schemas/fix/junit-10.xsd>`_
115
            * `xml` follows the `own XML schema </doc/schemas/fix/xml.xsd>`_
116

117
            The <comment>--quiet</comment> Do not output any message.
118

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

121
            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
122

123
            * `-v`: verbose
124
            * `-vv`: very verbose
125
            * `-vvv`: debug
126

127
            The <comment>--rules</comment> option limits the rules to apply to the
128
            project:
129

130
            EOF. /* @TODO: 4.0 - change to @PER */ <<<'EOF'
×
131

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

134
            By default the PSR-12 rules are used.
135

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

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

141
            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,
142
            using <comment>-name_of_fixer</comment>:
143

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

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

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

150
            Complete configuration for rules can be supplied using a `json` formatted string.
151

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

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

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

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

160
            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.
161
            A rule is considered risky if it could change code behaviour. By default no risky rules are run.
162

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

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

167
            * <comment>none</comment>: disables progress output;
168
            * <comment>dots</comment>: multiline progress output with number of files and percentage on each line.
169
            * <comment>bar</comment>: single line progress output with number of files and calculated percentage.
170

171
            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>.
172

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

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

178
            The command can also read from standard input, in which case it won't
179
            automatically fix anything:
180

181
                <info>$ cat foo.php | php %command.full_name% --diff -</info>
182

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

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

188
            Exit code
189
            ---------
190

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

193
            *  0 - OK.
194
            *  1 - General error (or PHP minimal requirement not matched).
195
            *  4 - Some files have invalid syntax (only in dry-run mode).
196
            *  8 - Some files need fixing (only in dry-run mode).
197
            * 16 - Configuration error of the application.
198
            * 32 - Configuration error of a Fixer.
199
            * 64 - Exception raised within the application.
200

201
            EOF;
×
202
    }
203

204
    protected function configure(): void
205
    {
206
        $this->setDefinition(
7✔
207
            [
7✔
208
                new InputArgument('path', InputArgument::IS_ARRAY, 'The path(s) that rules will be run against (each path can be a file or directory).'),
7✔
209
                new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, 'Specify path mode (can be `override` or `intersection`).', ConfigurationResolver::PATH_MODE_OVERRIDE),
7✔
210
                new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, 'Are risky fixers allowed (can be `yes` or `no`).'),
7✔
211
                new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'),
7✔
212
                new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'),
7✔
213
                new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.'),
7✔
214
                new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, 'Should cache be used (can be `yes` or `no`).'),
7✔
215
                new InputOption('allow-unsupported-php-version', '', InputOption::VALUE_REQUIRED, 'Should the command refuse to run on unsupported PHP version (can be `yes` or `no`).'),
7✔
216
                new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'),
7✔
217
                new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'),
7✔
218
                new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.'),
7✔
219
                new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'),
7✔
220
                new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, 'Type of progress indicator (none, dots).'),
7✔
221
                new InputOption('sequential', '', InputOption::VALUE_NONE, 'Enforce sequential analysis.'),
7✔
222
            ]
7✔
223
        );
7✔
224
    }
225

226
    protected function execute(InputInterface $input, OutputInterface $output): int
227
    {
228
        $verbosity = $output->getVerbosity();
7✔
229

230
        $passedConfig = $input->getOption('config');
7✔
231
        $passedRules = $input->getOption('rules');
7✔
232

233
        if (null !== $passedConfig && null !== $passedRules) {
7✔
234
            throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.');
×
235
        }
236

237
        $resolver = new ConfigurationResolver(
7✔
238
            $this->defaultConfig,
7✔
239
            [
7✔
240
                'allow-risky' => $input->getOption('allow-risky'),
7✔
241
                'config' => $passedConfig,
7✔
242
                'dry-run' => $this->isDryRun($input),
7✔
243
                'rules' => $passedRules,
7✔
244
                'path' => $input->getArgument('path'),
7✔
245
                'path-mode' => $input->getOption('path-mode'),
7✔
246
                'using-cache' => $input->getOption('using-cache'),
7✔
247
                'allow-unsupported-php-version' => $input->getOption('allow-unsupported-php-version'),
7✔
248
                'cache-file' => $input->getOption('cache-file'),
7✔
249
                'format' => $input->getOption('format'),
7✔
250
                'diff' => $input->getOption('diff'),
7✔
251
                'stop-on-violation' => $input->getOption('stop-on-violation'),
7✔
252
                'verbosity' => $verbosity,
7✔
253
                'show-progress' => $input->getOption('show-progress'),
7✔
254
                'sequential' => $input->getOption('sequential'),
7✔
255
            ],
7✔
256
            getcwd(),
7✔
257
            $this->toolInfo
7✔
258
        );
7✔
259

260
        $reporter = $resolver->getReporter();
7✔
261

262
        $stdErr = $output instanceof ConsoleOutputInterface
7✔
263
            ? $output->getErrorOutput()
×
264
            : ('txt' === $reporter->getFormat() ? $output : null);
7✔
265

266
        if (null !== $stdErr) {
7✔
267
            $stdErr->writeln(Application::getAboutWithRuntime(true));
7✔
268

269
            if (version_compare(PHP_VERSION, ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED.'.99', '>')) {
7✔
270
                $message = \sprintf(
7✔
271
                    'PHP CS Fixer currently supports PHP syntax only up to PHP %s, current PHP version: %s.',
7✔
272
                    ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED,
7✔
273
                    PHP_VERSION
7✔
274
                );
7✔
275

276
                if (!$resolver->getUnsupportedPhpVersionAllowed()) {
7✔
277
                    $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.';
1✔
278
                    $stdErr->writeln(\sprintf(
1✔
279
                        $stdErr->isDecorated() ? '<bg=red;fg=white;>%s</>' : '%s',
1✔
280
                        $message
1✔
281
                    ));
1✔
282

283
                    return 1;
1✔
284
                }
285
                $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.';
6✔
286
                $stdErr->writeln(\sprintf(
6✔
287
                    $stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s',
6✔
288
                    $message
6✔
289
                ));
6✔
290
            }
291

292
            $isParallel = $resolver->getParallelConfig()->getMaxProcesses() > 1;
6✔
293

294
            $stdErr->writeln(\sprintf(
6✔
295
                'Running analysis on %d core%s.',
6✔
296
                $resolver->getParallelConfig()->getMaxProcesses(),
6✔
297
                $isParallel ? \sprintf(
6✔
298
                    's with %d file%s per process',
6✔
299
                    $resolver->getParallelConfig()->getFilesPerProcess(),
6✔
300
                    $resolver->getParallelConfig()->getFilesPerProcess() > 1 ? 's' : ''
6✔
301
                ) : ' sequentially'
6✔
302
            ));
6✔
303

304
            /** @TODO v4 remove warnings related to parallel runner */
305
            $usageDocs = 'https://cs.symfony.com/doc/usage.html';
6✔
306
            $stdErr->writeln(\sprintf(
6✔
307
                $stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s',
6✔
308
                $isParallel
6✔
309
                    ? 'Parallel runner is an experimental feature and may be unstable, use it at your own risk. Feedback highly appreciated!'
5✔
310
                    : \sprintf(
1✔
311
                        'You can enable parallel runner and speed up the analysis! Please see %s for more information.',
1✔
312
                        $stdErr->isDecorated()
1✔
313
                            ? \sprintf('<href=%s;bg=yellow;fg=red;bold>usage docs</>', OutputFormatter::escape($usageDocs))
×
314
                            : $usageDocs
6✔
315
                    )
1✔
316
            ));
6✔
317

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

321
            if ($resolver->getUsingCache()) {
6✔
322
                $cacheFile = $resolver->getCacheFile();
×
323

324
                if (is_file($cacheFile)) {
×
325
                    $stdErr->writeln(\sprintf('Using cache file "%s".', $cacheFile));
×
326
                }
327
            }
328
        }
329

330
        $finder = new \ArrayIterator(iterator_to_array($resolver->getFinder()));
5✔
331

332
        if (null !== $stdErr && $resolver->configFinderIsOverridden()) {
5✔
333
            $stdErr->writeln(
4✔
334
                \sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.')
4✔
335
            );
4✔
336
        }
337

338
        $progressType = $resolver->getProgressType();
5✔
339
        $progressOutput = $this->progressOutputFactory->create(
5✔
340
            $progressType,
5✔
341
            new OutputContext(
5✔
342
                $stdErr,
5✔
343
                (new Terminal())->getWidth(),
5✔
344
                \count($finder)
5✔
345
            )
5✔
346
        );
5✔
347

348
        $runner = new Runner(
5✔
349
            $finder,
5✔
350
            $resolver->getFixers(),
5✔
351
            $resolver->getDiffer(),
5✔
352
            ProgressOutputType::NONE !== $progressType ? $this->eventDispatcher : null,
5✔
353
            $this->errorsManager,
5✔
354
            $resolver->getLinter(),
5✔
355
            $resolver->isDryRun(),
5✔
356
            $resolver->getCacheManager(),
5✔
357
            $resolver->getDirectory(),
5✔
358
            $resolver->shouldStopOnViolation(),
5✔
359
            $resolver->getParallelConfig(),
5✔
360
            $input,
5✔
361
            $resolver->getConfigFile()
5✔
362
        );
5✔
363

364
        $this->eventDispatcher->addListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']);
4✔
365
        $this->stopwatch->start('fixFiles');
4✔
366
        $changed = $runner->fix();
4✔
367
        $this->stopwatch->stop('fixFiles');
4✔
368
        $this->eventDispatcher->removeListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']);
4✔
369

370
        $progressOutput->printLegend();
4✔
371

372
        $fixEvent = $this->stopwatch->getEvent('fixFiles');
4✔
373

374
        $reportSummary = new ReportSummary(
4✔
375
            $changed,
4✔
376
            \count($finder),
4✔
377
            $fixEvent->getDuration(),
4✔
378
            $fixEvent->getMemory(),
4✔
379
            OutputInterface::VERBOSITY_VERBOSE <= $verbosity,
4✔
380
            $resolver->isDryRun(),
4✔
381
            $output->isDecorated()
4✔
382
        );
4✔
383

384
        $output->isDecorated()
4✔
385
            ? $output->write($reporter->generate($reportSummary))
×
386
            : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW);
4✔
387

388
        $invalidErrors = $this->errorsManager->getInvalidErrors();
4✔
389
        $exceptionErrors = $this->errorsManager->getExceptionErrors();
4✔
390
        $lintErrors = $this->errorsManager->getLintErrors();
4✔
391

392
        if (null !== $stdErr) {
4✔
393
            $errorOutput = new ErrorOutput($stdErr);
4✔
394

395
            if (\count($invalidErrors) > 0) {
4✔
396
                $errorOutput->listErrors('linting before fixing', $invalidErrors);
×
397
            }
398

399
            if (\count($exceptionErrors) > 0) {
4✔
400
                $errorOutput->listErrors('fixing', $exceptionErrors);
×
401
            }
402

403
            if (\count($lintErrors) > 0) {
4✔
404
                $errorOutput->listErrors('linting after fixing', $lintErrors);
×
405
            }
406
        }
407

408
        $exitStatusCalculator = new FixCommandExitStatusCalculator();
4✔
409

410
        return $exitStatusCalculator->calculate(
4✔
411
            $resolver->isDryRun(),
4✔
412
            \count($changed) > 0,
4✔
413
            \count($invalidErrors) > 0,
4✔
414
            \count($exceptionErrors) > 0,
4✔
415
            \count($lintErrors) > 0
4✔
416
        );
4✔
417
    }
418

419
    protected function isDryRun(InputInterface $input): bool
420
    {
421
        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.)
7✔
422
    }
423
}
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