FixCommand::getHelp()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 102

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 102
c 1
b 0
f 0
dl 0
loc 3
rs 8
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 *     Dariusz Rumiński <[email protected]>
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\ConfigurationResolver;
21
use PhpCsFixer\Console\Output\ErrorOutput;
22
use PhpCsFixer\Console\Output\NullOutput;
23
use PhpCsFixer\Console\Output\ProcessOutput;
24
use PhpCsFixer\Console\Report\FixReport\ReportSummary;
25
use PhpCsFixer\Error\ErrorsManager;
26
use PhpCsFixer\Runner\Runner;
27
use PhpCsFixer\ToolInfoInterface;
28
use Symfony\Component\Console\Command\Command;
29
use Symfony\Component\Console\Input\InputArgument;
30
use Symfony\Component\Console\Input\InputInterface;
31
use Symfony\Component\Console\Input\InputOption;
32
use Symfony\Component\Console\Output\ConsoleOutputInterface;
33
use Symfony\Component\Console\Output\OutputInterface;
34
use Symfony\Component\Console\Terminal;
35
use Symfony\Component\EventDispatcher\EventDispatcher;
36
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
37
use Symfony\Component\Stopwatch\Stopwatch;
38
39
/**
40
 * @author Fabien Potencier <[email protected]>
41
 * @author Dariusz Rumiński <[email protected]>
42
 *
43
 * @internal
44
 */
45
final class FixCommand extends Command
46
{
47
    /**
48
     * @var string
49
     */
50
    protected static $defaultName = 'fix';
51
52
    /**
53
     * @var EventDispatcherInterface
54
     */
55
    private $eventDispatcher;
56
57
    /**
58
     * @var ErrorsManager
59
     */
60
    private $errorsManager;
61
62
    /**
63
     * @var Stopwatch
64
     */
65
    private $stopwatch;
66
67
    /**
68
     * @var ConfigInterface
69
     */
70
    private $defaultConfig;
71
72
    /**
73
     * @var ToolInfoInterface
74
     */
75
    private $toolInfo;
76
77
    public function __construct(ToolInfoInterface $toolInfo)
78
    {
79
        parent::__construct();
80
81
        $this->defaultConfig = new Config();
82
        $this->errorsManager = new ErrorsManager();
83
        $this->eventDispatcher = new EventDispatcher();
84
        $this->stopwatch = new Stopwatch();
85
        $this->toolInfo = $toolInfo;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     *
91
     * Override here to only generate the help copy when used.
92
     */
93
    public function getHelp(): string
94
    {
95
        return <<<'EOF'
96
The <info>%command.name%</info> command tries to fix as much coding standards
97
problems as possible on a given file or files in a given directory and its subdirectories:
98
99
    <info>$ php %command.full_name% /path/to/dir</info>
100
    <info>$ php %command.full_name% /path/to/file</info>
101
102
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
103
command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use <comment>--path-mode=intersection</comment>
104
to merge paths from the config file and from the argument:
105
106
    <info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>
107
108
The <comment>--format</comment> option for the output format. Supported formats are `txt` (default one), `json`, `xml`, `checkstyle`, `junit` and `gitlab`.
109
110
NOTE: the output for the following formats are generated in accordance with schemas
111
112
* `checkstyle` follows the common `"checkstyle" XML schema </doc/schemas/fix/checkstyle.xsd>`_
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
    <info>$ php %command.full_name% /path/to/project --rules=@PSR12</info>
131
132
By default the PSR-12 rules are used.
133
134
The <comment>--rules</comment> option lets you choose the exact rules to
135
apply (the rule names must be separated by a comma):
136
137
    <info>$ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type</info>
138
139
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,
140
using <comment>-name_of_fixer</comment>:
141
142
    <info>$ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type</info>
143
144
When using combinations of exact and exclude rules, applying exact rules along with above excluded results:
145
146
    <info>$ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison</info>
147
148
Complete configuration for rules can be supplied using a `json` formatted string.
149
150
    <info>$ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}'</info>
151
152
The <comment>--dry-run</comment> flag will run the fixer without making changes to your files.
153
154
The <comment>--diff</comment> flag can be used to let the fixer output all the changes it makes.
155
156
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.
157
A rule is considered risky if it could change code behaviour. By default no risky rules are run.
158
159
The <comment>--stop-on-violation</comment> flag stops the execution upon first file that needs to be fixed.
160
161
The <comment>--show-progress</comment> option allows you to choose the way process progress is rendered:
162
163
* <comment>none</comment>: disables progress output;
164
* <comment>dots</comment>: multiline progress output with number of files and percentage on each line.
165
166
If the option is not provided, it defaults to <comment>dots</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>.
167
168
    <info>$ php %command.full_name% --verbose --show-progress=dots</info>
169
170
By using <command>--using-cache</command> option with `yes` or `no` you can set if the caching
171
mechanism should be used.
172
173
The command can also read from standard input, in which case it won't
174
automatically fix anything:
175
176
    <info>$ cat foo.php | php %command.full_name% --diff -</info>
177
178
Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that
179
would be default in next MAJOR release and to forbid using deprecated configuration:
180
181
    <info>$ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff</info>
182
183
Exit code
184
---------
185
186
Exit code of the fix command is built using following bit flags:
187
188
*  0 - OK.
189
*  1 - General error (or PHP minimal requirement not matched).
190
*  4 - Some files have invalid syntax (only in dry-run mode).
191
*  8 - Some files need fixing (only in dry-run mode).
192
* 16 - Configuration error of the application.
193
* 32 - Configuration error of a Fixer.
194
* 64 - Exception raised within the application.
195
196
EOF
197
            ;
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    protected function configure(): void
204
    {
205
        $this
206
            ->setDefinition(
207
                [
208
                    new InputArgument('path', InputArgument::IS_ARRAY, 'The path.'),
209
                    new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, 'Specify path mode (can be override or intersection).', ConfigurationResolver::PATH_MODE_OVERRIDE),
210
                    new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, 'Are risky fixers allowed (can be yes or no).'),
211
                    new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'),
212
                    new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'),
213
                    new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'The rules.'),
214
                    new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, 'Does cache should be used (can be yes or no).'),
215
                    new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'),
216
                    new InputOption('diff', '', InputOption::VALUE_NONE, 'Also produce diff for each file.'),
217
                    new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.'),
218
                    new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'),
219
                    new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, 'Type of progress indicator (none, dots).'),
220
                ]
221
            )
222
            ->setDescription('Fixes a directory or a file.')
223
        ;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    protected function execute(InputInterface $input, OutputInterface $output): int
230
    {
231
        $verbosity = $output->getVerbosity();
232
233
        $passedConfig = $input->getOption('config');
234
        $passedRules = $input->getOption('rules');
235
236
        if (null !== $passedConfig && null !== $passedRules) {
237
            throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.');
238
        }
239
240
        $resolver = new ConfigurationResolver(
241
            $this->defaultConfig,
242
            [
243
                'allow-risky' => $input->getOption('allow-risky'),
244
                'config' => $passedConfig,
245
                'dry-run' => $input->getOption('dry-run'),
246
                'rules' => $passedRules,
247
                'path' => $input->getArgument('path'),
248
                'path-mode' => $input->getOption('path-mode'),
249
                'using-cache' => $input->getOption('using-cache'),
250
                'cache-file' => $input->getOption('cache-file'),
251
                'format' => $input->getOption('format'),
252
                'diff' => $input->getOption('diff'),
253
                'stop-on-violation' => $input->getOption('stop-on-violation'),
254
                'verbosity' => $verbosity,
255
                'show-progress' => $input->getOption('show-progress'),
256
            ],
257
            getcwd(),
258
            $this->toolInfo
259
        );
260
261
        $reporter = $resolver->getReporter();
262
263
        $stdErr = $output instanceof ConsoleOutputInterface
264
            ? $output->getErrorOutput()
265
            : ('txt' === $reporter->getFormat() ? $output : null)
266
        ;
267
268
        if (null !== $stdErr) {
269
            if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
270
                $stdErr->writeln($this->getApplication()->getLongVersion());
271
                $stdErr->writeln(sprintf('Runtime: <info>PHP %s</info>', PHP_VERSION));
272
            }
273
274
            $configFile = $resolver->getConfigFile();
275
            $stdErr->writeln(sprintf('Loaded config <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"'));
276
277
            if ($resolver->getUsingCache()) {
278
                $cacheFile = $resolver->getCacheFile();
279
280
                if (is_file($cacheFile)) {
0 ignored issues
show
Bug introduced by
It seems like $cacheFile can also be of type null; however, parameter $filename of is_file() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

280
                if (is_file(/** @scrutinizer ignore-type */ $cacheFile)) {
Loading history...
281
                    $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile));
282
                }
283
            }
284
        }
285
286
        $progressType = $resolver->getProgress();
287
        $finder = $resolver->getFinder();
288
289
        if (null !== $stdErr && $resolver->configFinderIsOverridden()) {
290
            $stdErr->writeln(
291
                sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.')
292
            );
293
        }
294
295
        if ('none' === $progressType || null === $stdErr) {
296
            $progressOutput = new NullOutput();
297
        } else {
298
            $finder = new \ArrayIterator(iterator_to_array($finder));
299
            $progressOutput = new ProcessOutput(
300
                $stdErr,
301
                $this->eventDispatcher,
302
                (new Terminal())->getWidth(),
303
                \count($finder)
304
            );
305
        }
306
307
        $runner = new Runner(
308
            $finder,
309
            $resolver->getFixers(),
310
            $resolver->getDiffer(),
311
            'none' !== $progressType ? $this->eventDispatcher : null,
312
            $this->errorsManager,
313
            $resolver->getLinter(),
314
            $resolver->isDryRun(),
315
            $resolver->getCacheManager(),
316
            $resolver->getDirectory(),
317
            $resolver->shouldStopOnViolation()
318
        );
319
320
        $this->stopwatch->start('fixFiles');
321
        $changed = $runner->fix();
322
        $this->stopwatch->stop('fixFiles');
323
324
        $progressOutput->printLegend();
325
326
        $fixEvent = $this->stopwatch->getEvent('fixFiles');
327
328
        $reportSummary = new ReportSummary(
329
            $changed,
330
            $fixEvent->getDuration(),
0 ignored issues
show
Bug introduced by
It seems like $fixEvent->getDuration() can also be of type double; however, parameter $time of PhpCsFixer\Console\Repor...tSummary::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

330
            /** @scrutinizer ignore-type */ $fixEvent->getDuration(),
Loading history...
331
            $fixEvent->getMemory(),
332
            OutputInterface::VERBOSITY_VERBOSE <= $verbosity,
333
            $resolver->isDryRun(),
334
            $output->isDecorated()
335
        );
336
337
        $output->isDecorated()
338
            ? $output->write($reporter->generate($reportSummary))
339
            : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW)
340
        ;
341
342
        $invalidErrors = $this->errorsManager->getInvalidErrors();
343
        $exceptionErrors = $this->errorsManager->getExceptionErrors();
344
        $lintErrors = $this->errorsManager->getLintErrors();
345
346
        if (null !== $stdErr) {
347
            $errorOutput = new ErrorOutput($stdErr);
348
349
            if (\count($invalidErrors) > 0) {
350
                $errorOutput->listErrors('linting before fixing', $invalidErrors);
351
            }
352
353
            if (\count($exceptionErrors) > 0) {
354
                $errorOutput->listErrors('fixing', $exceptionErrors);
355
            }
356
357
            if (\count($lintErrors) > 0) {
358
                $errorOutput->listErrors('linting after fixing', $lintErrors);
359
            }
360
        }
361
362
        $exitStatusCalculator = new FixCommandExitStatusCalculator();
363
364
        return $exitStatusCalculator->calculate(
365
            $resolver->isDryRun(),
366
            \count($changed) > 0,
367
            \count($invalidErrors) > 0,
368
            \count($exceptionErrors) > 0,
369
            \count($lintErrors) > 0
370
        );
371
    }
372
}
373