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

keradus / PHP-CS-Fixer / 16999983712

15 Aug 2025 09:42PM UTC coverage: 94.75% (-0.09%) from 94.839%
16999983712

push

github

keradus
ci: more self-fixing checks on lowest/highest PHP

28263 of 29829 relevant lines covered (94.75%)

45.88 hits per line

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

90.0
/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\Differ\DifferInterface;
30
use PhpCsFixer\Differ\NullDiffer;
31
use PhpCsFixer\Differ\UnifiedDiffer;
32
use PhpCsFixer\Finder;
33
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
34
use PhpCsFixer\Fixer\FixerInterface;
35
use PhpCsFixer\FixerFactory;
36
use PhpCsFixer\Linter\Linter;
37
use PhpCsFixer\Linter\LinterInterface;
38
use PhpCsFixer\ParallelAwareConfigInterface;
39
use PhpCsFixer\RuleSet\RuleSet;
40
use PhpCsFixer\RuleSet\RuleSetInterface;
41
use PhpCsFixer\Runner\Parallel\ParallelConfig;
42
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
43
use PhpCsFixer\StdinFileInfo;
44
use PhpCsFixer\ToolInfoInterface;
45
use PhpCsFixer\UnsupportedPhpVersionAllowedConfigInterface;
46
use PhpCsFixer\Utils;
47
use PhpCsFixer\WhitespacesFixerConfig;
48
use PhpCsFixer\WordMatcher;
49
use Symfony\Component\Filesystem\Filesystem;
50
use Symfony\Component\Finder\Finder as SymfonyFinder;
51

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

88
    public const BOOL_YES = 'yes';
89
    public const BOOL_NO = 'no';
90
    public const BOOL_VALUES = [
91
        self::BOOL_YES,
92
        self::BOOL_NO,
93
    ];
94

95
    /**
96
     * @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
97
     */
98
    private ?string $deprecatedNestedConfigDir = null;
99

100
    private ?bool $allowRisky = null;
101

102
    private ?ConfigInterface $config = null;
103

104
    private ?string $configFile = null;
105

106
    private string $cwd;
107

108
    private ConfigInterface $defaultConfig;
109

110
    private ?ReporterInterface $reporter = null;
111

112
    private ?bool $isStdIn = null;
113

114
    private ?bool $isDryRun = null;
115

116
    /**
117
     * @var null|list<FixerInterface>
118
     */
119
    private ?array $fixers = null;
120

121
    private ?bool $configFinderIsOverridden = null;
122

123
    private ToolInfoInterface $toolInfo;
124

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

146
    private ?string $cacheFile = null;
147

148
    private ?CacheManagerInterface $cacheManager = null;
149

150
    private ?DifferInterface $differ = null;
151

152
    private ?Directory $directory = null;
153

154
    /**
155
     * @var null|iterable<\SplFileInfo>
156
     */
157
    private ?iterable $finder = null;
158

159
    private ?string $format = null;
160

161
    private ?Linter $linter = null;
162

163
    /**
164
     * @var null|list<string>
165
     */
166
    private ?array $path = null;
167

168
    /**
169
     * @var null|ProgressOutputType::*
170
     */
171
    private $progress;
172

173
    private ?RuleSet $ruleSet = null;
174

175
    private ?bool $usingCache = null;
176

177
    private ?bool $isUnsupportedPhpVersionAllowed = null;
178

179
    private ?FixerFactory $fixerFactory = null;
180

181
    /**
182
     * @param array<string, mixed> $options
183
     */
184
    public function __construct(
185
        ConfigInterface $config,
186
        array $options,
187
        string $cwd,
188
        ToolInfoInterface $toolInfo
189
    ) {
190
        $this->defaultConfig = $config;
126✔
191
        $this->cwd = $cwd;
126✔
192
        $this->toolInfo = $toolInfo;
126✔
193

194
        foreach ($options as $name => $value) {
126✔
195
            $this->setOption($name, $value);
102✔
196
        }
197
    }
198

199
    public function getCacheFile(): ?string
200
    {
201
        if (!$this->getUsingCache()) {
10✔
202
            return null;
4✔
203
        }
204

205
        if (null === $this->cacheFile) {
6✔
206
            if (null === $this->options['cache-file']) {
6✔
207
                $this->cacheFile = $this->getConfig()->getCacheFile();
4✔
208
            } else {
209
                $this->cacheFile = $this->options['cache-file'];
2✔
210
            }
211
        }
212

213
        return $this->cacheFile;
6✔
214
    }
215

216
    public function getCacheManager(): CacheManagerInterface
217
    {
218
        if (null === $this->cacheManager) {
1✔
219
            $cacheFile = $this->getCacheFile();
1✔
220

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

239
        return $this->cacheManager;
1✔
240
    }
241

242
    public function getConfig(): ConfigInterface
243
    {
244
        if (null === $this->config) {
79✔
245
            foreach ($this->computeConfigFiles() as $configFile) {
79✔
246
                if (!file_exists($configFile)) {
78✔
247
                    continue;
63✔
248
                }
249

250
                $configFileBasename = basename($configFile);
20✔
251

252
                /** @TODO v4 drop handling (triggering error) for v2 config names */
253
                $deprecatedConfigs = [
20✔
254
                    '.php_cs' => '.php-cs-fixer.php',
20✔
255
                    '.php_cs.dist' => '.php-cs-fixer.dist.php',
20✔
256
                ];
20✔
257

258
                if (isset($deprecatedConfigs[$configFileBasename])) {
20✔
259
                    throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`.");
×
260
                }
261

262
                if (null !== $this->deprecatedNestedConfigDir && str_starts_with($configFile, $this->deprecatedNestedConfigDir)) {
20✔
263
                    // @TODO v4: when removing, remove also TODO with `MARKER-multi-paths-vs-only-cwd-config`
264
                    Utils::triggerDeprecation(
7✔
265
                        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✔
266
                    );
7✔
267
                }
268

269
                $this->config = self::separatedContextLessInclude($configFile);
20✔
270
                $this->configFile = $configFile;
19✔
271

272
                break;
19✔
273
            }
274

275
            if (null === $this->config) {
77✔
276
                $this->config = $this->defaultConfig;
58✔
277
            }
278
        }
279

280
        return $this->config;
77✔
281
    }
282

283
    public function getParallelConfig(): ParallelConfig
284
    {
285
        $config = $this->getConfig();
3✔
286

287
        return true !== $this->options['sequential'] && $config instanceof ParallelAwareConfigInterface
3✔
288
            ? $config->getParallelConfig()
2✔
289
            : ParallelConfigFactory::sequential();
3✔
290
    }
291

292
    public function getConfigFile(): ?string
293
    {
294
        if (null === $this->configFile) {
19✔
295
            $this->getConfig();
14✔
296
        }
297

298
        return $this->configFile;
19✔
299
    }
300

301
    public function getDiffer(): DifferInterface
302
    {
303
        if (null === $this->differ) {
4✔
304
            $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer();
4✔
305
        }
306

307
        return $this->differ;
4✔
308
    }
309

310
    public function getDirectory(): DirectoryInterface
311
    {
312
        if (null === $this->directory) {
4✔
313
            $path = $this->getCacheFile();
4✔
314
            if (null === $path) {
4✔
315
                $absolutePath = $this->cwd;
1✔
316
            } else {
317
                $filesystem = new Filesystem();
3✔
318

319
                $absolutePath = $filesystem->isAbsolutePath($path)
3✔
320
                    ? $path
2✔
321
                    : $this->cwd.\DIRECTORY_SEPARATOR.$path;
1✔
322
                $absolutePath = \dirname($absolutePath);
3✔
323
            }
324

325
            $this->directory = new Directory($absolutePath);
4✔
326
        }
327

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

331
    /**
332
     * @return list<FixerInterface>
333
     */
334
    public function getFixers(): array
335
    {
336
        if (null === $this->fixers) {
5✔
337
            $this->fixers = $this->createFixerFactory()
5✔
338
                ->useRuleSet($this->getRuleSet())
5✔
339
                ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding()))
5✔
340
                ->getFixers()
5✔
341
            ;
5✔
342

343
            if (false === $this->getRiskyAllowed()) {
5✔
344
                $riskyFixers = array_map(
3✔
345
                    static fn (FixerInterface $fixer): string => $fixer->getName(),
3✔
346
                    array_filter(
3✔
347
                        $this->fixers,
3✔
348
                        static fn (FixerInterface $fixer): bool => $fixer->isRisky()
3✔
349
                    )
3✔
350
                );
3✔
351

352
                if (\count($riskyFixers) > 0) {
3✔
353
                    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)));
×
354
                }
355
            }
356
        }
357

358
        return $this->fixers;
5✔
359
    }
360

361
    public function getLinter(): LinterInterface
362
    {
363
        if (null === $this->linter) {
1✔
364
            $this->linter = new Linter();
1✔
365
        }
366

367
        return $this->linter;
1✔
368
    }
369

370
    /**
371
     * Returns path.
372
     *
373
     * @return list<string>
374
     */
375
    public function getPath(): array
376
    {
377
        if (null === $this->path) {
93✔
378
            $filesystem = new Filesystem();
93✔
379
            $cwd = $this->cwd;
93✔
380

381
            if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) {
93✔
382
                $this->path = $this->options['path'];
×
383
            } else {
384
                $this->path = array_map(
93✔
385
                    static function (string $rawPath) use ($cwd, $filesystem): string {
93✔
386
                        $path = trim($rawPath);
46✔
387

388
                        if ('' === $path) {
46✔
389
                            throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\".");
6✔
390
                        }
391

392
                        $absolutePath = $filesystem->isAbsolutePath($path)
42✔
393
                            ? $path
37✔
394
                            : $cwd.\DIRECTORY_SEPARATOR.$path;
5✔
395

396
                        if (!file_exists($absolutePath)) {
42✔
397
                            throw new InvalidConfigurationException(\sprintf(
5✔
398
                                'The path "%s" is not readable.',
5✔
399
                                $path
5✔
400
                            ));
5✔
401
                        }
402

403
                        return $absolutePath;
37✔
404
                    },
93✔
405
                    $this->options['path']
93✔
406
                );
93✔
407
            }
408
        }
409

410
        return $this->path;
82✔
411
    }
412

413
    /**
414
     * @return ProgressOutputType::*
415
     *
416
     * @throws InvalidConfigurationException
417
     */
418
    public function getProgressType(): string
419
    {
420
        if (null === $this->progress) {
13✔
421
            if ('txt' === $this->resolveFormat()) {
13✔
422
                $progressType = $this->options['show-progress'];
11✔
423

424
                if (null === $progressType) {
11✔
425
                    $progressType = $this->getConfig()->getHideProgress()
4✔
426
                        ? ProgressOutputType::NONE
2✔
427
                        : ProgressOutputType::BAR;
2✔
428
                } elseif (!\in_array($progressType, ProgressOutputType::all(), true)) {
7✔
429
                    throw new InvalidConfigurationException(\sprintf(
1✔
430
                        'The progress type "%s" is not defined, supported are %s.',
1✔
431
                        $progressType,
1✔
432
                        Utils::naturalLanguageJoin(ProgressOutputType::all())
1✔
433
                    ));
1✔
434
                }
435

436
                $this->progress = $progressType;
10✔
437
            } else {
438
                $this->progress = ProgressOutputType::NONE;
2✔
439
            }
440
        }
441

442
        return $this->progress;
12✔
443
    }
444

445
    public function getReporter(): ReporterInterface
446
    {
447
        if (null === $this->reporter) {
8✔
448
            $reporterFactory = new ReporterFactory();
8✔
449
            $reporterFactory->registerBuiltInReporters();
8✔
450

451
            $format = $this->resolveFormat();
8✔
452

453
            try {
454
                $this->reporter = $reporterFactory->getReporter($format);
8✔
455
            } catch (\UnexpectedValueException $e) {
1✔
456
                $formats = $reporterFactory->getFormats();
1✔
457
                sort($formats);
1✔
458

459
                throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats)));
1✔
460
            }
461
        }
462

463
        return $this->reporter;
7✔
464
    }
465

466
    public function getRiskyAllowed(): bool
467
    {
468
        if (null === $this->allowRisky) {
18✔
469
            if (null === $this->options['allow-risky']) {
18✔
470
                $this->allowRisky = $this->getConfig()->getRiskyAllowed();
10✔
471
            } else {
472
                $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky');
8✔
473
            }
474
        }
475

476
        return $this->allowRisky;
17✔
477
    }
478

479
    /**
480
     * Returns rules.
481
     *
482
     * @return array<string, array<string, mixed>|bool>
483
     */
484
    public function getRules(): array
485
    {
486
        return $this->getRuleSet()->getRules();
11✔
487
    }
488

489
    public function getUsingCache(): bool
490
    {
491
        if (null === $this->usingCache) {
22✔
492
            if (null === $this->options['using-cache']) {
22✔
493
                $this->usingCache = $this->getConfig()->getUsingCache();
17✔
494
            } else {
495
                $this->usingCache = $this->resolveOptionBooleanValue('using-cache');
5✔
496
            }
497
        }
498

499
        $this->usingCache = $this->usingCache && $this->isCachingAllowedForRuntime();
22✔
500

501
        return $this->usingCache;
22✔
502
    }
503

504
    public function getUnsupportedPhpVersionAllowed(): bool
505
    {
506
        if (null === $this->isUnsupportedPhpVersionAllowed) {
×
507
            if (null === $this->options['allow-unsupported-php-version']) {
×
508
                $config = $this->getConfig();
×
509
                $this->isUnsupportedPhpVersionAllowed = $config instanceof UnsupportedPhpVersionAllowedConfigInterface
×
510
                    ? $config->getUnsupportedPhpVersionAllowed()
×
511
                    : false;
×
512
            } else {
513
                $this->isUnsupportedPhpVersionAllowed = $this->resolveOptionBooleanValue('allow-unsupported-php-version');
×
514
            }
515
        }
516

517
        return $this->isUnsupportedPhpVersionAllowed;
×
518
    }
519

520
    /**
521
     * @return iterable<\SplFileInfo>
522
     */
523
    public function getFinder(): iterable
524
    {
525
        if (null === $this->finder) {
31✔
526
            $this->finder = $this->resolveFinder();
31✔
527
        }
528

529
        return $this->finder;
26✔
530
    }
531

532
    /**
533
     * Returns dry-run flag.
534
     */
535
    public function isDryRun(): bool
536
    {
537
        if (null === $this->isDryRun) {
4✔
538
            if ($this->isStdIn()) {
4✔
539
                // Can't write to STDIN
540
                $this->isDryRun = true;
1✔
541
            } else {
542
                $this->isDryRun = $this->options['dry-run'];
3✔
543
            }
544
        }
545

546
        return $this->isDryRun;
4✔
547
    }
548

549
    public function shouldStopOnViolation(): bool
550
    {
551
        return $this->options['stop-on-violation'];
1✔
552
    }
553

554
    public function configFinderIsOverridden(): bool
555
    {
556
        if (null === $this->configFinderIsOverridden) {
7✔
557
            $this->resolveFinder();
7✔
558
        }
559

560
        return $this->configFinderIsOverridden;
7✔
561
    }
562

563
    /**
564
     * Compute file candidates for config file.
565
     *
566
     * @TODO v4: don't offer configs from passed `path` CLI argument
567
     *
568
     * @return list<string>
569
     */
570
    private function computeConfigFiles(): array
571
    {
572
        $configFile = $this->options['config'];
79✔
573

574
        if (null !== $configFile) {
79✔
575
            if (false === file_exists($configFile) || false === is_readable($configFile)) {
11✔
576
                throw new InvalidConfigurationException(\sprintf('Cannot read config file "%s".', $configFile));
×
577
            }
578

579
            return [$configFile];
11✔
580
        }
581

582
        $path = $this->getPath();
68✔
583

584
        if ($this->isStdIn() || 0 === \count($path)) {
68✔
585
            $configDir = $this->cwd;
45✔
586
        } elseif (1 < \count($path)) {
23✔
587
            // @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config`
588
            throw new InvalidConfigurationException('For multiple paths config parameter is required.');
1✔
589
        } elseif (!is_file($path[0])) {
22✔
590
            $configDir = $path[0];
12✔
591
        } else {
592
            $dirName = pathinfo($path[0], \PATHINFO_DIRNAME);
10✔
593
            $configDir = is_dir($dirName) ? $dirName : $path[0];
10✔
594
        }
595

596
        $candidates = [
67✔
597
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
67✔
598
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
67✔
599

600
            // @TODO v4 drop handling (triggering error) for v2 config names
601
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later
67✔
602
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later
67✔
603
        ];
67✔
604

605
        if ($configDir !== $this->cwd) {
67✔
606
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php';
22✔
607
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php';
22✔
608

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

613
            $this->deprecatedNestedConfigDir = $configDir;
22✔
614
        }
615

616
        return $candidates;
67✔
617
    }
618

619
    private function createFixerFactory(): FixerFactory
620
    {
621
        if (null === $this->fixerFactory) {
15✔
622
            $fixerFactory = new FixerFactory();
15✔
623
            $fixerFactory->registerBuiltInFixers();
15✔
624
            $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers());
15✔
625

626
            $this->fixerFactory = $fixerFactory;
15✔
627
        }
628

629
        return $this->fixerFactory;
15✔
630
    }
631

632
    private function resolveFormat(): string
633
    {
634
        if (null === $this->format) {
19✔
635
            $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat();
19✔
636
            $parts = explode(',', $formatCandidate);
19✔
637

638
            if (\count($parts) > 2) {
19✔
639
                throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate));
×
640
            }
641

642
            $this->format = $parts[0];
19✔
643

644
            if ('@auto' === $this->format) {
19✔
645
                $this->format = $parts[1] ?? 'txt';
3✔
646

647
                if (filter_var(getenv('GITLAB_CI'), \FILTER_VALIDATE_BOOL)) {
3✔
648
                    $this->format = 'gitlab';
1✔
649
                }
650
            }
651
        }
652

653
        return $this->format;
19✔
654
    }
655

656
    private function getRuleSet(): RuleSetInterface
657
    {
658
        if (null === $this->ruleSet) {
16✔
659
            $rules = $this->parseRules();
16✔
660
            $this->validateRules($rules);
15✔
661

662
            $this->ruleSet = new RuleSet($rules);
10✔
663
        }
664

665
        return $this->ruleSet;
10✔
666
    }
667

668
    private function isStdIn(): bool
669
    {
670
        if (null === $this->isStdIn) {
86✔
671
            $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0];
86✔
672
        }
673

674
        return $this->isStdIn;
86✔
675
    }
676

677
    /**
678
     * @template T
679
     *
680
     * @param iterable<T> $iterable
681
     *
682
     * @return \Traversable<T>
683
     */
684
    private function iterableToTraversable(iterable $iterable): \Traversable
685
    {
686
        return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable;
25✔
687
    }
688

689
    /**
690
     * @return array<string, mixed>
691
     */
692
    private function parseRules(): array
693
    {
694
        if (null === $this->options['rules']) {
16✔
695
            return $this->getConfig()->getRules();
7✔
696
        }
697

698
        $rules = trim($this->options['rules']);
9✔
699
        if ('' === $rules) {
9✔
700
            throw new InvalidConfigurationException('Empty rules value is not allowed.');
1✔
701
        }
702

703
        if (str_starts_with($rules, '{')) {
8✔
704
            $rules = json_decode($rules, true);
×
705

706
            if (\JSON_ERROR_NONE !== json_last_error()) {
×
707
                throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', json_last_error_msg()));
×
708
            }
709

710
            return $rules;
×
711
        }
712

713
        $rules = [];
8✔
714

715
        foreach (explode(',', $this->options['rules']) as $rule) {
8✔
716
            $rule = trim($rule);
8✔
717

718
            if ('' === $rule) {
8✔
719
                throw new InvalidConfigurationException('Empty rule name is not allowed.');
×
720
            }
721

722
            if (str_starts_with($rule, '-')) {
8✔
723
                $rules[substr($rule, 1)] = false;
2✔
724
            } else {
725
                $rules[$rule] = true;
8✔
726
            }
727
        }
728

729
        return $rules;
8✔
730
    }
731

732
    /**
733
     * @param array<string, mixed> $rules
734
     *
735
     * @throws InvalidConfigurationException
736
     */
737
    private function validateRules(array $rules): void
738
    {
739
        /**
740
         * Create a ruleset that contains all configured rules, even when they originally have been disabled.
741
         *
742
         * @see RuleSet::resolveSet()
743
         */
744
        $ruleSet = [];
15✔
745

746
        foreach ($rules as $key => $value) {
15✔
747
            if (\is_int($key)) {
15✔
748
                throw new InvalidConfigurationException(\sprintf('Missing value for "%s" rule/set.', $value));
×
749
            }
750

751
            $ruleSet[$key] = true;
15✔
752
        }
753

754
        $ruleSet = new RuleSet($ruleSet);
15✔
755

756
        $configuredFixers = array_keys($ruleSet->getRules());
15✔
757

758
        $fixers = $this->createFixerFactory()->getFixers();
15✔
759

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

762
        $unknownFixers = array_diff($configuredFixers, $availableFixers);
15✔
763

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

818
            $message = 'The rules contain unknown fixers: ';
5✔
819
            $hasOldRule = false;
5✔
820

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

841
            $message = substr($message, 0, -2).'.';
5✔
842

843
            if ($hasOldRule) {
5✔
844
                $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✔
845
            }
846

847
            throw new InvalidConfigurationException($message);
5✔
848
        }
849

850
        foreach ($fixers as $fixer) {
10✔
851
            $fixerName = $fixer->getName();
10✔
852
            if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) {
10✔
853
                $successors = $fixer->getSuccessorsNames();
3✔
854
                $messageEnd = [] === $successors
3✔
855
                    ? \sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1)
×
856
                    : \sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors)));
3✔
857

858
                Utils::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}"));
3✔
859
            }
860
        }
861
    }
862

863
    /**
864
     * Apply path on config instance.
865
     *
866
     * @return iterable<\SplFileInfo>
867
     */
868
    private function resolveFinder(): iterable
869
    {
870
        $this->configFinderIsOverridden = false;
31✔
871

872
        if ($this->isStdIn()) {
31✔
873
            return new \ArrayIterator([new StdinFileInfo()]);
×
874
        }
875

876
        if (!\in_array(
31✔
877
            $this->options['path-mode'],
31✔
878
            self::PATH_MODE_VALUES,
31✔
879
            true
31✔
880
        )) {
31✔
881
            throw new InvalidConfigurationException(\sprintf(
×
882
                'The path-mode "%s" is not defined, supported are %s.',
×
883
                $this->options['path-mode'],
×
884
                Utils::naturalLanguageJoin(self::PATH_MODE_VALUES)
×
885
            ));
×
886
        }
887

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

890
        $paths = array_map(
31✔
891
            static fn (string $path) => realpath($path),
31✔
892
            $this->getPath()
31✔
893
        );
31✔
894

895
        if (0 === \count($paths)) {
26✔
896
            if ($isIntersectionPathMode) {
5✔
897
                return new \ArrayIterator([]);
1✔
898
            }
899

900
            return $this->iterableToTraversable($this->getConfig()->getFinder());
4✔
901
        }
902

903
        $pathsByType = [
21✔
904
            'file' => [],
21✔
905
            'dir' => [],
21✔
906
        ];
21✔
907

908
        foreach ($paths as $path) {
21✔
909
            if (is_file($path)) {
21✔
910
                $pathsByType['file'][] = $path;
11✔
911
            } else {
912
                $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR;
12✔
913
            }
914
        }
915

916
        $nestedFinder = null;
21✔
917
        $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder());
21✔
918

919
        try {
920
            $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder;
21✔
921
        } catch (\Exception $e) {
4✔
922
        }
923

924
        if ($isIntersectionPathMode) {
21✔
925
            if (null === $nestedFinder) {
11✔
926
                throw new InvalidConfigurationException(
×
927
                    'Cannot create intersection with not-fully defined Finder in configuration file.'
×
928
                );
×
929
            }
930

931
            return new \CallbackFilterIterator(
11✔
932
                new \IteratorIterator($nestedFinder),
11✔
933
                static function (\SplFileInfo $current) use ($pathsByType): bool {
11✔
934
                    $currentRealPath = $current->getRealPath();
10✔
935

936
                    if (\in_array($currentRealPath, $pathsByType['file'], true)) {
10✔
937
                        return true;
3✔
938
                    }
939

940
                    foreach ($pathsByType['dir'] as $path) {
10✔
941
                        if (str_starts_with($currentRealPath, $path)) {
5✔
942
                            return true;
4✔
943
                        }
944
                    }
945

946
                    return false;
10✔
947
                }
11✔
948
            );
11✔
949
        }
950

951
        if (null !== $this->getConfigFile() && null !== $nestedFinder) {
10✔
952
            $this->configFinderIsOverridden = true;
3✔
953
        }
954

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

960
        return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']);
6✔
961
    }
962

963
    /**
964
     * Set option that will be resolved.
965
     *
966
     * @param mixed $value
967
     */
968
    private function setOption(string $name, $value): void
969
    {
970
        if (!\array_key_exists($name, $this->options)) {
102✔
971
            throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name));
1✔
972
        }
973

974
        $this->options[$name] = $value;
101✔
975
    }
976

977
    /**
978
     * @param key-of<_Options> $optionName
979
     */
980
    private function resolveOptionBooleanValue(string $optionName): bool
981
    {
982
        $value = $this->options[$optionName];
12✔
983

984
        if (self::BOOL_YES === $value) {
12✔
985
            return true;
6✔
986
        }
987

988
        if (self::BOOL_NO === $value) {
7✔
989
            return false;
6✔
990
        }
991

992
        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✔
993
    }
994

995
    private static function separatedContextLessInclude(string $path): ConfigInterface
996
    {
997
        $config = include $path;
20✔
998

999
        // verify that the config has an instance of Config
1000
        if (!$config instanceof ConfigInterface) {
20✔
1001
            throw new InvalidConfigurationException(\sprintf('The config file: "%s" does not return a "PhpCsFixer\ConfigInterface" instance. Got: "%s".', $path, \is_object($config) ? \get_class($config) : \gettype($config)));
1✔
1002
        }
1003

1004
        return $config;
19✔
1005
    }
1006

1007
    private function isCachingAllowedForRuntime(): bool
1008
    {
1009
        return $this->toolInfo->isInstalledAsPhar()
14✔
1010
            || $this->toolInfo->isInstalledByComposer()
14✔
1011
            || $this->toolInfo->isRunInsideDocker()
14✔
1012
            || filter_var(getenv('PHP_CS_FIXER_ENFORCE_CACHE'), \FILTER_VALIDATE_BOOL);
14✔
1013
    }
1014
}
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