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

keradus / PHP-CS-Fixer / 18051010410

26 Sep 2025 10:40PM UTC coverage: 94.308% (-0.02%) from 94.331%
18051010410

push

github

web-flow
chore: use accidentally missing `@auto:risky` (#9102)

28583 of 30308 relevant lines covered (94.31%)

45.24 hits per line

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

90.29
/src/Console/ConfigurationResolver.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;
16

17
use PhpCsFixer\Cache\CacheManagerInterface;
18
use PhpCsFixer\Cache\Directory;
19
use PhpCsFixer\Cache\DirectoryInterface;
20
use PhpCsFixer\Cache\FileCacheManager;
21
use PhpCsFixer\Cache\FileHandler;
22
use PhpCsFixer\Cache\NullCacheManager;
23
use PhpCsFixer\Cache\Signature;
24
use PhpCsFixer\ConfigInterface;
25
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
26
use PhpCsFixer\Console\Output\Progress\ProgressOutputType;
27
use PhpCsFixer\Console\Report\FixReport\ReporterFactory;
28
use PhpCsFixer\Console\Report\FixReport\ReporterInterface;
29
use PhpCsFixer\CustomRulesetsAwareConfigInterface;
30
use PhpCsFixer\Differ\DifferInterface;
31
use PhpCsFixer\Differ\NullDiffer;
32
use PhpCsFixer\Differ\UnifiedDiffer;
33
use PhpCsFixer\Finder;
34
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
35
use PhpCsFixer\Fixer\FixerInterface;
36
use PhpCsFixer\FixerFactory;
37
use PhpCsFixer\Future;
38
use PhpCsFixer\Linter\Linter;
39
use PhpCsFixer\Linter\LinterInterface;
40
use PhpCsFixer\ParallelAwareConfigInterface;
41
use PhpCsFixer\RuleSet\RuleSet;
42
use PhpCsFixer\RuleSet\RuleSetInterface;
43
use PhpCsFixer\RuleSet\RuleSets;
44
use PhpCsFixer\Runner\Parallel\ParallelConfig;
45
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
46
use PhpCsFixer\StdinFileInfo;
47
use PhpCsFixer\ToolInfoInterface;
48
use PhpCsFixer\UnsupportedPhpVersionAllowedConfigInterface;
49
use PhpCsFixer\Utils;
50
use PhpCsFixer\WhitespacesFixerConfig;
51
use PhpCsFixer\WordMatcher;
52
use Symfony\Component\Filesystem\Filesystem;
53
use Symfony\Component\Finder\Finder as SymfonyFinder;
54

55
/**
56
 * The resolver that resolves configuration to use by command line options and config.
57
 *
58
 * @internal
59
 *
60
 * @phpstan-type _Options array{
61
 *      allow-risky: null|string,
62
 *      cache-file: null|string,
63
 *      config: null|string,
64
 *      diff: null|string,
65
 *      dry-run: null|bool,
66
 *      format: null|string,
67
 *      path: list<string>,
68
 *      path-mode: value-of<self::PATH_MODE_VALUES>,
69
 *      rules: null|string,
70
 *      sequential: null|string,
71
 *      show-progress: null|string,
72
 *      stop-on-violation: null|bool,
73
 *      using-cache: null|string,
74
 *      allow-unsupported-php-version: null|bool,
75
 *      verbosity: null|string,
76
 *  }
77
 *
78
 * @author Fabien Potencier <fabien@symfony.com>
79
 * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
80
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
81
 *
82
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
83
 */
84
final class ConfigurationResolver
85
{
86
    public const PATH_MODE_OVERRIDE = 'override';
87
    public const PATH_MODE_INTERSECTION = 'intersection';
88
    public const PATH_MODE_VALUES = [
89
        self::PATH_MODE_OVERRIDE,
90
        self::PATH_MODE_INTERSECTION,
91
    ];
92

93
    public const BOOL_YES = 'yes';
94
    public const BOOL_NO = 'no';
95
    public const BOOL_VALUES = [
96
        self::BOOL_YES,
97
        self::BOOL_NO,
98
    ];
99

100
    /**
101
     * @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
102
     */
103
    private ?string $deprecatedNestedConfigDir = null;
104

105
    private ?bool $allowRisky = null;
106

107
    private ?ConfigInterface $config = null;
108

109
    private ?string $configFile = null;
110

111
    private string $cwd;
112

113
    private ConfigInterface $defaultConfig;
114

115
    private ?ReporterInterface $reporter = null;
116

117
    private ?bool $isStdIn = null;
118

119
    private ?bool $isDryRun = null;
120

121
    /**
122
     * @var null|list<FixerInterface>
123
     */
124
    private ?array $fixers = null;
125

126
    private ?bool $configFinderIsOverridden = null;
127

128
    private ToolInfoInterface $toolInfo;
129

130
    /**
131
     * @var _Options
132
     */
133
    private array $options = [
134
        'allow-risky' => null,
135
        'cache-file' => null,
136
        'config' => null,
137
        'diff' => null,
138
        'dry-run' => null,
139
        'format' => null,
140
        'path' => [],
141
        'path-mode' => self::PATH_MODE_OVERRIDE,
142
        'rules' => null,
143
        'sequential' => null,
144
        'show-progress' => null,
145
        'stop-on-violation' => null,
146
        'using-cache' => null,
147
        'allow-unsupported-php-version' => null,
148
        'verbosity' => null,
149
    ];
150

151
    private ?string $cacheFile = null;
152

153
    private ?CacheManagerInterface $cacheManager = null;
154

155
    private ?DifferInterface $differ = null;
156

157
    private ?Directory $directory = null;
158

159
    /**
160
     * @var null|iterable<\SplFileInfo>
161
     */
162
    private ?iterable $finder = null;
163

164
    private ?string $format = null;
165

166
    private ?Linter $linter = null;
167

168
    /**
169
     * @var null|list<string>
170
     */
171
    private ?array $path = null;
172

173
    /**
174
     * @var null|ProgressOutputType::*
175
     */
176
    private $progress;
177

178
    private ?RuleSet $ruleSet = null;
179

180
    private ?bool $usingCache = null;
181

182
    private ?bool $isUnsupportedPhpVersionAllowed = null;
183

184
    private ?FixerFactory $fixerFactory = null;
185

186
    /**
187
     * @param array<string, mixed> $options
188
     */
189
    public function __construct(
190
        ConfigInterface $config,
191
        array $options,
192
        string $cwd,
193
        ToolInfoInterface $toolInfo
194
    ) {
195
        $this->defaultConfig = $config;
127✔
196
        $this->cwd = $cwd;
127✔
197
        $this->toolInfo = $toolInfo;
127✔
198

199
        foreach ($options as $name => $value) {
127✔
200
            $this->setOption($name, $value);
102✔
201
        }
202
    }
203

204
    public function getCacheFile(): ?string
205
    {
206
        if (!$this->getUsingCache()) {
10✔
207
            return null;
4✔
208
        }
209

210
        if (null === $this->cacheFile) {
6✔
211
            if (null === $this->options['cache-file']) {
6✔
212
                $this->cacheFile = $this->getConfig()->getCacheFile();
4✔
213
            } else {
214
                $this->cacheFile = $this->options['cache-file'];
2✔
215
            }
216
        }
217

218
        return $this->cacheFile;
6✔
219
    }
220

221
    public function getCacheManager(): CacheManagerInterface
222
    {
223
        if (null === $this->cacheManager) {
1✔
224
            $cacheFile = $this->getCacheFile();
1✔
225

226
            if (null === $cacheFile) {
1✔
227
                $this->cacheManager = new NullCacheManager();
1✔
228
            } else {
229
                $this->cacheManager = new FileCacheManager(
×
230
                    new FileHandler($cacheFile),
×
231
                    new Signature(
×
232
                        \PHP_VERSION,
×
233
                        $this->toolInfo->getVersion(),
×
234
                        $this->getConfig()->getIndent(),
×
235
                        $this->getConfig()->getLineEnding(),
×
236
                        $this->getRules()
×
237
                    ),
×
238
                    $this->isDryRun(),
×
239
                    $this->getDirectory()
×
240
                );
×
241
            }
242
        }
243

244
        return $this->cacheManager;
1✔
245
    }
246

247
    public function getConfig(): ConfigInterface
248
    {
249
        if (null === $this->config) {
80✔
250
            foreach ($this->computeConfigFiles() as $configFile) {
80✔
251
                if (!file_exists($configFile)) {
79✔
252
                    continue;
64✔
253
                }
254

255
                $configFileBasename = basename($configFile);
20✔
256

257
                /** @TODO v4 drop handling (triggering error) for v2 config names */
258
                $deprecatedConfigs = [
20✔
259
                    '.php_cs' => '.php-cs-fixer.php',
20✔
260
                    '.php_cs.dist' => '.php-cs-fixer.dist.php',
20✔
261
                ];
20✔
262

263
                if (isset($deprecatedConfigs[$configFileBasename])) {
20✔
264
                    throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`.");
×
265
                }
266

267
                if (null !== $this->deprecatedNestedConfigDir && str_starts_with($configFile, $this->deprecatedNestedConfigDir)) {
20✔
268
                    // @TODO v4: when removing, remove also TODO with `MARKER-multi-paths-vs-only-cwd-config`
269
                    Future::triggerDeprecation(
7✔
270
                        new InvalidConfigurationException("Configuration file `{$configFile}` is picked as file inside passed `path` CLI argument. This will be ignored in the future and only config file in `cwd` will be picked. Please use `config` CLI option instead if you want to keep current behaviour."),
7✔
271
                    );
7✔
272
                }
273

274
                $this->config = self::separatedContextLessInclude($configFile);
20✔
275
                $this->configFile = $configFile;
19✔
276

277
                break;
19✔
278
            }
279

280
            if (null === $this->config) {
78✔
281
                $this->config = $this->defaultConfig;
59✔
282
            }
283

284
            if ($this->config instanceof CustomRulesetsAwareConfigInterface) {
78✔
285
                foreach ($this->config->getCustomRuleSets() as $ruleSet) {
78✔
286
                    RuleSets::registerCustomRuleSet($ruleSet);
1✔
287
                }
288
            }
289
        }
290

291
        return $this->config;
78✔
292
    }
293

294
    public function getParallelConfig(): ParallelConfig
295
    {
296
        $config = $this->getConfig();
3✔
297

298
        return true !== $this->options['sequential'] && $config instanceof ParallelAwareConfigInterface
3✔
299
            ? $config->getParallelConfig()
2✔
300
            : ParallelConfigFactory::sequential();
3✔
301
    }
302

303
    public function getConfigFile(): ?string
304
    {
305
        if (null === $this->configFile) {
19✔
306
            $this->getConfig();
14✔
307
        }
308

309
        return $this->configFile;
19✔
310
    }
311

312
    public function getDiffer(): DifferInterface
313
    {
314
        if (null === $this->differ) {
4✔
315
            $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer();
4✔
316
        }
317

318
        return $this->differ;
4✔
319
    }
320

321
    public function getDirectory(): DirectoryInterface
322
    {
323
        if (null === $this->directory) {
4✔
324
            $path = $this->getCacheFile();
4✔
325
            if (null === $path) {
4✔
326
                $absolutePath = $this->cwd;
1✔
327
            } else {
328
                $filesystem = new Filesystem();
3✔
329

330
                $absolutePath = $filesystem->isAbsolutePath($path)
3✔
331
                    ? $path
2✔
332
                    : $this->cwd.\DIRECTORY_SEPARATOR.$path;
1✔
333
                $absolutePath = \dirname($absolutePath);
3✔
334
            }
335

336
            $this->directory = new Directory($absolutePath);
4✔
337
        }
338

339
        return $this->directory;
4✔
340
    }
341

342
    /**
343
     * @return list<FixerInterface>
344
     */
345
    public function getFixers(): array
346
    {
347
        if (null === $this->fixers) {
5✔
348
            $this->fixers = $this->createFixerFactory()
5✔
349
                ->useRuleSet($this->getRuleSet())
5✔
350
                ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding()))
5✔
351
                ->getFixers()
5✔
352
            ;
5✔
353

354
            if (false === $this->getRiskyAllowed()) {
5✔
355
                $riskyFixers = array_map(
3✔
356
                    static fn (FixerInterface $fixer): string => $fixer->getName(),
3✔
357
                    array_values(array_filter(
3✔
358
                        $this->fixers,
3✔
359
                        static fn (FixerInterface $fixer): bool => $fixer->isRisky()
3✔
360
                    ))
3✔
361
                );
3✔
362

363
                if (\count($riskyFixers) > 0) {
3✔
364
                    throw new InvalidConfigurationException(\sprintf('The rules contain risky fixers (%s), but they are not allowed to run. Perhaps you forget to use --allow-risky=yes option?', Utils::naturalLanguageJoin($riskyFixers)));
×
365
                }
366
            }
367
        }
368

369
        return $this->fixers;
5✔
370
    }
371

372
    public function getLinter(): LinterInterface
373
    {
374
        if (null === $this->linter) {
1✔
375
            $this->linter = new Linter();
1✔
376
        }
377

378
        return $this->linter;
1✔
379
    }
380

381
    /**
382
     * Returns path.
383
     *
384
     * @return list<string>
385
     */
386
    public function getPath(): array
387
    {
388
        if (null === $this->path) {
94✔
389
            $filesystem = new Filesystem();
94✔
390
            $cwd = $this->cwd;
94✔
391

392
            if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) {
94✔
393
                $this->path = $this->options['path'];
×
394
            } else {
395
                $this->path = array_map(
94✔
396
                    static function (string $rawPath) use ($cwd, $filesystem): string {
94✔
397
                        $path = trim($rawPath);
46✔
398

399
                        if ('' === $path) {
46✔
400
                            throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\".");
6✔
401
                        }
402

403
                        $absolutePath = $filesystem->isAbsolutePath($path)
42✔
404
                            ? $path
37✔
405
                            : $cwd.\DIRECTORY_SEPARATOR.$path;
5✔
406

407
                        if (!file_exists($absolutePath)) {
42✔
408
                            throw new InvalidConfigurationException(\sprintf(
5✔
409
                                'The path "%s" is not readable.',
5✔
410
                                $path
5✔
411
                            ));
5✔
412
                        }
413

414
                        return $absolutePath;
37✔
415
                    },
94✔
416
                    $this->options['path']
94✔
417
                );
94✔
418
            }
419
        }
420

421
        return $this->path;
83✔
422
    }
423

424
    /**
425
     * @return ProgressOutputType::*
426
     *
427
     * @throws InvalidConfigurationException
428
     */
429
    public function getProgressType(): string
430
    {
431
        if (null === $this->progress) {
13✔
432
            if ('txt' === $this->resolveFormat()) {
13✔
433
                $progressType = $this->options['show-progress'];
11✔
434

435
                if (null === $progressType) {
11✔
436
                    $progressType = $this->getConfig()->getHideProgress()
4✔
437
                        ? ProgressOutputType::NONE
2✔
438
                        : ProgressOutputType::BAR;
2✔
439
                } elseif (!\in_array($progressType, ProgressOutputType::all(), true)) {
7✔
440
                    throw new InvalidConfigurationException(\sprintf(
1✔
441
                        'The progress type "%s" is not defined, supported are %s.',
1✔
442
                        $progressType,
1✔
443
                        Utils::naturalLanguageJoin(ProgressOutputType::all())
1✔
444
                    ));
1✔
445
                }
446

447
                $this->progress = $progressType;
10✔
448
            } else {
449
                $this->progress = ProgressOutputType::NONE;
2✔
450
            }
451
        }
452

453
        return $this->progress;
12✔
454
    }
455

456
    public function getReporter(): ReporterInterface
457
    {
458
        if (null === $this->reporter) {
8✔
459
            $reporterFactory = new ReporterFactory();
8✔
460
            $reporterFactory->registerBuiltInReporters();
8✔
461

462
            $format = $this->resolveFormat();
8✔
463

464
            try {
465
                $this->reporter = $reporterFactory->getReporter($format);
8✔
466
            } catch (\UnexpectedValueException $e) {
1✔
467
                $formats = $reporterFactory->getFormats();
1✔
468
                sort($formats);
1✔
469

470
                throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats)));
1✔
471
            }
472
        }
473

474
        return $this->reporter;
7✔
475
    }
476

477
    public function getRiskyAllowed(): bool
478
    {
479
        if (null === $this->allowRisky) {
18✔
480
            if (null === $this->options['allow-risky']) {
18✔
481
                $this->allowRisky = $this->getConfig()->getRiskyAllowed();
10✔
482
            } else {
483
                $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky');
8✔
484
            }
485
        }
486

487
        return $this->allowRisky;
17✔
488
    }
489

490
    /**
491
     * Returns rules.
492
     *
493
     * @return array<string, array<string, mixed>|bool>
494
     */
495
    public function getRules(): array
496
    {
497
        return $this->getRuleSet()->getRules();
11✔
498
    }
499

500
    public function getUsingCache(): bool
501
    {
502
        if (null === $this->usingCache) {
22✔
503
            if (null === $this->options['using-cache']) {
22✔
504
                $this->usingCache = $this->getConfig()->getUsingCache();
17✔
505
            } else {
506
                $this->usingCache = $this->resolveOptionBooleanValue('using-cache');
5✔
507
            }
508
        }
509

510
        $this->usingCache = $this->usingCache && $this->isCachingAllowedForRuntime();
22✔
511

512
        return $this->usingCache;
22✔
513
    }
514

515
    public function getUnsupportedPhpVersionAllowed(): bool
516
    {
517
        if (null === $this->isUnsupportedPhpVersionAllowed) {
×
518
            if (null === $this->options['allow-unsupported-php-version']) {
×
519
                $config = $this->getConfig();
×
520
                $this->isUnsupportedPhpVersionAllowed = $config instanceof UnsupportedPhpVersionAllowedConfigInterface
×
521
                    ? $config->getUnsupportedPhpVersionAllowed()
×
522
                    : false;
×
523
            } else {
524
                $this->isUnsupportedPhpVersionAllowed = $this->resolveOptionBooleanValue('allow-unsupported-php-version');
×
525
            }
526
        }
527

528
        return $this->isUnsupportedPhpVersionAllowed;
×
529
    }
530

531
    /**
532
     * @return iterable<\SplFileInfo>
533
     */
534
    public function getFinder(): iterable
535
    {
536
        if (null === $this->finder) {
31✔
537
            $this->finder = $this->resolveFinder();
31✔
538
        }
539

540
        return $this->finder;
26✔
541
    }
542

543
    /**
544
     * Returns dry-run flag.
545
     */
546
    public function isDryRun(): bool
547
    {
548
        if (null === $this->isDryRun) {
4✔
549
            if ($this->isStdIn()) {
4✔
550
                // Can't write to STDIN
551
                $this->isDryRun = true;
1✔
552
            } else {
553
                $this->isDryRun = $this->options['dry-run'];
3✔
554
            }
555
        }
556

557
        return $this->isDryRun;
4✔
558
    }
559

560
    public function shouldStopOnViolation(): bool
561
    {
562
        return $this->options['stop-on-violation'];
1✔
563
    }
564

565
    public function configFinderIsOverridden(): bool
566
    {
567
        if (null === $this->configFinderIsOverridden) {
7✔
568
            $this->resolveFinder();
7✔
569
        }
570

571
        return $this->configFinderIsOverridden;
7✔
572
    }
573

574
    /**
575
     * Compute file candidates for config file.
576
     *
577
     * @TODO v4: don't offer configs from passed `path` CLI argument
578
     *
579
     * @return list<string>
580
     */
581
    private function computeConfigFiles(): array
582
    {
583
        $configFile = $this->options['config'];
80✔
584

585
        if (null !== $configFile) {
80✔
586
            if (false === file_exists($configFile) || false === is_readable($configFile)) {
11✔
587
                throw new InvalidConfigurationException(\sprintf('Cannot read config file "%s".', $configFile));
×
588
            }
589

590
            return [$configFile];
11✔
591
        }
592

593
        $path = $this->getPath();
69✔
594

595
        if ($this->isStdIn() || 0 === \count($path)) {
69✔
596
            $configDir = $this->cwd;
46✔
597
        } elseif (1 < \count($path)) {
23✔
598
            // @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
599
            throw new InvalidConfigurationException('For multiple paths config parameter is required.');
1✔
600
        } elseif (!is_file($path[0])) {
22✔
601
            $configDir = $path[0];
12✔
602
        } else {
603
            $dirName = pathinfo($path[0], \PATHINFO_DIRNAME);
10✔
604
            $configDir = is_dir($dirName) ? $dirName : $path[0];
10✔
605
        }
606

607
        $candidates = [
68✔
608
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
68✔
609
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
68✔
610

611
            // @TODO v4 drop handling (triggering error) for v2 config names
612
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later
68✔
613
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later
68✔
614
        ];
68✔
615

616
        if ($configDir !== $this->cwd) {
68✔
617
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php';
22✔
618
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php';
22✔
619

620
            // @TODO v4 drop handling (triggering error) for v2 config names
621
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs'; // old v2 config, present here only to throw nice error message later
22✔
622
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist'; // old v2 config, present here only to throw nice error message later
22✔
623

624
            $this->deprecatedNestedConfigDir = $configDir;
22✔
625
        }
626

627
        return $candidates;
68✔
628
    }
629

630
    private function createFixerFactory(): FixerFactory
631
    {
632
        if (null === $this->fixerFactory) {
15✔
633
            $fixerFactory = new FixerFactory();
15✔
634
            $fixerFactory->registerBuiltInFixers();
15✔
635
            $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers());
15✔
636

637
            $this->fixerFactory = $fixerFactory;
15✔
638
        }
639

640
        return $this->fixerFactory;
15✔
641
    }
642

643
    private function resolveFormat(): string
644
    {
645
        if (null === $this->format) {
19✔
646
            $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat();
19✔
647
            $parts = explode(',', $formatCandidate);
19✔
648

649
            if (\count($parts) > 2) {
19✔
650
                throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate));
×
651
            }
652

653
            $this->format = $parts[0];
19✔
654

655
            if ('@auto' === $this->format) {
19✔
656
                $this->format = $parts[1] ?? 'txt';
3✔
657

658
                if (filter_var(getenv('GITLAB_CI'), \FILTER_VALIDATE_BOOL)) {
3✔
659
                    $this->format = 'gitlab';
1✔
660
                }
661
            }
662
        }
663

664
        return $this->format;
19✔
665
    }
666

667
    private function getRuleSet(): RuleSetInterface
668
    {
669
        if (null === $this->ruleSet) {
16✔
670
            $rules = $this->parseRules();
16✔
671
            $this->validateRules($rules);
15✔
672

673
            $this->ruleSet = new RuleSet($rules);
10✔
674
        }
675

676
        return $this->ruleSet;
10✔
677
    }
678

679
    private function isStdIn(): bool
680
    {
681
        if (null === $this->isStdIn) {
87✔
682
            $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0];
87✔
683
        }
684

685
        return $this->isStdIn;
87✔
686
    }
687

688
    /**
689
     * @template T
690
     *
691
     * @param iterable<T> $iterable
692
     *
693
     * @return \Traversable<T>
694
     */
695
    private function iterableToTraversable(iterable $iterable): \Traversable
696
    {
697
        return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable;
25✔
698
    }
699

700
    /**
701
     * @return array<string, mixed>
702
     */
703
    private function parseRules(): array
704
    {
705
        if (null === $this->options['rules']) {
16✔
706
            return $this->getConfig()->getRules();
7✔
707
        }
708

709
        $rules = trim($this->options['rules']);
9✔
710
        if ('' === $rules) {
9✔
711
            throw new InvalidConfigurationException('Empty rules value is not allowed.');
1✔
712
        }
713

714
        if (str_starts_with($rules, '{')) {
8✔
715
            try {
716
                return json_decode($rules, true, 512, \JSON_THROW_ON_ERROR);
×
717
            } catch (\JsonException $e) {
×
718
                throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', $e->getMessage()));
×
719
            }
720
        }
721

722
        $rules = [];
8✔
723

724
        foreach (explode(',', $this->options['rules']) as $rule) {
8✔
725
            $rule = trim($rule);
8✔
726

727
            if ('' === $rule) {
8✔
728
                throw new InvalidConfigurationException('Empty rule name is not allowed.');
×
729
            }
730

731
            if (str_starts_with($rule, '-')) {
8✔
732
                $rules[substr($rule, 1)] = false;
2✔
733
            } else {
734
                $rules[$rule] = true;
8✔
735
            }
736
        }
737

738
        return $rules;
8✔
739
    }
740

741
    /**
742
     * @param array<string, mixed> $rules
743
     *
744
     * @throws InvalidConfigurationException
745
     */
746
    private function validateRules(array $rules): void
747
    {
748
        /**
749
         * Create a ruleset that contains all configured rules, even when they originally have been disabled.
750
         *
751
         * @see RuleSet::resolveSet()
752
         */
753
        $ruleSet = [];
15✔
754

755
        foreach ($rules as $key => $value) {
15✔
756
            if (\is_int($key)) {
15✔
757
                throw new InvalidConfigurationException(\sprintf('Missing value for "%s" rule/set.', $value));
×
758
            }
759

760
            $ruleSet[$key] = true;
15✔
761
        }
762

763
        $ruleSet = new RuleSet($ruleSet);
15✔
764

765
        $configuredFixers = array_keys($ruleSet->getRules());
15✔
766

767
        $fixers = $this->createFixerFactory()->getFixers();
15✔
768

769
        $availableFixers = array_map(static fn (FixerInterface $fixer): string => $fixer->getName(), $fixers);
15✔
770

771
        $unknownFixers = array_diff($configuredFixers, $availableFixers);
15✔
772

773
        if (\count($unknownFixers) > 0) {
15✔
774
            $renamedRules = [
5✔
775
                'blank_line_before_return' => [
5✔
776
                    'new_name' => 'blank_line_before_statement',
5✔
777
                    'config' => ['statements' => ['return']],
5✔
778
                ],
5✔
779
                'final_static_access' => [
5✔
780
                    'new_name' => 'self_static_accessor',
5✔
781
                ],
5✔
782
                'hash_to_slash_comment' => [
5✔
783
                    'new_name' => 'single_line_comment_style',
5✔
784
                    'config' => ['comment_types' => ['hash']],
5✔
785
                ],
5✔
786
                'lowercase_constants' => [
5✔
787
                    'new_name' => 'constant_case',
5✔
788
                    'config' => ['case' => 'lower'],
5✔
789
                ],
5✔
790
                'no_extra_consecutive_blank_lines' => [
5✔
791
                    'new_name' => 'no_extra_blank_lines',
5✔
792
                ],
5✔
793
                'no_multiline_whitespace_before_semicolons' => [
5✔
794
                    'new_name' => 'multiline_whitespace_before_semicolons',
5✔
795
                ],
5✔
796
                'no_short_echo_tag' => [
5✔
797
                    'new_name' => 'echo_tag_syntax',
5✔
798
                    'config' => ['format' => 'long'],
5✔
799
                ],
5✔
800
                'php_unit_ordered_covers' => [
5✔
801
                    'new_name' => 'phpdoc_order_by_value',
5✔
802
                    'config' => ['annotations' => ['covers']],
5✔
803
                ],
5✔
804
                'phpdoc_inline_tag' => [
5✔
805
                    'new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type',
5✔
806
                ],
5✔
807
                'pre_increment' => [
5✔
808
                    'new_name' => 'increment_style',
5✔
809
                    'config' => ['style' => 'pre'],
5✔
810
                ],
5✔
811
                'psr0' => [
5✔
812
                    'new_name' => 'psr_autoloading',
5✔
813
                    'config' => ['dir' => 'x'],
5✔
814
                ],
5✔
815
                'psr4' => [
5✔
816
                    'new_name' => 'psr_autoloading',
5✔
817
                ],
5✔
818
                'silenced_deprecation_error' => [
5✔
819
                    'new_name' => 'error_suppression',
5✔
820
                ],
5✔
821
                'trailing_comma_in_multiline_array' => [
5✔
822
                    'new_name' => 'trailing_comma_in_multiline',
5✔
823
                    'config' => ['elements' => ['arrays']],
5✔
824
                ],
5✔
825
            ];
5✔
826

827
            $message = 'The rules contain unknown fixers: ';
5✔
828
            $hasOldRule = false;
5✔
829

830
            foreach ($unknownFixers as $unknownFixer) {
5✔
831
                if (isset($renamedRules[$unknownFixer])) { // Check if present as old renamed rule
5✔
832
                    $hasOldRule = true;
4✔
833
                    $message .= \sprintf(
4✔
834
                        '"%s" is renamed (did you mean "%s"?%s), ',
4✔
835
                        $unknownFixer,
4✔
836
                        $renamedRules[$unknownFixer]['new_name'],
4✔
837
                        isset($renamedRules[$unknownFixer]['config']) ? ' (note: use configuration "'.Utils::toString($renamedRules[$unknownFixer]['config']).'")' : ''
4✔
838
                    );
4✔
839
                } else { // Go to normal matcher if it is not a renamed rule
840
                    $matcher = new WordMatcher($availableFixers);
2✔
841
                    $alternative = $matcher->match($unknownFixer);
2✔
842
                    $message .= \sprintf(
2✔
843
                        '"%s"%s, ',
2✔
844
                        $unknownFixer,
2✔
845
                        null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)'
2✔
846
                    );
2✔
847
                }
848
            }
849

850
            $message = substr($message, 0, -2).'.';
5✔
851

852
            if ($hasOldRule) {
5✔
853
                $message .= "\nFor more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless.";
4✔
854
            }
855

856
            throw new InvalidConfigurationException($message);
5✔
857
        }
858

859
        foreach ($fixers as $fixer) {
10✔
860
            $fixerName = $fixer->getName();
10✔
861
            if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) {
10✔
862
                $successors = $fixer->getSuccessorsNames();
3✔
863
                $messageEnd = [] === $successors
3✔
864
                    ? \sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1)
×
865
                    : \sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors)));
3✔
866

867
                Future::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}"));
3✔
868
            }
869
        }
870
    }
871

872
    /**
873
     * Apply path on config instance.
874
     *
875
     * @return iterable<\SplFileInfo>
876
     */
877
    private function resolveFinder(): iterable
878
    {
879
        $this->configFinderIsOverridden = false;
31✔
880

881
        if ($this->isStdIn()) {
31✔
882
            return new \ArrayIterator([new StdinFileInfo()]);
×
883
        }
884

885
        if (!\in_array(
31✔
886
            $this->options['path-mode'],
31✔
887
            self::PATH_MODE_VALUES,
31✔
888
            true
31✔
889
        )) {
31✔
890
            throw new InvalidConfigurationException(\sprintf(
×
891
                'The path-mode "%s" is not defined, supported are %s.',
×
892
                $this->options['path-mode'],
×
893
                Utils::naturalLanguageJoin(self::PATH_MODE_VALUES)
×
894
            ));
×
895
        }
896

897
        $isIntersectionPathMode = self::PATH_MODE_INTERSECTION === $this->options['path-mode'];
31✔
898

899
        $paths = array_map(
31✔
900
            static fn (string $path): string => realpath($path), // @phpstan-ignore return.type
31✔
901
            $this->getPath()
31✔
902
        );
31✔
903

904
        if (0 === \count($paths)) {
26✔
905
            if ($isIntersectionPathMode) {
5✔
906
                return new \ArrayIterator([]);
1✔
907
            }
908

909
            return $this->iterableToTraversable($this->getConfig()->getFinder());
4✔
910
        }
911

912
        $pathsByType = [
21✔
913
            'file' => [],
21✔
914
            'dir' => [],
21✔
915
        ];
21✔
916

917
        foreach ($paths as $path) {
21✔
918
            if (is_file($path)) {
21✔
919
                $pathsByType['file'][] = $path;
11✔
920
            } else {
921
                $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR;
12✔
922
            }
923
        }
924

925
        $nestedFinder = null;
21✔
926
        $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder());
21✔
927

928
        try {
929
            $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder;
21✔
930
        } catch (\Exception $e) {
4✔
931
        }
932

933
        if ($isIntersectionPathMode) {
21✔
934
            if (null === $nestedFinder) {
11✔
935
                throw new InvalidConfigurationException(
×
936
                    'Cannot create intersection with not-fully defined Finder in configuration file.'
×
937
                );
×
938
            }
939

940
            return new \CallbackFilterIterator(
11✔
941
                new \IteratorIterator($nestedFinder),
11✔
942
                static function (\SplFileInfo $current) use ($pathsByType): bool {
11✔
943
                    $currentRealPath = $current->getRealPath();
10✔
944

945
                    if (\in_array($currentRealPath, $pathsByType['file'], true)) {
10✔
946
                        return true;
3✔
947
                    }
948

949
                    foreach ($pathsByType['dir'] as $path) {
10✔
950
                        if (str_starts_with($currentRealPath, $path)) {
5✔
951
                            return true;
4✔
952
                        }
953
                    }
954

955
                    return false;
10✔
956
                }
11✔
957
            );
11✔
958
        }
959

960
        if (null !== $this->getConfigFile() && null !== $nestedFinder) {
10✔
961
            $this->configFinderIsOverridden = true;
3✔
962
        }
963

964
        if ($currentFinder instanceof SymfonyFinder && null === $nestedFinder) {
10✔
965
            // finder from configuration Symfony finder and it is not fully defined, we may fulfill it
966
            return $currentFinder->in($pathsByType['dir'])->append($pathsByType['file']);
4✔
967
        }
968

969
        return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']);
6✔
970
    }
971

972
    /**
973
     * Set option that will be resolved.
974
     *
975
     * @param mixed $value
976
     */
977
    private function setOption(string $name, $value): void
978
    {
979
        if (!\array_key_exists($name, $this->options)) {
102✔
980
            throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name));
1✔
981
        }
982

983
        $this->options[$name] = $value;
101✔
984
    }
985

986
    /**
987
     * @param key-of<_Options> $optionName
988
     */
989
    private function resolveOptionBooleanValue(string $optionName): bool
990
    {
991
        $value = $this->options[$optionName];
12✔
992

993
        if (self::BOOL_YES === $value) {
12✔
994
            return true;
6✔
995
        }
996

997
        if (self::BOOL_NO === $value) {
7✔
998
            return false;
6✔
999
        }
1000

1001
        throw new InvalidConfigurationException(\sprintf('Expected "%s" or "%s" for option "%s", got "%s".', self::BOOL_YES, self::BOOL_NO, $optionName, \is_object($value) ? \get_class($value) : (\is_scalar($value) ? $value : \gettype($value))));
1✔
1002
    }
1003

1004
    private static function separatedContextLessInclude(string $path): ConfigInterface
1005
    {
1006
        $config = include $path;
20✔
1007

1008
        // verify that the config has an instance of Config
1009
        if (!$config instanceof ConfigInterface) {
20✔
1010
            throw new InvalidConfigurationException(\sprintf('The config file: "%s" does not return a "%s" instance. Got: "%s".', $path, ConfigInterface::class, get_debug_type($config)));
1✔
1011
        }
1012

1013
        return $config;
19✔
1014
    }
1015

1016
    private function isCachingAllowedForRuntime(): bool
1017
    {
1018
        return $this->toolInfo->isInstalledAsPhar()
14✔
1019
            || $this->toolInfo->isInstalledByComposer()
14✔
1020
            || $this->toolInfo->isRunInsideDocker()
14✔
1021
            || filter_var(getenv('PHP_CS_FIXER_ENFORCE_CACHE'), \FILTER_VALIDATE_BOOL);
14✔
1022
    }
1023
}
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