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

keradus / PHP-CS-Fixer / 17642215709

11 Sep 2025 10:50AM UTC coverage: 94.689% (+0.003%) from 94.686%
17642215709

push

github

keradus
Merge remote-tracking branch 'upstream/master' into __modifier_keywords

10 of 10 new or added lines in 2 files covered. (100.0%)

77 existing lines in 10 files now uncovered.

28421 of 30015 relevant lines covered (94.69%)

45.51 hits per line

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

90.22
/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\Future;
37
use PhpCsFixer\Linter\Linter;
38
use PhpCsFixer\Linter\LinterInterface;
39
use PhpCsFixer\ParallelAwareConfigInterface;
40
use PhpCsFixer\RuleSet\RuleSet;
41
use PhpCsFixer\RuleSet\RuleSetInterface;
42
use PhpCsFixer\Runner\Parallel\ParallelConfig;
43
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
44
use PhpCsFixer\StdinFileInfo;
45
use PhpCsFixer\ToolInfoInterface;
46
use PhpCsFixer\UnsupportedPhpVersionAllowedConfigInterface;
47
use PhpCsFixer\Utils;
48
use PhpCsFixer\WhitespacesFixerConfig;
49
use PhpCsFixer\WordMatcher;
50
use Symfony\Component\Filesystem\Filesystem;
51
use Symfony\Component\Finder\Finder as SymfonyFinder;
52

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

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

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

103
    private ?bool $allowRisky = null;
104

105
    private ?ConfigInterface $config = null;
106

107
    private ?string $configFile = null;
108

109
    private string $cwd;
110

111
    private ConfigInterface $defaultConfig;
112

113
    private ?ReporterInterface $reporter = null;
114

115
    private ?bool $isStdIn = null;
116

117
    private ?bool $isDryRun = null;
118

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

124
    private ?bool $configFinderIsOverridden = null;
125

126
    private ToolInfoInterface $toolInfo;
127

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

149
    private ?string $cacheFile = null;
150

151
    private ?CacheManagerInterface $cacheManager = null;
152

153
    private ?DifferInterface $differ = null;
154

155
    private ?Directory $directory = null;
156

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

162
    private ?string $format = null;
163

164
    private ?Linter $linter = null;
165

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

171
    /**
172
     * @var null|ProgressOutputType::*
173
     */
174
    private $progress;
175

176
    private ?RuleSet $ruleSet = null;
177

178
    private ?bool $usingCache = null;
179

180
    private ?bool $isUnsupportedPhpVersionAllowed = null;
181

182
    private ?FixerFactory $fixerFactory = null;
183

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

197
        foreach ($options as $name => $value) {
126✔
198
            $this->setOption($name, $value);
102✔
199
        }
200
    }
201

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

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

216
        return $this->cacheFile;
6✔
217
    }
218

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

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

242
        return $this->cacheManager;
1✔
243
    }
244

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

253
                $configFileBasename = basename($configFile);
20✔
254

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

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

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

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

275
                break;
19✔
276
            }
277

278
            if (null === $this->config) {
77✔
279
                $this->config = $this->defaultConfig;
58✔
280
            }
281
        }
282

283
        return $this->config;
77✔
284
    }
285

286
    public function getParallelConfig(): ParallelConfig
287
    {
288
        $config = $this->getConfig();
3✔
289

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

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

301
        return $this->configFile;
19✔
302
    }
303

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

310
        return $this->differ;
4✔
311
    }
312

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

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

328
            $this->directory = new Directory($absolutePath);
4✔
329
        }
330

331
        return $this->directory;
4✔
332
    }
333

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

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

355
                if (\count($riskyFixers) > 0) {
3✔
UNCOV
356
                    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)));
×
357
                }
358
            }
359
        }
360

361
        return $this->fixers;
5✔
362
    }
363

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

370
        return $this->linter;
1✔
371
    }
372

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

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

391
                        if ('' === $path) {
46✔
392
                            throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\".");
6✔
393
                        }
394

395
                        $absolutePath = $filesystem->isAbsolutePath($path)
42✔
396
                            ? $path
37✔
397
                            : $cwd.\DIRECTORY_SEPARATOR.$path;
5✔
398

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

406
                        return $absolutePath;
37✔
407
                    },
93✔
408
                    $this->options['path']
93✔
409
                );
93✔
410
            }
411
        }
412

413
        return $this->path;
82✔
414
    }
415

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

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

439
                $this->progress = $progressType;
10✔
440
            } else {
441
                $this->progress = ProgressOutputType::NONE;
2✔
442
            }
443
        }
444

445
        return $this->progress;
12✔
446
    }
447

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

454
            $format = $this->resolveFormat();
8✔
455

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

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

466
        return $this->reporter;
7✔
467
    }
468

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

479
        return $this->allowRisky;
17✔
480
    }
481

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

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

502
        $this->usingCache = $this->usingCache && $this->isCachingAllowedForRuntime();
22✔
503

504
        return $this->usingCache;
22✔
505
    }
506

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

UNCOV
520
        return $this->isUnsupportedPhpVersionAllowed;
×
521
    }
522

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

532
        return $this->finder;
26✔
533
    }
534

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

549
        return $this->isDryRun;
4✔
550
    }
551

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

557
    public function configFinderIsOverridden(): bool
558
    {
559
        if (null === $this->configFinderIsOverridden) {
7✔
560
            $this->resolveFinder();
7✔
561
        }
562

563
        return $this->configFinderIsOverridden;
7✔
564
    }
565

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

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

582
            return [$configFile];
11✔
583
        }
584

585
        $path = $this->getPath();
68✔
586

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

599
        $candidates = [
67✔
600
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
67✔
601
            $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
67✔
602

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

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

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

616
            $this->deprecatedNestedConfigDir = $configDir;
22✔
617
        }
618

619
        return $candidates;
67✔
620
    }
621

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

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

632
        return $this->fixerFactory;
15✔
633
    }
634

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

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

645
            $this->format = $parts[0];
19✔
646

647
            if ('@auto' === $this->format) {
19✔
648
                $this->format = $parts[1] ?? 'txt';
3✔
649

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

656
        return $this->format;
19✔
657
    }
658

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

665
            $this->ruleSet = new RuleSet($rules);
10✔
666
        }
667

668
        return $this->ruleSet;
10✔
669
    }
670

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

677
        return $this->isStdIn;
86✔
678
    }
679

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

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

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

706
        if (str_starts_with($rules, '{')) {
8✔
707
            try {
708
                return json_decode($rules, true, 512, \JSON_THROW_ON_ERROR);
×
709
            } catch (\JsonException $e) {
×
UNCOV
710
                throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', $e->getMessage()));
×
711
            }
712
        }
713

714
        $rules = [];
8✔
715

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

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

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

730
        return $rules;
8✔
731
    }
732

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1005
        return $config;
19✔
1006
    }
1007

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