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

keradus / PHP-CS-Fixer / 25961188992

15 May 2026 03:27PM UTC coverage: 93.797% (+0.7%) from 93.053%
25961188992

push

github

web-flow
fix: `MultilinePromotedPropertiesFixer` - fix for `new` in initializers (#9619)

2 of 2 new or added lines in 1 file covered. (100.0%)

49 existing lines in 7 files now uncovered.

29908 of 31886 relevant lines covered (93.8%)

51.7 hits per line

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

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

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

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

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

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

111
    private ?bool $allowRisky = null;
112

113
    private ?ConfigInterface $config = null;
114

115
    private ?string $configFile = null;
116

117
    private string $cwd;
118

119
    private ConfigInterface $defaultConfig;
120

121
    private ?ReporterInterface $reporter = null;
122

123
    private ?bool $isStdIn = null;
124

125
    private ?bool $isDryRun = null;
126

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

132
    private ?bool $configFinderIsOverridden = null;
133

134
    private ?bool $configRulesAreOverridden = null;
135

136
    private ToolInfoInterface $toolInfo;
137

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

159
    private ?string $cacheFile = null;
160

161
    private ?CacheManagerInterface $cacheManager = null;
162

163
    private ?DifferInterface $differ = null;
164

165
    private ?Directory $directory = null;
166

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

172
    private ?string $format = null;
173

174
    private ?Linter $linter = null;
175

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

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

186
    private ?RuleSet $ruleSet = null;
187

188
    private ?bool $usingCache = null;
189

190
    private ?bool $isUnsupportedPhpVersionAllowed = null;
191

192
    private ?RuleCustomisationPolicyInterface $ruleCustomisationPolicy = null;
193

194
    private ?FixerFactory $fixerFactory = null;
195

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

209
        foreach ($options as $name => $value) {
133✔
210
            $this->setOption($name, $value);
108✔
211
        }
212
    }
213

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

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

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

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

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

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

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

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

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

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

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

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

288
                break;
19✔
289
            }
290

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

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

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

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

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

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

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

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

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

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

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

340
        return $this->directory;
5✔
341
    }
342

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

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

364
                if (\count($riskyFixers) > 0) {
3✔
UNCOV
365
                    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)));
×
366
                }
367
            }
368
        }
369

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

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

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

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

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

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

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

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

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

422
        return $this->path;
79✔
423
    }
424

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

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

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

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

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

463
            $format = $this->resolveFormat();
13✔
464

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

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

475
        return $this->reporter;
12✔
476
    }
477

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

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

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

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

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

513
        return $this->usingCache;
18✔
514
    }
515

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

UNCOV
529
        return $this->isUnsupportedPhpVersionAllowed;
×
530
    }
531

532
    public function getRuleCustomisationPolicy(): RuleCustomisationPolicyInterface
533
    {
534
        if (null === $this->ruleCustomisationPolicy) {
×
535
            $config = $this->getConfig();
×
536
            if ($config instanceof RuleCustomisationPolicyAwareConfigInterface) {
×
UNCOV
537
                $this->ruleCustomisationPolicy = $config->getRuleCustomisationPolicy();
×
538
            }
UNCOV
539
            $this->ruleCustomisationPolicy ??= new NullRuleCustomisationPolicy();
×
540
        }
541

UNCOV
542
        return $this->ruleCustomisationPolicy;
×
543
    }
544

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

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

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

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

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

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

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

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

UNCOV
594
        return $this->configRulesAreOverridden;
×
595
    }
596

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

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

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

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

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

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

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

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

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

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

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

654
        return $candidates;
62✔
655
    }
656

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

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

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

670
    private function resolveFormat(): string
671
    {
672
        if (null === $this->format) {
24✔
673
            $agentDetector = new AgentDetector\Detector();
24✔
674

675
            // When an AI agent is running, we ignore the format configuration entirely and use JSON format.
676
            if ($agentDetector->isAgentPresent(getenv())) {
24✔
677
                $this->format = 'json';
5✔
678

679
                return $this->format;
5✔
680
            }
681

682
            $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat();
19✔
683
            $parts = explode(',', $formatCandidate);
19✔
684

685
            if (\count($parts) > 2) {
19✔
UNCOV
686
                throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate));
×
687
            }
688

689
            $this->format = $parts[0];
19✔
690

691
            if ('@auto' === $this->format) {
19✔
692
                $this->format = $parts[1] ?? 'txt';
3✔
693

694
                if (filter_var(getenv('GITLAB_CI'), \FILTER_VALIDATE_BOOL)) {
3✔
695
                    $this->format = 'gitlab';
1✔
696
                }
697
            }
698
        }
699

700
        return $this->format;
19✔
701
    }
702

703
    private function getRuleSet(): RuleSetInterface
704
    {
705
        if (null === $this->ruleSet) {
16✔
706
            $rules = $this->parseRules();
16✔
707
            $this->validateRules($rules);
15✔
708

709
            $this->ruleSet = new RuleSet($rules);
10✔
710
        }
711

712
        return $this->ruleSet;
10✔
713
    }
714

715
    private function isStdIn(): bool
716
    {
717
        if (null === $this->isStdIn) {
83✔
718
            $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0];
83✔
719
        }
720

721
        return $this->isStdIn;
83✔
722
    }
723

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

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

734
            return $this->getConfig()->getRules();
7✔
735
        }
736

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

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

750
        $rules = [];
8✔
751

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

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

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

766
        $this->configRulesAreOverridden = true;
8✔
767

768
        return $rules;
8✔
769
    }
770

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

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

790
            $ruleSet[$key] = true;
15✔
791
        }
792

793
        $ruleSet = new RuleSet($ruleSet);
15✔
794

795
        $configuredFixers = array_keys($ruleSet->getRules());
15✔
796

797
        $fixers = $this->createFixerFactory()->getFixers();
15✔
798

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

801
        $unknownFixers = array_diff($configuredFixers, $availableFixers);
15✔
802

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

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

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

884
            $message = substr($message, 0, -2).'.';
5✔
885

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

890
            throw new InvalidConfigurationException($message);
5✔
891
        }
892

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

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

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

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

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

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

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

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

943
            return $this->getConfig()->getFinder();
4✔
944
        }
945

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

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

959
        $nestedFinder = null;
21✔
960
        $currentFinder = $this->getConfig()->getFinder();
21✔
961

962
        try {
963
            $nestedFinder = $currentFinder instanceof \IteratorAggregate
21✔
964
                ? $currentFinder->getIterator()
21✔
965
                : (
21✔
966
                    $currentFinder instanceof \Traversable
×
967
                        ? $currentFinder
×
UNCOV
968
                        : new \ArrayIterator($currentFinder)
×
969
                );
21✔
970
        } catch (\Exception $e) {
4✔
971
        }
972

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

980
            return new \CallbackFilterIterator(
11✔
981
                new \IteratorIterator($nestedFinder),
11✔
982
                static function (\SplFileInfo $current) use ($pathsByType): bool {
11✔
983
                    $currentRealPath = $current->getRealPath();
10✔
984

985
                    if (\in_array($currentRealPath, $pathsByType['file'], true)) {
10✔
986
                        return true;
3✔
987
                    }
988

989
                    foreach ($pathsByType['dir'] as $path) {
10✔
990
                        if (str_starts_with($currentRealPath, $path)) {
5✔
991
                            return true;
4✔
992
                        }
993
                    }
994

995
                    return false;
10✔
996
                },
11✔
997
            );
11✔
998
        }
999

1000
        if (null !== $this->getConfigFile() && null !== $nestedFinder) {
10✔
1001
            $this->configFinderIsOverridden = true;
3✔
1002
        }
1003

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

1009
        return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']);
6✔
1010
    }
1011

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

1023
        $this->options[$name] = $value;
107✔
1024
    }
1025

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

1033
        if (self::BOOL_YES === $value) {
12✔
1034
            return true;
6✔
1035
        }
1036

1037
        if (self::BOOL_NO === $value) {
7✔
1038
            return false;
6✔
1039
        }
1040

1041
        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✔
1042
    }
1043

1044
    private static function separatedContextLessInclude(string $path): ConfigInterface
1045
    {
1046
        $config = include $path;
20✔
1047

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

1053
        return $config;
19✔
1054
    }
1055

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