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

PHP-CS-Fixer / PHP-CS-Fixer / 15906293412

26 Jun 2025 03:39PM UTC coverage: 94.829% (-0.04%) from 94.87%
15906293412

Pull #8733

github

web-flow
Merge f9db1d7b2 into a32defda7
Pull Request #8733: feat: allowUnsupportedPhpVersion

22 of 33 new or added lines in 3 files covered. (66.67%)

3 existing lines in 1 file now uncovered.

28129 of 29663 relevant lines covered (94.83%)

45.34 hits per line

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

89.9
/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
 * @author Fabien Potencier <fabien@symfony.com>
56
 * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
57
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
58
 *
59
 * @internal
60
 *
61
 * @phpstan-type _Options array{
62
 *      allow-risky: null|string,
63
 *      cache-file: null|string,
64
 *      config: null|string,
65
 *      diff: null|string,
66
 *      dry-run: null|bool,
67
 *      format: null|string,
68
 *      path: list<string>,
69
 *      path-mode: self::PATH_MODE_*,
70
 *      rules: null|string,
71
 *      sequential: null|string,
72
 *      show-progress: null|string,
73
 *      stop-on-violation: null|bool,
74
 *      using-cache: null|string,
75
 *      allow-unsupported-php-version: null|bool,
76
 *      verbosity: null|string,
77
 *  }
78
 */
79
final class ConfigurationResolver
80
{
81
    public const PATH_MODE_OVERRIDE = 'override';
82
    public const PATH_MODE_INTERSECTION = 'intersection';
83

84
    private ?bool $allowRisky = null;
85

86
    private ?ConfigInterface $config = null;
87

88
    private ?string $configFile = null;
89

90
    private string $cwd;
91

92
    private ConfigInterface $defaultConfig;
93

94
    private ?ReporterInterface $reporter = null;
95

96
    private ?bool $isStdIn = null;
97

98
    private ?bool $isDryRun = null;
99

100
    /**
101
     * @var null|list<FixerInterface>
102
     */
103
    private ?array $fixers = null;
104

105
    private ?bool $configFinderIsOverridden = null;
106

107
    private ToolInfoInterface $toolInfo;
108

109
    /**
110
     * @var _Options
111
     */
112
    private array $options = [
113
        'allow-risky' => null,
114
        'cache-file' => null,
115
        'config' => null,
116
        'diff' => null,
117
        'dry-run' => null,
118
        'format' => null,
119
        'path' => [],
120
        'path-mode' => self::PATH_MODE_OVERRIDE,
121
        'rules' => null,
122
        'sequential' => null,
123
        'show-progress' => null,
124
        'stop-on-violation' => null,
125
        'using-cache' => null,
126
        'allow-unsupported-php-version' => null,
127
        'verbosity' => null,
128
    ];
129

130
    private ?string $cacheFile = null;
131

132
    private ?CacheManagerInterface $cacheManager = null;
133

134
    private ?DifferInterface $differ = null;
135

136
    private ?Directory $directory = null;
137

138
    /**
139
     * @var null|iterable<\SplFileInfo>
140
     */
141
    private ?iterable $finder = null;
142

143
    private ?string $format = null;
144

145
    private ?Linter $linter = null;
146

147
    /**
148
     * @var null|list<string>
149
     */
150
    private ?array $path = null;
151

152
    /**
153
     * @var null|ProgressOutputType::*
154
     */
155
    private $progress;
156

157
    private ?RuleSet $ruleSet = null;
158

159
    private ?bool $usingCache = null;
160

161
    private ?bool $isUnsupportedPhpVersionAllowed = null;
162

163
    private ?FixerFactory $fixerFactory = null;
164

165
    /**
166
     * @param array<string, mixed> $options
167
     */
168
    public function __construct(
169
        ConfigInterface $config,
170
        array $options,
171
        string $cwd,
172
        ToolInfoInterface $toolInfo
173
    ) {
174
        $this->defaultConfig = $config;
126✔
175
        $this->cwd = $cwd;
126✔
176
        $this->toolInfo = $toolInfo;
126✔
177

178
        foreach ($options as $name => $value) {
126✔
179
            $this->setOption($name, $value);
102✔
180
        }
181
    }
182

183
    public function getCacheFile(): ?string
184
    {
185
        if (!$this->getUsingCache()) {
10✔
186
            return null;
4✔
187
        }
188

189
        if (null === $this->cacheFile) {
6✔
190
            if (null === $this->options['cache-file']) {
6✔
191
                $this->cacheFile = $this->getConfig()->getCacheFile();
4✔
192
            } else {
193
                $this->cacheFile = $this->options['cache-file'];
2✔
194
            }
195
        }
196

197
        return $this->cacheFile;
6✔
198
    }
199

200
    public function getCacheManager(): CacheManagerInterface
201
    {
202
        if (null === $this->cacheManager) {
1✔
203
            $cacheFile = $this->getCacheFile();
1✔
204

205
            if (null === $cacheFile) {
1✔
206
                $this->cacheManager = new NullCacheManager();
1✔
207
            } else {
208
                $this->cacheManager = new FileCacheManager(
×
209
                    new FileHandler($cacheFile),
×
210
                    new Signature(
×
211
                        PHP_VERSION,
×
212
                        $this->toolInfo->getVersion(),
×
213
                        $this->getConfig()->getIndent(),
×
214
                        $this->getConfig()->getLineEnding(),
×
215
                        $this->getRules()
×
216
                    ),
×
217
                    $this->isDryRun(),
×
218
                    $this->getDirectory()
×
219
                );
×
220
            }
221
        }
222

223
        return $this->cacheManager;
1✔
224
    }
225

226
    public function getConfig(): ConfigInterface
227
    {
228
        if (null === $this->config) {
79✔
229
            foreach ($this->computeConfigFiles() as $configFile) {
79✔
230
                if (!file_exists($configFile)) {
78✔
231
                    continue;
63✔
232
                }
233

234
                $configFileBasename = basename($configFile);
20✔
235
                $deprecatedConfigs = [
20✔
236
                    '.php_cs' => '.php-cs-fixer.php',
20✔
237
                    '.php_cs.dist' => '.php-cs-fixer.dist.php',
20✔
238
                ];
20✔
239

240
                if (isset($deprecatedConfigs[$configFileBasename])) {
20✔
241
                    throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`.");
×
242
                }
243

244
                $this->config = self::separatedContextLessInclude($configFile);
20✔
245
                $this->configFile = $configFile;
19✔
246

247
                break;
19✔
248
            }
249

250
            if (null === $this->config) {
77✔
251
                $this->config = $this->defaultConfig;
58✔
252
            }
253
        }
254

255
        return $this->config;
77✔
256
    }
257

258
    public function getParallelConfig(): ParallelConfig
259
    {
260
        $config = $this->getConfig();
3✔
261

262
        return true !== $this->options['sequential'] && $config instanceof ParallelAwareConfigInterface
3✔
263
            ? $config->getParallelConfig()
2✔
264
            : ParallelConfigFactory::sequential();
3✔
265
    }
266

267
    public function getConfigFile(): ?string
268
    {
269
        if (null === $this->configFile) {
19✔
270
            $this->getConfig();
14✔
271
        }
272

273
        return $this->configFile;
19✔
274
    }
275

276
    public function getDiffer(): DifferInterface
277
    {
278
        if (null === $this->differ) {
4✔
279
            $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer();
4✔
280
        }
281

282
        return $this->differ;
4✔
283
    }
284

285
    public function getDirectory(): DirectoryInterface
286
    {
287
        if (null === $this->directory) {
4✔
288
            $path = $this->getCacheFile();
4✔
289
            if (null === $path) {
4✔
290
                $absolutePath = $this->cwd;
1✔
291
            } else {
292
                $filesystem = new Filesystem();
3✔
293

294
                $absolutePath = $filesystem->isAbsolutePath($path)
3✔
295
                    ? $path
2✔
296
                    : $this->cwd.\DIRECTORY_SEPARATOR.$path;
1✔
297
                $absolutePath = \dirname($absolutePath);
3✔
298
            }
299

300
            $this->directory = new Directory($absolutePath);
4✔
301
        }
302

303
        return $this->directory;
4✔
304
    }
305

306
    /**
307
     * @return list<FixerInterface>
308
     */
309
    public function getFixers(): array
310
    {
311
        if (null === $this->fixers) {
5✔
312
            $this->fixers = $this->createFixerFactory()
5✔
313
                ->useRuleSet($this->getRuleSet())
5✔
314
                ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding()))
5✔
315
                ->getFixers()
5✔
316
            ;
5✔
317

318
            if (false === $this->getRiskyAllowed()) {
5✔
319
                $riskyFixers = array_map(
3✔
320
                    static fn (FixerInterface $fixer): string => $fixer->getName(),
3✔
321
                    array_filter(
3✔
322
                        $this->fixers,
3✔
323
                        static fn (FixerInterface $fixer): bool => $fixer->isRisky()
3✔
324
                    )
3✔
325
                );
3✔
326

327
                if (\count($riskyFixers) > 0) {
3✔
328
                    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)));
×
329
                }
330
            }
331
        }
332

333
        return $this->fixers;
5✔
334
    }
335

336
    public function getLinter(): LinterInterface
337
    {
338
        if (null === $this->linter) {
1✔
339
            $this->linter = new Linter();
1✔
340
        }
341

342
        return $this->linter;
1✔
343
    }
344

345
    /**
346
     * Returns path.
347
     *
348
     * @return list<string>
349
     */
350
    public function getPath(): array
351
    {
352
        if (null === $this->path) {
93✔
353
            $filesystem = new Filesystem();
93✔
354
            $cwd = $this->cwd;
93✔
355

356
            if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) {
93✔
357
                $this->path = $this->options['path'];
×
358
            } else {
359
                $this->path = array_map(
93✔
360
                    static function (string $rawPath) use ($cwd, $filesystem): string {
93✔
361
                        $path = trim($rawPath);
46✔
362

363
                        if ('' === $path) {
46✔
364
                            throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\".");
6✔
365
                        }
366

367
                        $absolutePath = $filesystem->isAbsolutePath($path)
42✔
368
                            ? $path
37✔
369
                            : $cwd.\DIRECTORY_SEPARATOR.$path;
5✔
370

371
                        if (!file_exists($absolutePath)) {
42✔
372
                            throw new InvalidConfigurationException(\sprintf(
5✔
373
                                'The path "%s" is not readable.',
5✔
374
                                $path
5✔
375
                            ));
5✔
376
                        }
377

378
                        return $absolutePath;
37✔
379
                    },
93✔
380
                    $this->options['path']
93✔
381
                );
93✔
382
            }
383
        }
384

385
        return $this->path;
82✔
386
    }
387

388
    /**
389
     * @return ProgressOutputType::*
390
     *
391
     * @throws InvalidConfigurationException
392
     */
393
    public function getProgressType(): string
394
    {
395
        if (null === $this->progress) {
13✔
396
            if ('txt' === $this->resolveFormat()) {
13✔
397
                $progressType = $this->options['show-progress'];
11✔
398

399
                if (null === $progressType) {
11✔
400
                    $progressType = $this->getConfig()->getHideProgress()
4✔
401
                        ? ProgressOutputType::NONE
2✔
402
                        : ProgressOutputType::BAR;
2✔
403
                } elseif (!\in_array($progressType, ProgressOutputType::all(), true)) {
7✔
404
                    throw new InvalidConfigurationException(\sprintf(
1✔
405
                        'The progress type "%s" is not defined, supported are %s.',
1✔
406
                        $progressType,
1✔
407
                        Utils::naturalLanguageJoin(ProgressOutputType::all())
1✔
408
                    ));
1✔
409
                }
410

411
                $this->progress = $progressType;
10✔
412
            } else {
413
                $this->progress = ProgressOutputType::NONE;
2✔
414
            }
415
        }
416

417
        return $this->progress;
12✔
418
    }
419

420
    public function getReporter(): ReporterInterface
421
    {
422
        if (null === $this->reporter) {
8✔
423
            $reporterFactory = new ReporterFactory();
8✔
424
            $reporterFactory->registerBuiltInReporters();
8✔
425

426
            $format = $this->resolveFormat();
8✔
427

428
            try {
429
                $this->reporter = $reporterFactory->getReporter($format);
8✔
430
            } catch (\UnexpectedValueException $e) {
1✔
431
                $formats = $reporterFactory->getFormats();
1✔
432
                sort($formats);
1✔
433

434
                throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats)));
1✔
435
            }
436
        }
437

438
        return $this->reporter;
7✔
439
    }
440

441
    public function getRiskyAllowed(): bool
442
    {
443
        if (null === $this->allowRisky) {
18✔
444
            if (null === $this->options['allow-risky']) {
18✔
445
                $this->allowRisky = $this->getConfig()->getRiskyAllowed();
10✔
446
            } else {
447
                $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky');
8✔
448
            }
449
        }
450

451
        return $this->allowRisky;
17✔
452
    }
453

454
    /**
455
     * Returns rules.
456
     *
457
     * @return array<string, array<string, mixed>|bool>
458
     */
459
    public function getRules(): array
460
    {
461
        return $this->getRuleSet()->getRules();
11✔
462
    }
463

464
    public function getUsingCache(): bool
465
    {
466
        if (null === $this->usingCache) {
22✔
467
            if (null === $this->options['using-cache']) {
22✔
468
                $this->usingCache = $this->getConfig()->getUsingCache();
17✔
469
            } else {
470
                $this->usingCache = $this->resolveOptionBooleanValue('using-cache');
5✔
471
            }
472
        }
473

474
        $this->usingCache = $this->usingCache && $this->isCachingAllowedForRuntime();
22✔
475

476
        return $this->usingCache;
22✔
477
    }
478

479
    public function getUnsupportedPhpVersionAllowed(): bool
480
    {
NEW
481
        if (null === $this->isUnsupportedPhpVersionAllowed) {
×
NEW
482
            if (null === $this->options['allow-unsupported-php-version']) {
×
NEW
483
                $config = $this->getConfig();
×
NEW
484
                $this->isUnsupportedPhpVersionAllowed = $config instanceof UnsupportedPhpVersionAllowedConfigInterface
×
NEW
485
                    ? $config->getUnsupportedPhpVersionAllowed()
×
NEW
486
                    : false;
×
487
            } else {
NEW
488
                $this->isUnsupportedPhpVersionAllowed = $this->resolveOptionBooleanValue('allow-unsupported-php-version');
×
489
            }
490
        }
491

NEW
492
        return $this->isUnsupportedPhpVersionAllowed;
×
493
    }
494

495
    /**
496
     * @return iterable<\SplFileInfo>
497
     */
498
    public function getFinder(): iterable
499
    {
500
        if (null === $this->finder) {
31✔
501
            $this->finder = $this->resolveFinder();
31✔
502
        }
503

504
        return $this->finder;
26✔
505
    }
506

507
    /**
508
     * Returns dry-run flag.
509
     */
510
    public function isDryRun(): bool
511
    {
512
        if (null === $this->isDryRun) {
4✔
513
            if ($this->isStdIn()) {
4✔
514
                // Can't write to STDIN
515
                $this->isDryRun = true;
1✔
516
            } else {
517
                $this->isDryRun = $this->options['dry-run'];
3✔
518
            }
519
        }
520

521
        return $this->isDryRun;
4✔
522
    }
523

524
    public function shouldStopOnViolation(): bool
525
    {
526
        return $this->options['stop-on-violation'];
1✔
527
    }
528

529
    public function configFinderIsOverridden(): bool
530
    {
531
        if (null === $this->configFinderIsOverridden) {
7✔
532
            $this->resolveFinder();
7✔
533
        }
534

535
        return $this->configFinderIsOverridden;
7✔
536
    }
537

538
    /**
539
     * Compute file candidates for config file.
540
     *
541
     * @return list<string>
542
     */
543
    private function computeConfigFiles(): array
544
    {
545
        $configFile = $this->options['config'];
79✔
546

547
        if (null !== $configFile) {
79✔
548
            if (false === file_exists($configFile) || false === is_readable($configFile)) {
11✔
549
                throw new InvalidConfigurationException(\sprintf('Cannot read config file "%s".', $configFile));
×
550
            }
551

552
            return [$configFile];
11✔
553
        }
554

555
        $path = $this->getPath();
68✔
556

557
        if ($this->isStdIn() || 0 === \count($path)) {
68✔
558
            $configDir = $this->cwd;
45✔
559
        } elseif (1 < \count($path)) {
23✔
560
            throw new InvalidConfigurationException('For multiple paths config parameter is required.');
1✔
561
        } elseif (!is_file($path[0])) {
22✔
562
            $configDir = $path[0];
12✔
563
        } else {
564
            $dirName = pathinfo($path[0], PATHINFO_DIRNAME);
10✔
565
            $configDir = is_dir($dirName) ? $dirName : $path[0];
10✔
566
        }
567

568
        $candidates = [
67✔
569
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
67✔
570
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
67✔
571
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later
67✔
572
            $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later
67✔
573
        ];
67✔
574

575
        if ($configDir !== $this->cwd) {
67✔
576
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php';
22✔
577
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php';
22✔
578
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs'; // old v2 config, present here only to throw nice error message later
22✔
579
            $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist'; // old v2 config, present here only to throw nice error message later
22✔
580
        }
581

582
        return $candidates;
67✔
583
    }
584

585
    private function createFixerFactory(): FixerFactory
586
    {
587
        if (null === $this->fixerFactory) {
15✔
588
            $fixerFactory = new FixerFactory();
15✔
589
            $fixerFactory->registerBuiltInFixers();
15✔
590
            $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers());
15✔
591

592
            $this->fixerFactory = $fixerFactory;
15✔
593
        }
594

595
        return $this->fixerFactory;
15✔
596
    }
597

598
    private function resolveFormat(): string
599
    {
600
        if (null === $this->format) {
19✔
601
            $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat();
19✔
602
            $parts = explode(',', $formatCandidate);
19✔
603

604
            if (\count($parts) > 2) {
19✔
605
                throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate));
×
606
            }
607

608
            $this->format = $parts[0];
19✔
609

610
            if ('@auto' === $this->format) {
19✔
611
                $this->format = $parts[1] ?? 'txt';
3✔
612

613
                if (filter_var(getenv('GITLAB_CI'), FILTER_VALIDATE_BOOL)) {
3✔
614
                    $this->format = 'gitlab';
1✔
615
                }
616
            }
617
        }
618

619
        return $this->format;
19✔
620
    }
621

622
    private function getRuleSet(): RuleSetInterface
623
    {
624
        if (null === $this->ruleSet) {
16✔
625
            $rules = $this->parseRules();
16✔
626
            $this->validateRules($rules);
15✔
627

628
            $this->ruleSet = new RuleSet($rules);
10✔
629
        }
630

631
        return $this->ruleSet;
10✔
632
    }
633

634
    private function isStdIn(): bool
635
    {
636
        if (null === $this->isStdIn) {
86✔
637
            $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0];
86✔
638
        }
639

640
        return $this->isStdIn;
86✔
641
    }
642

643
    /**
644
     * @template T
645
     *
646
     * @param iterable<T> $iterable
647
     *
648
     * @return \Traversable<T>
649
     */
650
    private function iterableToTraversable(iterable $iterable): \Traversable
651
    {
652
        return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable;
25✔
653
    }
654

655
    /**
656
     * @return array<string, mixed>
657
     */
658
    private function parseRules(): array
659
    {
660
        if (null === $this->options['rules']) {
16✔
661
            return $this->getConfig()->getRules();
7✔
662
        }
663

664
        $rules = trim($this->options['rules']);
9✔
665
        if ('' === $rules) {
9✔
666
            throw new InvalidConfigurationException('Empty rules value is not allowed.');
1✔
667
        }
668

669
        if (str_starts_with($rules, '{')) {
8✔
670
            $rules = json_decode($rules, true);
×
671

672
            if (JSON_ERROR_NONE !== json_last_error()) {
×
673
                throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', json_last_error_msg()));
×
674
            }
675

676
            return $rules;
×
677
        }
678

679
        $rules = [];
8✔
680

681
        foreach (explode(',', $this->options['rules']) as $rule) {
8✔
682
            $rule = trim($rule);
8✔
683

684
            if ('' === $rule) {
8✔
685
                throw new InvalidConfigurationException('Empty rule name is not allowed.');
×
686
            }
687

688
            if (str_starts_with($rule, '-')) {
8✔
689
                $rules[substr($rule, 1)] = false;
2✔
690
            } else {
691
                $rules[$rule] = true;
8✔
692
            }
693
        }
694

695
        return $rules;
8✔
696
    }
697

698
    /**
699
     * @param array<string, mixed> $rules
700
     *
701
     * @throws InvalidConfigurationException
702
     */
703
    private function validateRules(array $rules): void
704
    {
705
        /**
706
         * Create a ruleset that contains all configured rules, even when they originally have been disabled.
707
         *
708
         * @see RuleSet::resolveSet()
709
         */
710
        $ruleSet = [];
15✔
711

712
        foreach ($rules as $key => $value) {
15✔
713
            if (\is_int($key)) {
15✔
714
                throw new InvalidConfigurationException(\sprintf('Missing value for "%s" rule/set.', $value));
×
715
            }
716

717
            $ruleSet[$key] = true;
15✔
718
        }
719

720
        $ruleSet = new RuleSet($ruleSet);
15✔
721

722
        $configuredFixers = array_keys($ruleSet->getRules());
15✔
723

724
        $fixers = $this->createFixerFactory()->getFixers();
15✔
725

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

728
        $unknownFixers = array_diff($configuredFixers, $availableFixers);
15✔
729

730
        if (\count($unknownFixers) > 0) {
15✔
731
            $renamedRules = [
5✔
732
                'blank_line_before_return' => [
5✔
733
                    'new_name' => 'blank_line_before_statement',
5✔
734
                    'config' => ['statements' => ['return']],
5✔
735
                ],
5✔
736
                'final_static_access' => [
5✔
737
                    'new_name' => 'self_static_accessor',
5✔
738
                ],
5✔
739
                'hash_to_slash_comment' => [
5✔
740
                    'new_name' => 'single_line_comment_style',
5✔
741
                    'config' => ['comment_types' => ['hash']],
5✔
742
                ],
5✔
743
                'lowercase_constants' => [
5✔
744
                    'new_name' => 'constant_case',
5✔
745
                    'config' => ['case' => 'lower'],
5✔
746
                ],
5✔
747
                'no_extra_consecutive_blank_lines' => [
5✔
748
                    'new_name' => 'no_extra_blank_lines',
5✔
749
                ],
5✔
750
                'no_multiline_whitespace_before_semicolons' => [
5✔
751
                    'new_name' => 'multiline_whitespace_before_semicolons',
5✔
752
                ],
5✔
753
                'no_short_echo_tag' => [
5✔
754
                    'new_name' => 'echo_tag_syntax',
5✔
755
                    'config' => ['format' => 'long'],
5✔
756
                ],
5✔
757
                'php_unit_ordered_covers' => [
5✔
758
                    'new_name' => 'phpdoc_order_by_value',
5✔
759
                    'config' => ['annotations' => ['covers']],
5✔
760
                ],
5✔
761
                'phpdoc_inline_tag' => [
5✔
762
                    'new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type',
5✔
763
                ],
5✔
764
                'pre_increment' => [
5✔
765
                    'new_name' => 'increment_style',
5✔
766
                    'config' => ['style' => 'pre'],
5✔
767
                ],
5✔
768
                'psr0' => [
5✔
769
                    'new_name' => 'psr_autoloading',
5✔
770
                    'config' => ['dir' => 'x'],
5✔
771
                ],
5✔
772
                'psr4' => [
5✔
773
                    'new_name' => 'psr_autoloading',
5✔
774
                ],
5✔
775
                'silenced_deprecation_error' => [
5✔
776
                    'new_name' => 'error_suppression',
5✔
777
                ],
5✔
778
                'trailing_comma_in_multiline_array' => [
5✔
779
                    'new_name' => 'trailing_comma_in_multiline',
5✔
780
                    'config' => ['elements' => ['arrays']],
5✔
781
                ],
5✔
782
            ];
5✔
783

784
            $message = 'The rules contain unknown fixers: ';
5✔
785
            $hasOldRule = false;
5✔
786

787
            foreach ($unknownFixers as $unknownFixer) {
5✔
788
                if (isset($renamedRules[$unknownFixer])) { // Check if present as old renamed rule
5✔
789
                    $hasOldRule = true;
4✔
790
                    $message .= \sprintf(
4✔
791
                        '"%s" is renamed (did you mean "%s"?%s), ',
4✔
792
                        $unknownFixer,
4✔
793
                        $renamedRules[$unknownFixer]['new_name'],
4✔
794
                        isset($renamedRules[$unknownFixer]['config']) ? ' (note: use configuration "'.Utils::toString($renamedRules[$unknownFixer]['config']).'")' : ''
4✔
795
                    );
4✔
796
                } else { // Go to normal matcher if it is not a renamed rule
797
                    $matcher = new WordMatcher($availableFixers);
2✔
798
                    $alternative = $matcher->match($unknownFixer);
2✔
799
                    $message .= \sprintf(
2✔
800
                        '"%s"%s, ',
2✔
801
                        $unknownFixer,
2✔
802
                        null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)'
2✔
803
                    );
2✔
804
                }
805
            }
806

807
            $message = substr($message, 0, -2).'.';
5✔
808

809
            if ($hasOldRule) {
5✔
810
                $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✔
811
            }
812

813
            throw new InvalidConfigurationException($message);
5✔
814
        }
815

816
        foreach ($fixers as $fixer) {
10✔
817
            $fixerName = $fixer->getName();
10✔
818
            if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) {
10✔
819
                $successors = $fixer->getSuccessorsNames();
3✔
820
                $messageEnd = [] === $successors
3✔
821
                    ? \sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1)
×
822
                    : \sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors)));
3✔
823

824
                Utils::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}"));
3✔
825
            }
826
        }
827
    }
828

829
    /**
830
     * Apply path on config instance.
831
     *
832
     * @return iterable<\SplFileInfo>
833
     */
834
    private function resolveFinder(): iterable
835
    {
836
        $this->configFinderIsOverridden = false;
31✔
837

838
        if ($this->isStdIn()) {
31✔
839
            return new \ArrayIterator([new StdinFileInfo()]);
×
840
        }
841

842
        $modes = [self::PATH_MODE_OVERRIDE, self::PATH_MODE_INTERSECTION];
31✔
843

844
        if (!\in_array(
31✔
845
            $this->options['path-mode'],
31✔
846
            $modes,
31✔
847
            true
31✔
848
        )) {
31✔
849
            throw new InvalidConfigurationException(\sprintf(
×
850
                'The path-mode "%s" is not defined, supported are %s.',
×
851
                $this->options['path-mode'],
×
852
                Utils::naturalLanguageJoin($modes)
×
853
            ));
×
854
        }
855

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

858
        $paths = array_map(
31✔
859
            static fn (string $path) => realpath($path),
31✔
860
            $this->getPath()
31✔
861
        );
31✔
862

863
        if (0 === \count($paths)) {
26✔
864
            if ($isIntersectionPathMode) {
5✔
865
                return new \ArrayIterator([]);
1✔
866
            }
867

868
            return $this->iterableToTraversable($this->getConfig()->getFinder());
4✔
869
        }
870

871
        $pathsByType = [
21✔
872
            'file' => [],
21✔
873
            'dir' => [],
21✔
874
        ];
21✔
875

876
        foreach ($paths as $path) {
21✔
877
            if (is_file($path)) {
21✔
878
                $pathsByType['file'][] = $path;
11✔
879
            } else {
880
                $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR;
12✔
881
            }
882
        }
883

884
        $nestedFinder = null;
21✔
885
        $currentFinder = $this->iterableToTraversable($this->getConfig()->getFinder());
21✔
886

887
        try {
888
            $nestedFinder = $currentFinder instanceof \IteratorAggregate ? $currentFinder->getIterator() : $currentFinder;
21✔
889
        } catch (\Exception $e) {
4✔
890
        }
891

892
        if ($isIntersectionPathMode) {
21✔
893
            if (null === $nestedFinder) {
11✔
894
                throw new InvalidConfigurationException(
×
895
                    'Cannot create intersection with not-fully defined Finder in configuration file.'
×
896
                );
×
897
            }
898

899
            return new \CallbackFilterIterator(
11✔
900
                new \IteratorIterator($nestedFinder),
11✔
901
                static function (\SplFileInfo $current) use ($pathsByType): bool {
11✔
902
                    $currentRealPath = $current->getRealPath();
10✔
903

904
                    if (\in_array($currentRealPath, $pathsByType['file'], true)) {
10✔
905
                        return true;
3✔
906
                    }
907

908
                    foreach ($pathsByType['dir'] as $path) {
10✔
909
                        if (str_starts_with($currentRealPath, $path)) {
5✔
910
                            return true;
4✔
911
                        }
912
                    }
913

914
                    return false;
10✔
915
                }
11✔
916
            );
11✔
917
        }
918

919
        if (null !== $this->getConfigFile() && null !== $nestedFinder) {
10✔
920
            $this->configFinderIsOverridden = true;
3✔
921
        }
922

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

928
        return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']);
6✔
929
    }
930

931
    /**
932
     * Set option that will be resolved.
933
     *
934
     * @param mixed $value
935
     */
936
    private function setOption(string $name, $value): void
937
    {
938
        if (!\array_key_exists($name, $this->options)) {
102✔
939
            throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name));
1✔
940
        }
941

942
        $this->options[$name] = $value;
101✔
943
    }
944

945
    /**
946
     * @param key-of<_Options> $optionName
947
     */
948
    private function resolveOptionBooleanValue(string $optionName): bool
949
    {
950
        $value = $this->options[$optionName];
12✔
951

952
        if ('yes' === $value) {
12✔
953
            return true;
6✔
954
        }
955

956
        if ('no' === $value) {
7✔
957
            return false;
6✔
958
        }
959

960
        throw new InvalidConfigurationException(\sprintf('Expected "yes" or "no" for option "%s", got "%s".', $optionName, \is_object($value) ? \get_class($value) : (\is_scalar($value) ? $value : \gettype($value))));
1✔
961
    }
962

963
    private static function separatedContextLessInclude(string $path): ConfigInterface
964
    {
965
        $config = include $path;
20✔
966

967
        // verify that the config has an instance of Config
968
        if (!$config instanceof ConfigInterface) {
20✔
969
            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✔
970
        }
971

972
        return $config;
19✔
973
    }
974

975
    private function isCachingAllowedForRuntime(): bool
976
    {
977
        return $this->toolInfo->isInstalledAsPhar()
14✔
978
            || $this->toolInfo->isInstalledByComposer()
14✔
979
            || $this->toolInfo->isRunInsideDocker()
14✔
980
            || filter_var(getenv('PHP_CS_FIXER_ENFORCE_CACHE'), FILTER_VALIDATE_BOOL);
14✔
981
    }
982
}
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

© 2025 Coveralls, Inc