123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524 |
- <?php
- declare(strict_types=1);
- /*
- * This file is part of PHP CS Fixer.
- *
- * (c) Fabien Potencier <fabien@symfony.com>
- * Dariusz Rumiński <dariusz.ruminski@gmail.com>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace PhpCsFixer\Tests\Console;
- use PhpCsFixer\AbstractFixer;
- use PhpCsFixer\Cache\NullCacheManager;
- use PhpCsFixer\Config;
- use PhpCsFixer\ConfigInterface;
- use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
- use PhpCsFixer\Console\Command\FixCommand;
- use PhpCsFixer\Console\ConfigurationResolver;
- use PhpCsFixer\Console\Output\Progress\ProgressOutputType;
- use PhpCsFixer\Differ\NullDiffer;
- use PhpCsFixer\Differ\UnifiedDiffer;
- use PhpCsFixer\Finder;
- use PhpCsFixer\Fixer\ConfigurableFixerInterface;
- use PhpCsFixer\Fixer\ConfigurableFixerTrait;
- use PhpCsFixer\Fixer\DeprecatedFixerInterface;
- use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
- use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
- use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
- use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
- use PhpCsFixer\Runner\Parallel\ParallelConfig;
- use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
- use PhpCsFixer\Tests\TestCase;
- use PhpCsFixer\Tokenizer\Tokens;
- use PhpCsFixer\ToolInfoInterface;
- use PhpCsFixer\Utils;
- use Symfony\Component\Console\Output\OutputInterface;
- /**
- * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
- * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
- *
- * @internal
- *
- * @covers \PhpCsFixer\Console\ConfigurationResolver
- */
- final class ConfigurationResolverTest extends TestCase
- {
- public function testResolveParallelConfig(): void
- {
- $parallelConfig = new ParallelConfig();
- $config = (new Config())->setParallelConfig($parallelConfig);
- $resolver = $this->createConfigurationResolver([], $config);
- self::assertSame($parallelConfig, $resolver->getParallelConfig());
- }
- public function testDefaultParallelConfigFallbacksToSequential(): void
- {
- $parallelConfig = $this->createConfigurationResolver([])->getParallelConfig();
- $defaultParallelConfig = ParallelConfigFactory::sequential();
- self::assertSame($defaultParallelConfig->getMaxProcesses(), $parallelConfig->getMaxProcesses());
- self::assertSame($defaultParallelConfig->getFilesPerProcess(), $parallelConfig->getFilesPerProcess());
- self::assertSame($defaultParallelConfig->getProcessTimeout(), $parallelConfig->getProcessTimeout());
- }
- public function testCliSequentialOptionOverridesParallelConfig(): void
- {
- $config = (new Config())->setParallelConfig(new ParallelConfig(10));
- $resolver = $this->createConfigurationResolver(['sequential' => true], $config);
- self::assertSame(1, $resolver->getParallelConfig()->getMaxProcesses());
- }
- public function testSetOptionWithUndefinedOption(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessageMatches('/^Unknown option name: "foo"\.$/');
- $this->createConfigurationResolver(['foo' => 'bar']);
- }
- public function testResolveProgressWithPositiveConfigAndPositiveOption(): void
- {
- $config = new Config();
- $config->setHideProgress(true);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
- ], $config);
- self::assertSame('none', $resolver->getProgressType());
- }
- public function testResolveProgressWithPositiveConfigAndNegativeOption(): void
- {
- $config = new Config();
- $config->setHideProgress(true);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_NORMAL,
- ], $config);
- self::assertSame('none', $resolver->getProgressType());
- }
- public function testResolveProgressWithNegativeConfigAndPositiveOption(): void
- {
- $config = new Config();
- $config->setHideProgress(false);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
- ], $config);
- self::assertSame('bar', $resolver->getProgressType());
- }
- public function testResolveProgressWithNegativeConfigAndNegativeOption(): void
- {
- $config = new Config();
- $config->setHideProgress(false);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_NORMAL,
- ], $config);
- self::assertSame('bar', $resolver->getProgressType());
- }
- /**
- * @dataProvider provideProgressTypeCases
- */
- public function testResolveProgressWithPositiveConfigAndExplicitProgress(string $progressType): void
- {
- $config = new Config();
- $config->setHideProgress(true);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
- 'show-progress' => $progressType,
- ], $config);
- self::assertSame($progressType, $resolver->getProgressType());
- }
- /**
- * @dataProvider provideProgressTypeCases
- */
- public function testResolveProgressWithNegativeConfigAndExplicitProgress(string $progressType): void
- {
- $config = new Config();
- $config->setHideProgress(false);
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
- 'show-progress' => $progressType,
- ], $config);
- self::assertSame($progressType, $resolver->getProgressType());
- }
- /**
- * @return iterable<string, array{0: ProgressOutputType::*}>
- */
- public static function provideProgressTypeCases(): iterable
- {
- foreach (ProgressOutputType::all() as $outputType) {
- yield $outputType => [$outputType];
- }
- }
- public function testResolveProgressWithInvalidExplicitProgress(): void
- {
- $resolver = $this->createConfigurationResolver([
- 'format' => 'txt',
- 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
- 'show-progress' => 'foo',
- ]);
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The progress type "foo" is not defined, supported are "bar", "dots" and "none".');
- $resolver->getProgressType();
- }
- public function testResolveConfigFileDefault(): void
- {
- $resolver = $this->createConfigurationResolver([]);
- self::assertNull($resolver->getConfigFile());
- }
- public function testResolveConfigFileByPathOfFile(): void
- {
- $dir = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_1';
- $resolver = $this->createConfigurationResolver(['path' => [$dir.\DIRECTORY_SEPARATOR.'foo.php']]);
- self::assertSame($dir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', $resolver->getConfigFile());
- self::assertInstanceOf(\Test1Config::class, $resolver->getConfig()); // @phpstan-ignore-line to avoid `Class Test1Config not found.`
- }
- public function testResolveConfigFileSpecified(): void
- {
- $file = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_4/my.php-cs-fixer.php';
- $resolver = $this->createConfigurationResolver(['config' => $file]);
- self::assertSame($file, $resolver->getConfigFile());
- self::assertInstanceOf(\Test4Config::class, $resolver->getConfig()); // @phpstan-ignore-line to avoid `Class Test4Config not found.`
- }
- /**
- * @dataProvider provideResolveConfigFileChooseFileCases
- *
- * @param class-string<ConfigInterface> $expectedClass
- */
- public function testResolveConfigFileChooseFile(string $expectedFile, string $expectedClass, string $path, ?string $cwdPath = null): void
- {
- $resolver = $this->createConfigurationResolver(
- ['path' => [$path]],
- null,
- $cwdPath ?? ''
- );
- self::assertSame($expectedFile, $resolver->getConfigFile());
- self::assertInstanceOf($expectedClass, $resolver->getConfig());
- }
- /**
- * @return iterable<array{0: string, 1: string, 2: string, 3?: string}>
- */
- public static function provideResolveConfigFileChooseFileCases(): iterable
- {
- $dirBase = self::getFixtureDir();
- yield [
- $dirBase.'case_1'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
- 'Test1Config',
- $dirBase.'case_1',
- ];
- yield [
- $dirBase.'case_2'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
- 'Test2Config',
- $dirBase.'case_2',
- ];
- yield [
- $dirBase.'case_3'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php',
- 'Test3Config',
- $dirBase.'case_3',
- ];
- yield [
- $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
- 'Test6Config',
- $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir',
- $dirBase.'case_6',
- ];
- yield [
- $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php',
- 'Test6Config',
- $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir/empty_file.php',
- $dirBase.'case_6',
- ];
- }
- public function testResolveConfigFileChooseFileWithInvalidFile(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessageMatches(
- '#^The config file: ".+[\/\\\]Fixtures[\/\\\]ConfigurationResolverConfigFile[\/\\\]case_5[\/\\\]\.php-cs-fixer\.dist\.php" does not return a "PhpCsFixer\\\ConfigInterface" instance\. Got: "string"\.$#'
- );
- $dirBase = self::getFixtureDir();
- $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_5']]);
- $resolver->getConfig();
- }
- public function testResolveConfigFileChooseFileWithInvalidFormat(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessageMatches('/^The format "xls" is not defined, supported are "checkstyle", "gitlab", "json", "junit", "txt" and "xml"\.$/');
- $dirBase = self::getFixtureDir();
- $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_7']]);
- $resolver->getReporter();
- }
- public function testResolveConfigFileChooseFileWithPathArrayWithoutConfig(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessageMatches('/^For multiple paths config parameter is required\.$/');
- $dirBase = self::getFixtureDir();
- $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_1/.php-cs-fixer.dist.php', $dirBase.'case_1/foo.php']]);
- $resolver->getConfig();
- }
- public function testResolveConfigFileChooseFileWithPathArrayAndConfig(): void
- {
- $dirBase = self::getFixtureDir();
- $configFile = $dirBase.'case_1/.php-cs-fixer.dist.php';
- $resolver = $this->createConfigurationResolver([
- 'config' => $configFile,
- 'path' => [$configFile, $dirBase.'case_1/foo.php'],
- ]);
- self::assertSame($configFile, $resolver->getConfigFile());
- }
- /**
- * @param array<int, string> $paths
- * @param array<int, string> $expectedPaths
- *
- * @dataProvider provideResolvePathCases
- */
- public function testResolvePath(array $paths, string $cwd, array $expectedPaths): void
- {
- $resolver = $this->createConfigurationResolver(
- ['path' => $paths],
- null,
- $cwd
- );
- self::assertSame($expectedPaths, $resolver->getPath());
- }
- public static function provideResolvePathCases(): iterable
- {
- yield [
- ['Command'],
- __DIR__,
- [__DIR__.\DIRECTORY_SEPARATOR.'Command'],
- ];
- yield [
- [basename(__DIR__)],
- \dirname(__DIR__),
- [__DIR__],
- ];
- yield [
- [' Command'],
- __DIR__,
- [__DIR__.\DIRECTORY_SEPARATOR.'Command'],
- ];
- yield [
- ['Command '],
- __DIR__,
- [__DIR__.\DIRECTORY_SEPARATOR.'Command'],
- ];
- }
- /**
- * @param list<string> $paths
- *
- * @dataProvider provideRejectInvalidPathCases
- */
- public function testRejectInvalidPath(array $paths, string $expectedMessage): void
- {
- $resolver = $this->createConfigurationResolver(
- ['path' => $paths],
- null,
- \dirname(__DIR__)
- );
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage($expectedMessage);
- $resolver->getPath();
- }
- public static function provideRejectInvalidPathCases(): iterable
- {
- yield [
- [''],
- 'Invalid path: "".',
- ];
- yield [
- [__DIR__, ''],
- 'Invalid path: "".',
- ];
- yield [
- ['', __DIR__],
- 'Invalid path: "".',
- ];
- yield [
- [' '],
- 'Invalid path: " ".',
- ];
- yield [
- [__DIR__, ' '],
- 'Invalid path: " ".',
- ];
- yield [
- [' ', __DIR__],
- 'Invalid path: " ".',
- ];
- }
- public function testResolvePathWithFileThatIsExcludedDirectlyOverridePathMode(): void
- {
- $config = new Config();
- $config->getFinder()
- ->in(__DIR__)
- ->notPath(basename(__FILE__))
- ;
- $resolver = $this->createConfigurationResolver(
- ['path' => [__FILE__]],
- $config
- );
- self::assertCount(1, $resolver->getFinder());
- }
- public function testResolvePathWithFileThatIsExcludedDirectlyIntersectionPathMode(): void
- {
- $config = new Config();
- $config->getFinder()
- ->in(__DIR__)
- ->notPath(basename(__FILE__))
- ;
- $resolver = $this->createConfigurationResolver([
- 'path' => [__FILE__],
- 'path-mode' => 'intersection',
- ], $config);
- self::assertCount(0, $resolver->getFinder());
- }
- public function testResolvePathWithFileThatIsExcludedByDirOverridePathMode(): void
- {
- $dir = \dirname(__DIR__);
- $config = new Config();
- $config->getFinder()
- ->in($dir)
- ->exclude(basename(__DIR__))
- ;
- $resolver = $this->createConfigurationResolver(
- ['path' => [__FILE__]],
- $config
- );
- self::assertCount(1, $resolver->getFinder());
- }
- public function testResolvePathWithFileThatIsExcludedByDirIntersectionPathMode(): void
- {
- $dir = \dirname(__DIR__);
- $config = new Config();
- $config->getFinder()
- ->in($dir)
- ->exclude(basename(__DIR__))
- ;
- $resolver = $this->createConfigurationResolver([
- 'path-mode' => 'intersection',
- 'path' => [__FILE__],
- ], $config);
- self::assertCount(0, $resolver->getFinder());
- }
- public function testResolvePathWithFileThatIsNotExcluded(): void
- {
- $dir = __DIR__;
- $config = new Config();
- $config->getFinder()
- ->in($dir)
- ->notPath('foo-'.basename(__FILE__))
- ;
- $resolver = $this->createConfigurationResolver(
- ['path' => [__FILE__]],
- $config
- );
- self::assertCount(1, $resolver->getFinder());
- }
- /**
- * @param \Exception|list<string> $expected
- * @param list<string> $path
- *
- * @dataProvider provideResolveIntersectionOfPathsCases
- */
- public function testResolveIntersectionOfPaths($expected, ?Finder $configFinder, array $path, string $pathMode, ?string $configOption = null): void
- {
- if ($expected instanceof \Exception) {
- $this->expectException(\get_class($expected));
- }
- if (null !== $configFinder) {
- $config = new Config();
- $config->setFinder($configFinder);
- } else {
- $config = null;
- }
- $resolver = $this->createConfigurationResolver([
- 'config' => $configOption,
- 'path' => $path,
- 'path-mode' => $pathMode,
- ], $config);
- $intersectionItems = array_map(
- static fn (\SplFileInfo $file): string => $file->getRealPath(),
- iterator_to_array($resolver->getFinder(), false)
- );
- sort($expected);
- sort($intersectionItems);
- self::assertSame($expected, $intersectionItems);
- }
- public static function provideResolveIntersectionOfPathsCases(): iterable
- {
- $dir = __DIR__.'/../Fixtures/ConfigurationResolverPathsIntersection';
- $cb = static fn (array $items): array => array_map(
- static fn (string $item): string => realpath($dir.'/'.$item),
- $items
- );
- yield 'no path at all' => [
- new \LogicException(),
- Finder::create(),
- [],
- 'override',
- ];
- yield 'configured only by finder' => [
- // don't override if the argument is empty
- $cb(['a1.php', 'a2.php', 'b/b1.php', 'b/b2.php', 'b_b/b_b1.php', 'c/c1.php', 'c/d/cd1.php', 'd/d1.php', 'd/d2.php', 'd/e/de1.php', 'd/f/df1.php']),
- Finder::create()
- ->in($dir),
- [],
- 'override',
- ];
- yield 'configured only by argument' => [
- $cb(['a1.php', 'a2.php', 'b/b1.php', 'b/b2.php', 'b_b/b_b1.php', 'c/c1.php', 'c/d/cd1.php', 'd/d1.php', 'd/d2.php', 'd/e/de1.php', 'd/f/df1.php']),
- Finder::create(),
- [$dir],
- 'override',
- ];
- yield 'configured by finder, intersected with empty argument' => [
- [],
- Finder::create()
- ->in($dir),
- [],
- 'intersection',
- ];
- yield 'configured by finder, intersected with dir' => [
- $cb(['c/c1.php', 'c/d/cd1.php']),
- Finder::create()
- ->in($dir),
- [$dir.'/c'],
- 'intersection',
- ];
- yield 'configured by finder, intersected with file' => [
- $cb(['c/c1.php']),
- Finder::create()
- ->in($dir),
- [$dir.'/c/c1.php'],
- 'intersection',
- ];
- yield 'finder points to one dir while argument to another, not connected' => [
- [],
- Finder::create()
- ->in($dir.'/b'),
- [$dir.'/c'],
- 'intersection',
- ];
- yield 'finder with excluded dir, intersected with excluded file' => [
- [],
- Finder::create()
- ->in($dir)
- ->exclude('c'),
- [$dir.'/c/d/cd1.php'],
- 'intersection',
- ];
- yield 'finder with excluded dir, intersected with dir containing excluded one' => [
- $cb(['c/c1.php']),
- Finder::create()
- ->in($dir)
- ->exclude('c/d'),
- [$dir.'/c'],
- 'intersection',
- ];
- yield 'finder with excluded file, intersected with dir containing excluded one' => [
- $cb(['c/d/cd1.php']),
- Finder::create()
- ->in($dir)
- ->notPath('c/c1.php'),
- [$dir.'/c'],
- 'intersection',
- ];
- yield 'configured by finder, intersected with non-existing path' => [
- new \LogicException(),
- Finder::create()
- ->in($dir),
- ['non_existing_dir'],
- 'intersection',
- ];
- yield 'configured by config file, overridden by multiple files' => [
- $cb(['d/d1.php', 'd/d2.php']),
- null,
- [$dir.'/d/d1.php', $dir.'/d/d2.php'],
- 'override',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, intersected with multiple files' => [
- $cb(['d/d1.php', 'd/d2.php']),
- null,
- [$dir.'/d/d1.php', $dir.'/d/d2.php'],
- 'intersection',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, overridden by non-existing dir' => [
- new \LogicException(),
- null,
- [$dir.'/d/fff'],
- 'override',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, intersected with non-existing dir' => [
- new \LogicException(),
- null,
- [$dir.'/d/fff'],
- 'intersection',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, overridden by non-existing file' => [
- new \LogicException(),
- null,
- [$dir.'/d/fff.php'],
- 'override',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, intersected with non-existing file' => [
- new \LogicException(),
- null,
- [$dir.'/d/fff.php'],
- 'intersection',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, overridden by multiple files and dirs' => [
- $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']),
- null,
- [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'],
- 'override',
- $dir.'/d/.php-cs-fixer.php',
- ];
- yield 'configured by config file, intersected with multiple files and dirs' => [
- $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']),
- null,
- [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'],
- 'intersection',
- $dir.'/d/.php-cs-fixer.php',
- ];
- }
- /**
- * @param array<string, mixed> $options
- *
- * @dataProvider provideConfigFinderIsOverriddenCases
- */
- public function testConfigFinderIsOverridden(array $options, bool $expectedResult): void
- {
- $resolver = $this->createConfigurationResolver($options);
- self::assertSame($expectedResult, $resolver->configFinderIsOverridden());
- $resolver = $this->createConfigurationResolver($options);
- $resolver->getFinder();
- self::assertSame($expectedResult, $resolver->configFinderIsOverridden());
- }
- public static function provideConfigFinderIsOverriddenCases(): iterable
- {
- $root = __DIR__.'/../..';
- yield [
- [
- 'config' => $root.'/.php-cs-fixer.dist.php',
- ],
- false,
- ];
- yield [
- [
- 'config' => $root.'/.php-cs-fixer.dist.php',
- 'path' => [$root.'/src'],
- ],
- true,
- ];
- yield [
- [],
- false,
- ];
- yield [
- [
- 'path' => [$root.'/src'],
- ],
- false,
- ];
- yield [
- [
- 'config' => $root.'/.php-cs-fixer.dist.php',
- 'path' => [$root.'/src'],
- 'path-mode' => ConfigurationResolver::PATH_MODE_INTERSECTION,
- ],
- false,
- ];
- // scenario when loaded config is not setting custom finder
- yield [
- [
- 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.dist.php',
- 'path' => [$root.'/src'],
- ],
- false,
- ];
- // scenario when loaded config contains not fully defined finder
- yield [
- [
- 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_9/.php-cs-fixer.php',
- 'path' => [$root.'/src'],
- ],
- false,
- ];
- }
- public function testResolveIsDryRunViaStdIn(): void
- {
- $resolver = $this->createConfigurationResolver([
- 'dry-run' => false,
- 'path' => ['-'],
- ]);
- self::assertTrue($resolver->isDryRun());
- }
- public function testResolveIsDryRunViaNegativeOption(): void
- {
- $resolver = $this->createConfigurationResolver(['dry-run' => false]);
- self::assertFalse($resolver->isDryRun());
- }
- public function testResolveIsDryRunViaPositiveOption(): void
- {
- $resolver = $this->createConfigurationResolver(['dry-run' => true]);
- self::assertTrue($resolver->isDryRun());
- }
- /**
- * @dataProvider provideResolveBooleanOptionCases
- */
- public function testResolveUsingCacheWithConfigOption(bool $expected, bool $configValue, ?string $passed): void
- {
- $config = new Config();
- $config->setUsingCache($configValue);
- $resolver = $this->createConfigurationResolver(
- ['using-cache' => $passed],
- $config
- );
- self::assertSame($expected, $resolver->getUsingCache());
- }
- public function testResolveUsingCacheWithPositiveConfigAndNoOption(): void
- {
- $config = new Config();
- $config->setUsingCache(true);
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertTrue($resolver->getUsingCache());
- }
- public function testResolveUsingCacheWithNegativeConfigAndNoOption(): void
- {
- $config = new Config();
- $config->setUsingCache(false);
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertFalse($resolver->getUsingCache());
- }
- /**
- * @dataProvider provideResolveUsingCacheForRuntimesCases
- */
- public function testResolveUsingCacheForRuntimes(bool $cacheAllowed, bool $installedWithComposer, bool $asPhar, bool $inDocker): void
- {
- $config = new Config();
- $config->setUsingCache(true);
- $resolver = $this->createConfigurationResolver(
- [],
- $config,
- '',
- new class($installedWithComposer, $asPhar, $inDocker) implements ToolInfoInterface {
- private bool $installedWithComposer;
- private bool $asPhar;
- private bool $inDocker;
- public function __construct(bool $installedWithComposer, bool $asPhar, bool $inDocker)
- {
- $this->installedWithComposer = $installedWithComposer;
- $this->asPhar = $asPhar;
- $this->inDocker = $inDocker;
- }
- public function getComposerInstallationDetails(): array
- {
- throw new \BadMethodCallException();
- }
- public function getComposerVersion(): string
- {
- throw new \BadMethodCallException();
- }
- public function getVersion(): string
- {
- throw new \BadMethodCallException();
- }
- public function isInstalledAsPhar(): bool
- {
- return $this->asPhar;
- }
- public function isInstalledByComposer(): bool
- {
- return $this->installedWithComposer;
- }
- public function isRunInsideDocker(): bool
- {
- return $this->inDocker;
- }
- public function getPharDownloadUri(string $version): string
- {
- throw new \BadMethodCallException();
- }
- }
- );
- self::assertSame($cacheAllowed, $resolver->getUsingCache());
- }
- /**
- * @return iterable<array{0: bool, 1: bool, 2: bool, 3: bool}>
- */
- public static function provideResolveUsingCacheForRuntimesCases(): iterable
- {
- yield 'none of the allowed runtimes' => [false, false, false, false];
- yield 'composer installation' => [true, true, false, false];
- yield 'PHAR distribution' => [true, false, true, false];
- yield 'Docker runtime' => [true, false, false, true];
- }
- public function testResolveCacheFileWithoutConfigAndOption(): void
- {
- $config = new Config();
- $default = $config->getCacheFile();
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertSame($default, $resolver->getCacheFile());
- }
- public function testResolveCacheFileWithConfig(): void
- {
- $cacheFile = 'foo/bar.baz';
- $config = new Config();
- $config
- ->setUsingCache(false)
- ->setCacheFile($cacheFile)
- ;
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertNull($resolver->getCacheFile());
- $cacheManager = $resolver->getCacheManager();
- self::assertInstanceOf(NullCacheManager::class, $cacheManager);
- self::assertFalse($resolver->getLinter()->isAsync());
- }
- public function testResolveCacheFileWithOption(): void
- {
- $cacheFile = 'bar.baz';
- $config = new Config();
- $config->setCacheFile($cacheFile);
- $resolver = $this->createConfigurationResolver(
- ['cache-file' => $cacheFile],
- $config
- );
- self::assertSame($cacheFile, $resolver->getCacheFile());
- }
- public function testResolveCacheFileWithConfigAndOption(): void
- {
- $configCacheFile = 'foo/bar.baz';
- $optionCacheFile = 'bar.baz';
- $config = new Config();
- $config->setCacheFile($configCacheFile);
- $resolver = $this->createConfigurationResolver(
- ['cache-file' => $optionCacheFile],
- $config
- );
- self::assertSame($optionCacheFile, $resolver->getCacheFile());
- }
- /**
- * @dataProvider provideResolveBooleanOptionCases
- */
- public function testResolveAllowRiskyWithConfigOption(bool $expected, bool $configValue, ?string $passed): void
- {
- $config = new Config();
- $config->setRiskyAllowed($configValue);
- $resolver = $this->createConfigurationResolver(
- ['allow-risky' => $passed],
- $config
- );
- self::assertSame($expected, $resolver->getRiskyAllowed());
- }
- public function testResolveAllowRiskyWithNegativeConfigAndPositiveOption(): void
- {
- $config = new Config();
- $config->setRiskyAllowed(false);
- $resolver = $this->createConfigurationResolver(
- ['allow-risky' => 'yes'],
- $config
- );
- self::assertTrue($resolver->getRiskyAllowed());
- }
- public function testResolveAllowRiskyWithNegativeConfigAndNegativeOption(): void
- {
- $config = new Config();
- $config->setRiskyAllowed(false);
- $resolver = $this->createConfigurationResolver(
- ['allow-risky' => 'no'],
- $config
- );
- self::assertFalse($resolver->getRiskyAllowed());
- }
- public function testResolveAllowRiskyWithPositiveConfigAndNoOption(): void
- {
- $config = new Config();
- $config->setRiskyAllowed(true);
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertTrue($resolver->getRiskyAllowed());
- }
- public function testResolveAllowRiskyWithNegativeConfigAndNoOption(): void
- {
- $config = new Config();
- $config->setRiskyAllowed(false);
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertFalse($resolver->getRiskyAllowed());
- }
- public function testResolveRulesWithConfig(): void
- {
- $config = new Config();
- $config->setRules([
- 'statement_indentation' => true,
- 'strict_comparison' => false,
- ]);
- $resolver = $this->createConfigurationResolver(
- [],
- $config
- );
- self::assertSameRules(
- [
- 'statement_indentation' => true,
- ],
- $resolver->getRules()
- );
- }
- public function testResolveRulesWithOption(): void
- {
- $resolver = $this->createConfigurationResolver(['rules' => 'statement_indentation,-strict_comparison']);
- self::assertSameRules(
- [
- 'statement_indentation' => true,
- ],
- $resolver->getRules()
- );
- }
- /**
- * @param list<string> $rules
- *
- * @dataProvider provideResolveRenamedRulesWithUnknownRulesCases
- */
- public function testResolveRenamedRulesWithUnknownRules(string $expectedMessage, array $rules): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage($expectedMessage);
- $resolver = $this->createConfigurationResolver(['rules' => implode(',', $rules)]);
- $resolver->getRules();
- }
- public static function provideResolveRenamedRulesWithUnknownRulesCases(): iterable
- {
- yield 'with config' => [
- 'The rules contain unknown fixers: "blank_line_before_return" is renamed (did you mean "blank_line_before_statement"? (note: use configuration "[\'statements\' => [\'return\']]")).
- For more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless.',
- ['blank_line_before_return'],
- ];
- yield 'without config' => [
- 'The rules contain unknown fixers: "final_static_access" is renamed (did you mean "self_static_accessor"?).
- For more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless.',
- ['final_static_access'],
- ];
- yield [
- 'The rules contain unknown fixers: "hash_to_slash_comment" is renamed (did you mean "single_line_comment_style"? (note: use configuration "[\'comment_types\' => [\'hash\']]")).
- For more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless.',
- ['hash_to_slash_comment'],
- ];
- yield 'both renamed and unknown' => [
- 'The rules contain unknown fixers: "final_static_access" is renamed (did you mean "self_static_accessor"?), "binary_operator_space" (did you mean "binary_operator_spaces"?).
- For more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless.',
- ['final_static_access', 'binary_operator_space'],
- ];
- }
- public function testResolveRulesWithUnknownRules(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The rules contain unknown fixers: "bar", "binary_operator_space" (did you mean "binary_operator_spaces"?).');
- $resolver = $this->createConfigurationResolver(['rules' => 'statement_indentation,-bar,binary_operator_space']);
- $resolver->getRules();
- }
- public function testResolveRulesWithConfigAndOption(): void
- {
- $config = new Config();
- $config->setRules([
- 'statement_indentation' => true,
- 'strict_comparison' => false,
- ]);
- $resolver = $this->createConfigurationResolver(
- ['rules' => 'blank_line_before_statement'],
- $config
- );
- self::assertSameRules(
- [
- 'blank_line_before_statement' => true,
- ],
- $resolver->getRules()
- );
- }
- public function testResolveCommandLineInputOverridesDefault(): void
- {
- $command = new FixCommand($this->createToolInfoDouble());
- $definition = $command->getDefinition();
- $arguments = $definition->getArguments();
- self::assertCount(1, $arguments, 'Expected one argument, possibly test needs updating.');
- self::assertArrayHasKey('path', $arguments);
- $options = $definition->getOptions();
- self::assertSame(
- ['path-mode', 'allow-risky', 'config', 'dry-run', 'rules', 'using-cache', 'cache-file', 'diff', 'format', 'stop-on-violation', 'show-progress', 'sequential'],
- array_keys($options),
- 'Expected options mismatch, possibly test needs updating.'
- );
- $resolver = $this->createConfigurationResolver([
- 'path-mode' => 'intersection',
- 'allow-risky' => 'yes',
- 'config' => null,
- 'dry-run' => true,
- 'rules' => 'php_unit_construct',
- 'using-cache' => 'no',
- 'diff' => true,
- 'format' => 'json',
- 'stop-on-violation' => true,
- ]);
- self::assertTrue($resolver->shouldStopOnViolation());
- self::assertTrue($resolver->getRiskyAllowed());
- self::assertTrue($resolver->isDryRun());
- self::assertSame(['php_unit_construct' => true], $resolver->getRules());
- self::assertFalse($resolver->getUsingCache());
- self::assertNull($resolver->getCacheFile());
- self::assertInstanceOf(UnifiedDiffer::class, $resolver->getDiffer());
- self::assertSame('json', $resolver->getReporter()->getFormat());
- self::assertSame('none', $resolver->getProgressType());
- }
- /**
- * @param class-string $expected
- * @param null|bool|string $diffConfig
- *
- * @dataProvider provideResolveDifferCases
- */
- public function testResolveDiffer(string $expected, $diffConfig): void
- {
- $resolver = $this->createConfigurationResolver([
- 'diff' => $diffConfig,
- ]);
- self::assertInstanceOf($expected, $resolver->getDiffer());
- }
- /**
- * @return iterable<array{string, null|bool}>
- */
- public static function provideResolveDifferCases(): iterable
- {
- yield [
- NullDiffer::class,
- false,
- ];
- yield [
- NullDiffer::class,
- null,
- ];
- yield [
- UnifiedDiffer::class,
- true,
- ];
- }
- public function testResolveConfigFileOverridesDefault(): void
- {
- $dir = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_8';
- $resolver = $this->createConfigurationResolver(['path' => [$dir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php']]);
- self::assertTrue($resolver->getRiskyAllowed());
- self::assertSame(['php_unit_construct' => true], $resolver->getRules());
- self::assertFalse($resolver->getUsingCache());
- self::assertNull($resolver->getCacheFile());
- self::assertSame('xml', $resolver->getReporter()->getFormat());
- self::assertSame('none', $resolver->getProgressType());
- }
- public function testDeprecationOfPassingOtherThanNoOrYes(): void
- {
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('Expected "yes" or "no" for option "allow-risky", got "yes please".');
- $resolver = $this->createConfigurationResolver(['allow-risky' => 'yes please']);
- $resolver->getRiskyAllowed();
- }
- /**
- * @return iterable<array{bool, bool, null|string}>
- */
- public static function provideResolveBooleanOptionCases(): iterable
- {
- yield [true, true, 'yes'];
- yield [true, false, 'yes'];
- yield [false, true, 'no'];
- yield [false, false, 'no'];
- yield [true, true, null];
- yield [false, false, null];
- }
- public function testWithEmptyRules(): void
- {
- $resolver = $this->createConfigurationResolver(['rules' => '']);
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessageMatches('/^Empty rules value is not allowed\.$/');
- $resolver->getRules();
- }
- /**
- * @param array<string, mixed>|bool $ruleConfig
- *
- * @dataProvider provideDeprecatedFixerConfiguredCases
- *
- * @group legacy
- */
- public function testDeprecatedFixerConfigured($ruleConfig): void
- {
- $this->expectDeprecation('Rule "Vendor4/foo" is deprecated. Use "testA" and "testB" instead.');
- $fixer = $this->createDeprecatedFixerDouble();
- $config = new Config();
- $config->registerCustomFixers([$fixer]);
- $config->setRules([$fixer->getName() => $ruleConfig]);
- $resolver = $this->createConfigurationResolver([], $config);
- $resolver->getFixers();
- }
- public static function provideDeprecatedFixerConfiguredCases(): iterable
- {
- yield [true];
- yield [['foo' => true]];
- yield [false];
- }
- /**
- * @dataProvider provideDeprecatedRuleSetConfiguredCases
- *
- * @group legacy
- *
- * @param list<string> $successors
- */
- public function testDeprecatedRuleSetConfigured(string $ruleSet, array $successors): void
- {
- $this->expectDeprecation(\sprintf(
- 'Rule set "%s" is deprecated. %s.',
- $ruleSet,
- [] === $successors
- ? 'No replacement available'
- : \sprintf('Use %s instead', Utils::naturalLanguageJoin($successors))
- ));
- $config = new Config();
- $config->setRules([$ruleSet => true]);
- $config->setRiskyAllowed(true);
- $resolver = $this->createConfigurationResolver([], $config);
- $resolver->getFixers();
- }
- /**
- * @return iterable<array{0: string, 1: list<string>}>
- */
- public static function provideDeprecatedRuleSetConfiguredCases(): iterable
- {
- yield ['@PER', ['@PER-CS']];
- yield ['@PER:risky', ['@PER-CS:risky']];
- }
- /**
- * @return iterable<array{null|string, string, string}>
- */
- public static function provideGetDirectoryCases(): iterable
- {
- yield [null, '/my/path/my/file', 'my/file'];
- yield ['/my/path/.php-cs-fixer.cache', '/my/path/my/file', 'my/file'];
- yield ['/my/path2/dir/.php-cs-fixer.cache', '/my/path2/dir/dir2/file', 'dir2/file'];
- yield ['dir/.php-cs-fixer.cache', '/my/path/dir/dir3/file', 'dir3/file'];
- }
- /**
- * @dataProvider provideGetDirectoryCases
- *
- * @param ?non-empty-string $cacheFile
- * @param non-empty-string $file
- * @param non-empty-string $expectedPathRelativeToFile
- */
- public function testGetDirectory(?string $cacheFile, string $file, string $expectedPathRelativeToFile): void
- {
- if (null !== $cacheFile) {
- $cacheFile = $this->normalizePath($cacheFile);
- }
- $file = $this->normalizePath($file);
- $expectedPathRelativeToFile = $this->normalizePath($expectedPathRelativeToFile);
- $config = new Config();
- if (null === $cacheFile) {
- $config->setUsingCache(false);
- } else {
- $config->setCacheFile($cacheFile);
- }
- $resolver = new ConfigurationResolver($config, [], $this->normalizePath('/my/path'), $this->createToolInfoDouble());
- $directory = $resolver->getDirectory();
- self::assertSame($expectedPathRelativeToFile, $directory->getRelativePathTo($file));
- }
- /**
- * @param non-empty-string $path
- *
- * @return non-empty-string
- */
- private function normalizePath(string $path): string
- {
- return str_replace('/', \DIRECTORY_SEPARATOR, $path);
- }
- /**
- * @param array<string, array<string, mixed>|bool> $expected
- * @param array<string, array<string, mixed>|bool> $actual
- */
- private static function assertSameRules(array $expected, array $actual): void
- {
- ksort($expected);
- ksort($actual);
- self::assertSame($expected, $actual);
- }
- private static function getFixtureDir(): string
- {
- return realpath(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'ConfigurationResolverConfigFile'.\DIRECTORY_SEPARATOR).'/';
- }
- /**
- * @param array<string, mixed> $options
- */
- private function createConfigurationResolver(
- array $options,
- ?ConfigInterface $config = null,
- string $cwdPath = '',
- ?ToolInfoInterface $toolInfo = null
- ): ConfigurationResolver {
- return new ConfigurationResolver(
- $config ?? new Config(),
- $options,
- $cwdPath,
- $toolInfo ?? $this->createToolInfoDouble()
- );
- }
- private function createDeprecatedFixerDouble(): DeprecatedFixerInterface
- {
- return new class extends AbstractFixer implements DeprecatedFixerInterface, ConfigurableFixerInterface {
- /** @use ConfigurableFixerTrait<array<string, mixed>, array<string, mixed>> */
- use ConfigurableFixerTrait;
- public function getDefinition(): FixerDefinitionInterface
- {
- throw new \LogicException('Not implemented.');
- }
- public function isCandidate(Tokens $tokens): bool
- {
- throw new \LogicException('Not implemented.');
- }
- public function getSuccessorsNames(): array
- {
- return ['testA', 'testB'];
- }
- public function getName(): string
- {
- return 'Vendor4/foo';
- }
- protected function applyFix(\SplFileInfo $file, Tokens $tokens): void {}
- protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
- {
- return new FixerConfigurationResolver([
- (new FixerOptionBuilder('foo', 'Foo.'))->getOption(),
- ]);
- }
- };
- }
- private function createToolInfoDouble(): ToolInfoInterface
- {
- return new class implements ToolInfoInterface {
- public function getComposerInstallationDetails(): array
- {
- throw new \BadMethodCallException();
- }
- public function getComposerVersion(): string
- {
- throw new \BadMethodCallException();
- }
- public function getVersion(): string
- {
- throw new \BadMethodCallException();
- }
- public function isInstalledAsPhar(): bool
- {
- return true;
- }
- public function isInstalledByComposer(): bool
- {
- throw new \BadMethodCallException();
- }
- public function isRunInsideDocker(): bool
- {
- return false;
- }
- public function getPharDownloadUri(string $version): string
- {
- throw new \BadMethodCallException();
- }
- };
- }
- }
|