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

keradus / PHP-CS-Fixer / 22042339290

15 Feb 2026 08:14PM UTC coverage: 92.957% (-0.2%) from 93.171%
22042339290

push

github

keradus
test: check PHP env in CI jobs

29302 of 31522 relevant lines covered (92.96%)

44.04 hits per line

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

88.1
/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\Config\NullRuleCustomisationPolicy;
25
use PhpCsFixer\Config\RuleCustomisationPolicyAwareConfigInterface;
26
use PhpCsFixer\Config\RuleCustomisationPolicyInterface;
27
use PhpCsFixer\ConfigInterface;
28
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
29
use PhpCsFixer\Console\Output\Progress\ProgressOutputType;
30
use PhpCsFixer\Console\Report\FixReport\ReporterFactory;
31
use PhpCsFixer\Console\Report\FixReport\ReporterInterface;
32
use PhpCsFixer\CustomRulesetsAwareConfigInterface;
33
use PhpCsFixer\Differ\DifferInterface;
34
use PhpCsFixer\Differ\NullDiffer;
35
use PhpCsFixer\Differ\UnifiedDiffer;
36
use PhpCsFixer\Finder;
37
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
38
use PhpCsFixer\Fixer\FixerInterface;
39
use PhpCsFixer\FixerFactory;
40
use PhpCsFixer\Future;
41
use PhpCsFixer\Linter\Linter;
42
use PhpCsFixer\Linter\LinterInterface;
43
use PhpCsFixer\ParallelAwareConfigInterface;
44
use PhpCsFixer\RuleSet\RuleSet;
45
use PhpCsFixer\RuleSet\RuleSetInterface;
46
use PhpCsFixer\RuleSet\RuleSets;
47
use PhpCsFixer\Runner\Parallel\ParallelConfig;
48
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
49
use PhpCsFixer\StdinFileInfo;
50
use PhpCsFixer\ToolInfoInterface;
51
use PhpCsFixer\UnsupportedPhpVersionAllowedConfigInterface;
52
use PhpCsFixer\Utils;
53
use PhpCsFixer\WhitespacesFixerConfig;
54
use PhpCsFixer\WordMatcher;
55
use Symfony\Component\Filesystem\Filesystem;
56
use Symfony\Component\Finder\Finder as SymfonyFinder;
57

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

91
    public const PATH_MODE_OVERRIDE = 'override';
92
    public const PATH_MODE_INTERSECTION = 'intersection';
93
    public const PATH_MODE_VALUES = [
94
        self::PATH_MODE_OVERRIDE,
95
        self::PATH_MODE_INTERSECTION,
96
    ];
97

98
    public const BOOL_YES = 'yes';
99
    public const BOOL_NO = 'no';
100
    public const BOOL_VALUES = [
101
        self::BOOL_YES,
102
        self::BOOL_NO,
103
    ];
104

105
    /**
106
     * @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
107
     */
108
    private ?string $deprecatedNestedConfigDir = null;
109

110
    private ?bool $allowRisky = null;
111

112
    private ?ConfigInterface $config = null;
113

114
    private ?string $configFile = null;
115

116
    private string $cwd;
117

118
    private ConfigInterface $defaultConfig;
119

120
    private ?ReporterInterface $reporter = null;
121

122
    private ?bool $isStdIn = null;
123

124
    private ?bool $isDryRun = null;
125

126
    /**
127
     * @var null|list<FixerInterface>
128
     */
129
    private ?array $fixers = null;
130

131
    private ?bool $configFinderIsOverridden = null;
132

133
    private ?bool $configRulesAreOverridden = null;
134

135
    private ToolInfoInterface $toolInfo;
136

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

158
    private ?string $cacheFile = null;
159

160
    private ?CacheManagerInterface $cacheManager = null;
161

162
    private ?DifferInterface $differ = null;
163

164
    private ?Directory $directory = null;
165

166
    /**
167
     * @var null|iterable<\SplFileInfo>
168
     */
169
    private ?iterable $finder = null;
170

171
    private ?string $format = null;
172

173
    private ?Linter $linter = null;
174

175
    /**
176
     * @var null|list<string>
177
     */
178
    private ?array $path = null;
179

180
    /**
181
     * @var null|ProgressOutputType::*
182
     */
183
    private $progress;
184

185
    private ?RuleSet $ruleSet = null;
186

187
    private ?bool $usingCache = null;
188

189
    private ?bool $isUnsupportedPhpVersionAllowed = null;
190

191
    private ?RuleCustomisationPolicyInterface $ruleCustomisationPolicy = null;
192

193
    private ?FixerFactory $fixerFactory = null;
194

195
    /**
196
     * @param array<string, mixed> $options
197
     */
198
    public function __construct(
199
        ConfigInterface $config,
200
        array $options,
201
        string $cwd,
202
        ToolInfoInterface $toolInfo
203
    ) {
204
        $this->defaultConfig = $config;
128✔
205
        $this->cwd = $cwd;
128✔
206
        $this->toolInfo = $toolInfo;
128✔
207

208
        foreach ($options as $name => $value) {
128✔
209
            $this->setOption($name, $value);
103✔
210
        }
211
    }
212

213
    public function getCacheFile(): ?string
214
    {
215
        if (!$this->getUsingCache()) {
6✔
216
            return null;
3✔
217
        }
218

219
        if (null === $this->cacheFile) {
3✔
220
            if (null === $this->options['cache-file']) {
3✔
221
                $this->cacheFile = $this->getConfig()->getCacheFile();
1✔
222
            } else {
223
                $this->cacheFile = $this->options['cache-file'];
2✔
224
            }
225
        }
226

227
        return $this->cacheFile;
3✔
228
    }
229

230
    public function getCacheManager(): CacheManagerInterface
231
    {
232
        if (null === $this->cacheManager) {
1✔
233
            $cacheFile = $this->getCacheFile();
1✔
234

235
            if (null === $cacheFile) {
1✔
236
                $this->cacheManager = new NullCacheManager();
1✔
237
            } else {
238
                $this->cacheManager = new FileCacheManager(
×
239
                    new FileHandler($cacheFile),
×
240
                    new Signature(
×
241
                        \PHP_VERSION,
×
242
                        $this->toolInfo->getVersion(),
×
243
                        $this->getConfig()->getIndent(),
×
244
                        $this->getConfig()->getLineEnding(),
×
245
                        $this->getRules(),
×
246
                        $this->getRuleCustomisationPolicy()->getPolicyVersionForCache(),
×
247
                    ),
×
248
                    $this->isDryRun(),
×
249
                    $this->getDirectory(),
×
250
                );
×
251
            }
252
        }
253

254
        return $this->cacheManager;
1✔
255
    }
256

257
    public function getConfig(): ConfigInterface
258
    {
259
        if (null === $this->config) {
76✔
260
            foreach ($this->computeConfigFiles() as $configFile) {
76✔
261
                if (!file_exists($configFile)) {
73✔
262
                    continue;
58✔
263
                }
264

265
                $configFileBasename = basename($configFile);
20✔
266

267
                /** @TODO v4 drop handling (triggering error) for v2 config names */
268
                $deprecatedConfigs = [
20✔
269
                    '.php_cs' => '.php-cs-fixer.php',
20✔
270
                    '.php_cs.dist' => '.php-cs-fixer.dist.php',
20✔
271
                ];
20✔
272

273
                if (isset($deprecatedConfigs[$configFileBasename])) {
20✔
274
                    throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`.");
×
275
                }
276

277
                if (null !== $this->deprecatedNestedConfigDir && str_starts_with($configFile, $this->deprecatedNestedConfigDir)) {
20✔
278
                    // @TODO v4: when removing, remove also TODO with `MARKER-multi-paths-vs-only-cwd-config`
279
                    Future::triggerDeprecation(
7✔
280
                        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✔
281
                    );
7✔
282
                }
283

284
                $this->config = self::separatedContextLessInclude($configFile);
20✔
285
                $this->configFile = $configFile;
19✔
286

287
                break;
19✔
288
            }
289

290
            if (null === $this->config) {
74✔
291
                $this->config = $this->defaultConfig;
55✔
292
            }
293

294
            if ($this->config instanceof CustomRulesetsAwareConfigInterface) {
74✔
295
                foreach ($this->config->getCustomRuleSets() as $ruleSet) {
74✔
296
                    RuleSets::registerCustomRuleSet($ruleSet);
1✔
297
                }
298
            }
299
        }
300

301
        return $this->config;
74✔
302
    }
303

304
    public function getParallelConfig(): ParallelConfig
305
    {
306
        $config = $this->getConfig();
3✔
307

308
        return true !== $this->options['sequential'] && $config instanceof ParallelAwareConfigInterface
3✔
309
            ? $config->getParallelConfig()
2✔
310
            : ParallelConfigFactory::sequential();
3✔
311
    }
312

313
    public function getConfigFile(): ?string
314
    {
315
        if (null === $this->configFile) {
19✔
316
            $this->getConfig();
14✔
317
        }
318

319
        return $this->configFile;
19✔
320
    }
321

322
    public function getDiffer(): DifferInterface
323
    {
324
        if (null === $this->differ) {
4✔
325
            $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer();
4✔
326
        }
327

328
        return $this->differ;
4✔
329
    }
330

331
    public function getDirectory(): DirectoryInterface
332
    {
333
        if (null === $this->directory) {
5✔
334
            $cwd = realpath($this->cwd);
5✔
335

336
            $this->directory = new Directory(false !== $cwd ? $cwd : $this->cwd);
5✔
337
        }
338

339
        return $this->directory;
5✔
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) {
90✔
389
            $filesystem = new Filesystem();
90✔
390
            $cwd = $this->cwd;
90✔
391

392
            if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) {
90✔
393
                $this->path = $this->options['path'];
×
394
            } else {
395
                $this->path = array_map(
90✔
396
                    static function (string $rawPath) use ($cwd, $filesystem): string {
90✔
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
                    },
90✔
416
                    $this->options['path'],
90✔
417
                );
90✔
418
            }
419
        }
420

421
        return $this->path;
79✔
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) {
18✔
503
            if (null === $this->options['using-cache']) {
18✔
504
                $this->usingCache = $this->getConfig()->getUsingCache();
13✔
505
            } else {
506
                $this->usingCache = $this->resolveOptionBooleanValue('using-cache');
5✔
507
            }
508
        }
509

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

512
        return $this->usingCache;
18✔
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
    public function getRuleCustomisationPolicy(): RuleCustomisationPolicyInterface
532
    {
533
        if (null === $this->ruleCustomisationPolicy) {
×
534
            $config = $this->getConfig();
×
535
            if ($config instanceof RuleCustomisationPolicyAwareConfigInterface) {
×
536
                $this->ruleCustomisationPolicy = $config->getRuleCustomisationPolicy();
×
537
            }
538
            $this->ruleCustomisationPolicy ??= new NullRuleCustomisationPolicy();
×
539
        }
540

541
        return $this->ruleCustomisationPolicy;
×
542
    }
543

544
    /**
545
     * @return iterable<\SplFileInfo>
546
     */
547
    public function getFinder(): iterable
548
    {
549
        if (null === $this->finder) {
31✔
550
            $this->finder = $this->resolveFinder();
31✔
551
        }
552

553
        return $this->finder;
26✔
554
    }
555

556
    /**
557
     * Returns dry-run flag.
558
     */
559
    public function isDryRun(): bool
560
    {
561
        if (null === $this->isDryRun) {
4✔
562
            if ($this->isStdIn()) {
4✔
563
                // Can't write to STDIN
564
                $this->isDryRun = true;
1✔
565
            } else {
566
                $this->isDryRun = $this->options['dry-run'];
3✔
567
            }
568
        }
569

570
        return $this->isDryRun;
4✔
571
    }
572

573
    public function shouldStopOnViolation(): bool
574
    {
575
        return $this->options['stop-on-violation'];
1✔
576
    }
577

578
    public function configFinderIsOverridden(): bool
579
    {
580
        if (null === $this->configFinderIsOverridden) {
7✔
581
            $this->resolveFinder();
7✔
582
        }
583

584
        return $this->configFinderIsOverridden;
7✔
585
    }
586

587
    public function configRulesAreOverridden(): bool
588
    {
589
        if (null === $this->configRulesAreOverridden) {
×
590
            $this->parseRules();
×
591
        }
592

593
        return $this->configRulesAreOverridden;
×
594
    }
595

596
    /**
597
     * Compute file candidates for config file.
598
     *
599
     * @TODO v4: don't offer configs from passed `path` CLI argument
600
     *
601
     * @return list<string>
602
     */
603
    private function computeConfigFiles(): array
604
    {
605
        $configFile = $this->options['config'];
76✔
606

607
        if (self::IGNORE_CONFIG_FILE === $configFile) {
76✔
608
            return [];
2✔
609
        }
610

611
        if (null !== $configFile) {
74✔
612
            if (false === file_exists($configFile) || false === is_readable($configFile)) {
11✔
613
                throw new InvalidConfigurationException(\sprintf('Cannot read config file "%s".', $configFile));
×
614
            }
615

616
            return [$configFile];
11✔
617
        }
618

619
        $path = $this->getPath();
63✔
620

621
        if ($this->isStdIn() || 0 === \count($path)) {
63✔
622
            $configDir = $this->cwd;
41✔
623
        } elseif (1 < \count($path)) {
22✔
624
            // @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
625
            throw new InvalidConfigurationException('For multiple paths config parameter is required.');
1✔
626
        } elseif (!is_file($path[0])) {
21✔
627
            $configDir = $path[0];
11✔
628
        } else {
629
            $dirName = pathinfo($path[0], \PATHINFO_DIRNAME);
10✔
630
            $configDir = is_dir($dirName) ? $dirName : $path[0];
10✔
631
        }
632

633
        $candidates = [
62✔
634
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
62✔
635
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
62✔
636

637
            // @TODO v4 drop handling (triggering error) for v2 config names
638
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later
62✔
639
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later
62✔
640
        ];
62✔
641

642
        if ($configDir !== $this->cwd) {
62✔
643
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php';
21✔
644
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php';
21✔
645

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

650
            $this->deprecatedNestedConfigDir = $configDir;
21✔
651
        }
652

653
        return $candidates;
62✔
654
    }
655

656
    private function createFixerFactory(): FixerFactory
657
    {
658
        if (null === $this->fixerFactory) {
15✔
659
            $fixerFactory = new FixerFactory();
15✔
660
            $fixerFactory->registerBuiltInFixers();
15✔
661
            $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers());
15✔
662

663
            $this->fixerFactory = $fixerFactory;
15✔
664
        }
665

666
        return $this->fixerFactory;
15✔
667
    }
668

669
    private function resolveFormat(): string
670
    {
671
        if (null === $this->format) {
19✔
672
            $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat();
19✔
673
            $parts = explode(',', $formatCandidate);
19✔
674

675
            if (\count($parts) > 2) {
19✔
676
                throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate));
×
677
            }
678

679
            $this->format = $parts[0];
19✔
680

681
            if ('@auto' === $this->format) {
19✔
682
                $this->format = $parts[1] ?? 'txt';
3✔
683

684
                if (filter_var(getenv('GITLAB_CI'), \FILTER_VALIDATE_BOOL)) {
3✔
685
                    $this->format = 'gitlab';
1✔
686
                }
687
            }
688
        }
689

690
        return $this->format;
19✔
691
    }
692

693
    private function getRuleSet(): RuleSetInterface
694
    {
695
        if (null === $this->ruleSet) {
16✔
696
            $rules = $this->parseRules();
16✔
697
            $this->validateRules($rules);
15✔
698

699
            $this->ruleSet = new RuleSet($rules);
10✔
700
        }
701

702
        return $this->ruleSet;
10✔
703
    }
704

705
    private function isStdIn(): bool
706
    {
707
        if (null === $this->isStdIn) {
83✔
708
            $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0];
83✔
709
        }
710

711
        return $this->isStdIn;
83✔
712
    }
713

714
    /**
715
     * @template T
716
     *
717
     * @param iterable<T> $iterable
718
     *
719
     * @return \Traversable<T>
720
     */
721
    private function iterableToTraversable(iterable $iterable): \Traversable
722
    {
723
        return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable;
25✔
724
    }
725

726
    /**
727
     * @return array<string, mixed>
728
     */
729
    private function parseRules(): array
730
    {
731
        $this->configRulesAreOverridden = null !== $this->options['rules'];
16✔
732

733
        if (null === $this->options['rules']) {
16✔
734
            $this->configRulesAreOverridden = false;
7✔
735

736
            return $this->getConfig()->getRules();
7✔
737
        }
738

739
        $rules = trim($this->options['rules']);
9✔
740
        if ('' === $rules) {
9✔
741
            throw new InvalidConfigurationException('Empty rules value is not allowed.');
1✔
742
        }
743

744
        if (str_starts_with($rules, '{')) {
8✔
745
            try {
746
                return json_decode($rules, true, 512, \JSON_THROW_ON_ERROR);
×
747
            } catch (\JsonException $e) {
×
748
                throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', $e->getMessage()));
×
749
            }
750
        }
751

752
        $rules = [];
8✔
753

754
        foreach (explode(',', $this->options['rules']) as $rule) {
8✔
755
            $rule = trim($rule);
8✔
756

757
            if ('' === $rule) {
8✔
758
                throw new InvalidConfigurationException('Empty rule name is not allowed.');
×
759
            }
760

761
            if (str_starts_with($rule, '-')) {
8✔
762
                $rules[substr($rule, 1)] = false;
2✔
763
            } else {
764
                $rules[$rule] = true;
8✔
765
            }
766
        }
767

768
        $this->configRulesAreOverridden = true;
8✔
769

770
        return $rules;
8✔
771
    }
772

773
    /**
774
     * @param array<string, mixed> $rules
775
     *
776
     * @throws InvalidConfigurationException
777
     */
778
    private function validateRules(array $rules): void
779
    {
780
        /**
781
         * Create a ruleset that contains all configured rules, even when they originally have been disabled.
782
         *
783
         * @see RuleSet::resolveSet()
784
         */
785
        $ruleSet = [];
15✔
786

787
        foreach ($rules as $key => $value) {
15✔
788
            if (\is_int($key)) {
15✔
789
                throw new InvalidConfigurationException(\sprintf('Missing value for "%s" rule/set.', $value));
×
790
            }
791

792
            $ruleSet[$key] = true;
15✔
793
        }
794

795
        $ruleSet = new RuleSet($ruleSet);
15✔
796

797
        $configuredFixers = array_keys($ruleSet->getRules());
15✔
798

799
        $fixers = $this->createFixerFactory()->getFixers();
15✔
800

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

803
        $unknownFixers = array_diff($configuredFixers, $availableFixers);
15✔
804

805
        if (\count($unknownFixers) > 0) {
15✔
806
            /**
807
             * @TODO v4: `renamedRulesFromV2ToV3` no longer needed
808
             * @TODO v3.99: decide how to handle v3 to v4 (where legacy rules are already removed)
809
             */
810
            $renamedRulesFromV2ToV3 = [
5✔
811
                'blank_line_before_return' => [
5✔
812
                    'new_name' => 'blank_line_before_statement',
5✔
813
                    'config' => ['statements' => ['return']],
5✔
814
                ],
5✔
815
                'final_static_access' => [
5✔
816
                    'new_name' => 'self_static_accessor',
5✔
817
                ],
5✔
818
                'hash_to_slash_comment' => [
5✔
819
                    'new_name' => 'single_line_comment_style',
5✔
820
                    'config' => ['comment_types' => ['hash']],
5✔
821
                ],
5✔
822
                'lowercase_constants' => [
5✔
823
                    'new_name' => 'constant_case',
5✔
824
                    'config' => ['case' => 'lower'],
5✔
825
                ],
5✔
826
                'no_extra_consecutive_blank_lines' => [
5✔
827
                    'new_name' => 'no_extra_blank_lines',
5✔
828
                ],
5✔
829
                'no_multiline_whitespace_before_semicolons' => [
5✔
830
                    'new_name' => 'multiline_whitespace_before_semicolons',
5✔
831
                ],
5✔
832
                'no_short_echo_tag' => [
5✔
833
                    'new_name' => 'echo_tag_syntax',
5✔
834
                    'config' => ['format' => 'long'],
5✔
835
                ],
5✔
836
                'php_unit_ordered_covers' => [
5✔
837
                    'new_name' => 'phpdoc_order_by_value',
5✔
838
                    'config' => ['annotations' => ['covers']],
5✔
839
                ],
5✔
840
                'phpdoc_inline_tag' => [
5✔
841
                    'new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type',
5✔
842
                ],
5✔
843
                'pre_increment' => [
5✔
844
                    'new_name' => 'increment_style',
5✔
845
                    'config' => ['style' => 'pre'],
5✔
846
                ],
5✔
847
                'psr0' => [
5✔
848
                    'new_name' => 'psr_autoloading',
5✔
849
                    'config' => ['dir' => 'x'],
5✔
850
                ],
5✔
851
                'psr4' => [
5✔
852
                    'new_name' => 'psr_autoloading',
5✔
853
                ],
5✔
854
                'silenced_deprecation_error' => [
5✔
855
                    'new_name' => 'error_suppression',
5✔
856
                ],
5✔
857
                'trailing_comma_in_multiline_array' => [
5✔
858
                    'new_name' => 'trailing_comma_in_multiline',
5✔
859
                    'config' => ['elements' => ['arrays']],
5✔
860
                ],
5✔
861
            ];
5✔
862

863
            $message = 'The rules contain unknown fixers: ';
5✔
864
            $hasOldRule = false;
5✔
865

866
            foreach ($unknownFixers as $unknownFixer) {
5✔
867
                if (isset($renamedRulesFromV2ToV3[$unknownFixer])) { // Check if present as old renamed rule
5✔
868
                    $hasOldRule = true;
4✔
869
                    $message .= \sprintf(
4✔
870
                        '"%s" is renamed (did you mean "%s"?%s), ',
4✔
871
                        $unknownFixer,
4✔
872
                        $renamedRulesFromV2ToV3[$unknownFixer]['new_name'],
4✔
873
                        isset($renamedRulesFromV2ToV3[$unknownFixer]['config']) ? ' (note: use configuration "'.Utils::toString($renamedRulesFromV2ToV3[$unknownFixer]['config']).'")' : '',
4✔
874
                    );
4✔
875
                } else { // Go to normal matcher if it is not a renamed rule
876
                    $matcher = new WordMatcher($availableFixers);
2✔
877
                    $alternative = $matcher->match($unknownFixer);
2✔
878
                    $message .= \sprintf(
2✔
879
                        '"%s"%s, ',
2✔
880
                        $unknownFixer,
2✔
881
                        null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)',
2✔
882
                    );
2✔
883
                }
884
            }
885

886
            $message = substr($message, 0, -2).'.';
5✔
887

888
            if ($hasOldRule) {
5✔
889
                $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✔
890
            }
891

892
            throw new InvalidConfigurationException($message);
5✔
893
        }
894

895
        foreach ($fixers as $fixer) {
10✔
896
            $fixerName = $fixer->getName();
10✔
897
            if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) {
10✔
898
                $successors = $fixer->getSuccessorsNames();
3✔
899
                $messageEnd = [] === $successors
3✔
900
                    ? \sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1)
×
901
                    : \sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors)));
3✔
902

903
                Future::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}"));
3✔
904
            }
905
        }
906
    }
907

908
    /**
909
     * Apply path on config instance.
910
     *
911
     * @return iterable<\SplFileInfo>
912
     */
913
    private function resolveFinder(): iterable
914
    {
915
        $this->configFinderIsOverridden = false;
31✔
916

917
        if ($this->isStdIn()) {
31✔
918
            return new \ArrayIterator([new StdinFileInfo()]);
×
919
        }
920

921
        if (!\in_array(
31✔
922
            $this->options['path-mode'],
31✔
923
            self::PATH_MODE_VALUES,
31✔
924
            true,
31✔
925
        )) {
31✔
926
            throw new InvalidConfigurationException(\sprintf(
×
927
                'The path-mode "%s" is not defined, supported are %s.',
×
928
                $this->options['path-mode'],
×
929
                Utils::naturalLanguageJoin(self::PATH_MODE_VALUES),
×
930
            ));
×
931
        }
932

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

935
        $paths = array_map(
31✔
936
            static fn (string $path): string => realpath($path), // @phpstan-ignore return.type
31✔
937
            $this->getPath(),
31✔
938
        );
31✔
939

940
        if (0 === \count($paths)) {
26✔
941
            if ($isIntersectionPathMode) {
5✔
942
                return new \ArrayIterator([]);
1✔
943
            }
944

945
            return $this->iterableToTraversable($this->getConfig()->getFinder());
4✔
946
        }
947

948
        $pathsByType = [
21✔
949
            'file' => [],
21✔
950
            'dir' => [],
21✔
951
        ];
21✔
952

953
        foreach ($paths as $path) {
21✔
954
            if (is_file($path)) {
21✔
955
                $pathsByType['file'][] = $path;
11✔
956
            } else {
957
                $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR;
12✔
958
            }
959
        }
960

961
        $nestedFinder = null;
21✔
962
        $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder());
21✔
963

964
        try {
965
            $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder;
21✔
966
        } catch (\Exception $e) {
4✔
967
        }
968

969
        if ($isIntersectionPathMode) {
21✔
970
            if (null === $nestedFinder) {
11✔
971
                throw new InvalidConfigurationException(
×
972
                    'Cannot create intersection with not-fully defined Finder in configuration file.',
×
973
                );
×
974
            }
975

976
            return new \CallbackFilterIterator(
11✔
977
                new \IteratorIterator($nestedFinder),
11✔
978
                static function (\SplFileInfo $current) use ($pathsByType): bool {
11✔
979
                    $currentRealPath = $current->getRealPath();
10✔
980

981
                    if (\in_array($currentRealPath, $pathsByType['file'], true)) {
10✔
982
                        return true;
3✔
983
                    }
984

985
                    foreach ($pathsByType['dir'] as $path) {
10✔
986
                        if (str_starts_with($currentRealPath, $path)) {
5✔
987
                            return true;
4✔
988
                        }
989
                    }
990

991
                    return false;
10✔
992
                },
11✔
993
            );
11✔
994
        }
995

996
        if (null !== $this->getConfigFile() && null !== $nestedFinder) {
10✔
997
            $this->configFinderIsOverridden = true;
3✔
998
        }
999

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

1005
        return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']);
6✔
1006
    }
1007

1008
    /**
1009
     * Set option that will be resolved.
1010
     *
1011
     * @param mixed $value
1012
     */
1013
    private function setOption(string $name, $value): void
1014
    {
1015
        if (!\array_key_exists($name, $this->options)) {
103✔
1016
            throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name));
1✔
1017
        }
1018

1019
        $this->options[$name] = $value;
102✔
1020
    }
1021

1022
    /**
1023
     * @param key-of<_Options> $optionName
1024
     */
1025
    private function resolveOptionBooleanValue(string $optionName): bool
1026
    {
1027
        $value = $this->options[$optionName];
12✔
1028

1029
        if (self::BOOL_YES === $value) {
12✔
1030
            return true;
6✔
1031
        }
1032

1033
        if (self::BOOL_NO === $value) {
7✔
1034
            return false;
6✔
1035
        }
1036

1037
        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✔
1038
    }
1039

1040
    private static function separatedContextLessInclude(string $path): ConfigInterface
1041
    {
1042
        $config = include $path;
20✔
1043

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

1049
        return $config;
19✔
1050
    }
1051

1052
    private function isCachingAllowedForRuntime(): bool
1053
    {
1054
        return $this->toolInfo->isInstalledAsPhar()
11✔
1055
            || $this->toolInfo->isInstalledByComposer()
11✔
1056
            || $this->toolInfo->isRunInsideDocker()
11✔
1057
            || filter_var(getenv('PHP_CS_FIXER_ENFORCE_CACHE'), \FILTER_VALIDATE_BOOL);
11✔
1058
    }
1059
}
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