ConfigurationResolverTest.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. <?php
  2. /*
  3. * This file is part of PHP CS Fixer.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace PhpCsFixer\Tests\Console;
  12. use PhpCsFixer\Cache\NullCacheManager;
  13. use PhpCsFixer\Config;
  14. use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
  15. use PhpCsFixer\Console\Command\FixCommand;
  16. use PhpCsFixer\Console\ConfigurationResolver;
  17. use PhpCsFixer\Finder;
  18. use PhpCsFixer\Linter\LinterInterface;
  19. use PhpCsFixer\Tests\Fixtures\DeprecatedFixer;
  20. use PhpCsFixer\Tests\TestCase;
  21. use PhpCsFixer\ToolInfo;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. /**
  24. * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
  25. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  26. *
  27. * @internal
  28. *
  29. * @covers \PhpCsFixer\Console\ConfigurationResolver
  30. */
  31. final class ConfigurationResolverTest extends TestCase
  32. {
  33. public function testSetOptionWithUndefinedOption()
  34. {
  35. $this->expectException(InvalidConfigurationException::class);
  36. $this->expectExceptionMessageRegExp('/^Unknown option name: "foo"\.$/');
  37. $this->createConfigurationResolver(['foo' => 'bar']);
  38. }
  39. public function testResolveProgressWithPositiveConfigAndPositiveOption()
  40. {
  41. $config = new Config();
  42. $config->setHideProgress(true);
  43. $resolver = $this->createConfigurationResolver([
  44. 'format' => 'txt',
  45. 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
  46. ], $config);
  47. static::assertSame('none', $resolver->getProgress());
  48. }
  49. public function testResolveProgressWithPositiveConfigAndNegativeOption()
  50. {
  51. $config = new Config();
  52. $config->setHideProgress(true);
  53. $resolver = $this->createConfigurationResolver([
  54. 'format' => 'txt',
  55. 'verbosity' => OutputInterface::VERBOSITY_NORMAL,
  56. ], $config);
  57. static::assertSame('none', $resolver->getProgress());
  58. }
  59. public function testResolveProgressWithNegativeConfigAndPositiveOption()
  60. {
  61. $config = new Config();
  62. $config->setHideProgress(false);
  63. $resolver = $this->createConfigurationResolver([
  64. 'format' => 'txt',
  65. 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
  66. ], $config);
  67. static::assertSame('run-in', $resolver->getProgress());
  68. }
  69. public function testResolveProgressWithNegativeConfigAndNegativeOption()
  70. {
  71. $config = new Config();
  72. $config->setHideProgress(false);
  73. $resolver = $this->createConfigurationResolver([
  74. 'format' => 'txt',
  75. 'verbosity' => OutputInterface::VERBOSITY_NORMAL,
  76. ], $config);
  77. static::assertSame('none', $resolver->getProgress());
  78. }
  79. /**
  80. * @param string $progressType
  81. *
  82. * @dataProvider provideProgressTypeCases
  83. */
  84. public function testResolveProgressWithPositiveConfigAndExplicitProgress($progressType)
  85. {
  86. $config = new Config();
  87. $config->setHideProgress(true);
  88. $resolver = $this->createConfigurationResolver([
  89. 'format' => 'txt',
  90. 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
  91. 'show-progress' => $progressType,
  92. ], $config);
  93. static::assertSame($progressType, $resolver->getProgress());
  94. }
  95. /**
  96. * @param string $progressType
  97. *
  98. * @dataProvider provideProgressTypeLegacyCases
  99. *
  100. * @group legacy
  101. * @expectedDeprecation Passing `estimating`, `estimating-max` or `run-in` is deprecated and will not be supported in 3.0, use `none` or `dots` instead.
  102. */
  103. public function testResolveProgressWithPositiveConfigAndExplicitProgressLegacy($progressType)
  104. {
  105. $this->testResolveProgressWithPositiveConfigAndExplicitProgress($progressType);
  106. }
  107. /**
  108. * @param string $progressType
  109. *
  110. * @dataProvider provideProgressTypeCases
  111. */
  112. public function testResolveProgressWithNegativeConfigAndExplicitProgress($progressType)
  113. {
  114. $config = new Config();
  115. $config->setHideProgress(false);
  116. $resolver = $this->createConfigurationResolver([
  117. 'format' => 'txt',
  118. 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
  119. 'show-progress' => $progressType,
  120. ], $config);
  121. static::assertSame($progressType, $resolver->getProgress());
  122. }
  123. /**
  124. * @param string $progressType
  125. *
  126. * @dataProvider provideProgressTypeLegacyCases
  127. *
  128. * @group legacy
  129. * @expectedDeprecation Passing `estimating`, `estimating-max` or `run-in` is deprecated and will not be supported in 3.0, use `none` or `dots` instead.
  130. */
  131. public function testResolveProgressWithNegativeConfigAndExplicitProgressLegacy($progressType)
  132. {
  133. $this->testResolveProgressWithNegativeConfigAndExplicitProgress($progressType);
  134. }
  135. public function provideProgressTypeLegacyCases()
  136. {
  137. return [
  138. ['run-in'],
  139. ['estimating'],
  140. ['estimating-max'],
  141. ];
  142. }
  143. public function provideProgressTypeCases()
  144. {
  145. return [
  146. ['none'],
  147. ['dots'],
  148. ];
  149. }
  150. public function testResolveProgressWithInvalidExplicitProgress()
  151. {
  152. $resolver = $this->createConfigurationResolver([
  153. 'format' => 'txt',
  154. 'verbosity' => OutputInterface::VERBOSITY_VERBOSE,
  155. 'show-progress' => 'foo',
  156. ]);
  157. $this->expectException(InvalidConfigurationException::class);
  158. $this->expectExceptionMessage('The progress type "foo" is not defined, supported are "none", "run-in", "estimating", "estimating-max", "dots".');
  159. $resolver->getProgress();
  160. }
  161. public function testResolveConfigFileDefault()
  162. {
  163. $resolver = $this->createConfigurationResolver([]);
  164. static::assertNull($resolver->getConfigFile());
  165. static::assertInstanceOf(\PhpCsFixer\ConfigInterface::class, $resolver->getConfig());
  166. }
  167. public function testResolveConfigFileByPathOfFile()
  168. {
  169. $dir = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_1';
  170. $resolver = $this->createConfigurationResolver(['path' => [$dir.\DIRECTORY_SEPARATOR.'foo.php']]);
  171. static::assertSame($dir.\DIRECTORY_SEPARATOR.'.php_cs.dist', $resolver->getConfigFile());
  172. static::assertInstanceOf('Test1Config', $resolver->getConfig());
  173. }
  174. public function testResolveConfigFileSpecified()
  175. {
  176. $file = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_4/my.php_cs';
  177. $resolver = $this->createConfigurationResolver(['config' => $file]);
  178. static::assertSame($file, $resolver->getConfigFile());
  179. static::assertInstanceOf('Test4Config', $resolver->getConfig());
  180. }
  181. /**
  182. * @param string $expectedFile
  183. * @param string $expectedClass
  184. * @param string $path
  185. * @param null|string $cwdPath
  186. *
  187. * @dataProvider provideResolveConfigFileDefaultCases
  188. */
  189. public function testResolveConfigFileChooseFile($expectedFile, $expectedClass, $path, $cwdPath = null)
  190. {
  191. $resolver = $this->createConfigurationResolver(
  192. ['path' => [$path]],
  193. null,
  194. $cwdPath
  195. );
  196. static::assertSame($expectedFile, $resolver->getConfigFile());
  197. static::assertInstanceOf($expectedClass, $resolver->getConfig());
  198. }
  199. public function provideResolveConfigFileDefaultCases()
  200. {
  201. $dirBase = $this->getFixtureDir();
  202. return [
  203. [
  204. $dirBase.'case_1'.\DIRECTORY_SEPARATOR.'.php_cs.dist',
  205. 'Test1Config',
  206. $dirBase.'case_1',
  207. ],
  208. [
  209. $dirBase.'case_2'.\DIRECTORY_SEPARATOR.'.php_cs',
  210. 'Test2Config',
  211. $dirBase.'case_2',
  212. ],
  213. [
  214. $dirBase.'case_3'.\DIRECTORY_SEPARATOR.'.php_cs',
  215. 'Test3Config',
  216. $dirBase.'case_3',
  217. ],
  218. [
  219. $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php_cs.dist',
  220. 'Test6Config',
  221. $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir',
  222. $dirBase.'case_6',
  223. ],
  224. [
  225. $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php_cs.dist',
  226. 'Test6Config',
  227. $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir/empty_file.php',
  228. $dirBase.'case_6',
  229. ],
  230. ];
  231. }
  232. public function testResolveConfigFileChooseFileWithInvalidFile()
  233. {
  234. $this->expectException(InvalidConfigurationException::class);
  235. $this->expectExceptionMessageRegExp(
  236. '#^The config file: ".+[\/\\\]Fixtures[\/\\\]ConfigurationResolverConfigFile[\/\\\]case_5[\/\\\]\.php_cs\.dist" does not return a "PhpCsFixer\\\ConfigInterface" instance\. Got: "string"\.$#'
  237. );
  238. $dirBase = $this->getFixtureDir();
  239. $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_5']]);
  240. $resolver->getConfig();
  241. }
  242. public function testResolveConfigFileChooseFileWithInvalidFormat()
  243. {
  244. $this->expectException(InvalidConfigurationException::class);
  245. $this->expectExceptionMessageRegExp('/^The format "xls" is not defined, supported are "checkstyle", "gitlab", "json", "junit", "txt", "xml"\.$/');
  246. $dirBase = $this->getFixtureDir();
  247. $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_7']]);
  248. $resolver->getReporter();
  249. }
  250. public function testResolveConfigFileChooseFileWithPathArrayWithoutConfig()
  251. {
  252. $this->expectException(InvalidConfigurationException::class);
  253. $this->expectExceptionMessageRegExp('/^For multiple paths config parameter is required\.$/');
  254. $dirBase = $this->getFixtureDir();
  255. $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_1/.php_cs.dist', $dirBase.'case_1/foo.php']]);
  256. $resolver->getConfig();
  257. }
  258. public function testResolveConfigFileChooseFileWithPathArrayAndConfig()
  259. {
  260. $dirBase = $this->getFixtureDir();
  261. $resolver = $this->createConfigurationResolver([
  262. 'config' => $dirBase.'case_1/.php_cs.dist',
  263. 'path' => [$dirBase.'case_1/.php_cs.dist', $dirBase.'case_1/foo.php'],
  264. ]);
  265. static::assertInstanceOf(\PhpCsFixer\Console\ConfigurationResolver::class, $resolver);
  266. }
  267. public function testResolvePathRelativeA()
  268. {
  269. $resolver = $this->createConfigurationResolver(
  270. ['path' => ['Command']],
  271. null,
  272. __DIR__
  273. );
  274. static::assertSame([__DIR__.\DIRECTORY_SEPARATOR.'Command'], $resolver->getPath());
  275. }
  276. public function testResolvePathRelativeB()
  277. {
  278. $resolver = $this->createConfigurationResolver(
  279. ['path' => [basename(__DIR__)]],
  280. null,
  281. \dirname(__DIR__)
  282. );
  283. static::assertSame([__DIR__], $resolver->getPath());
  284. }
  285. public function testResolvePathWithFileThatIsExcludedDirectlyOverridePathMode()
  286. {
  287. $config = new Config();
  288. $config->getFinder()
  289. ->in(__DIR__)
  290. ->notPath(basename(__FILE__))
  291. ;
  292. $resolver = $this->createConfigurationResolver(
  293. ['path' => [__FILE__]],
  294. $config
  295. );
  296. static::assertCount(1, $resolver->getFinder());
  297. }
  298. public function testResolvePathWithFileThatIsExcludedDirectlyIntersectionPathMode()
  299. {
  300. $config = new Config();
  301. $config->getFinder()
  302. ->in(__DIR__)
  303. ->notPath(basename(__FILE__))
  304. ;
  305. $resolver = $this->createConfigurationResolver([
  306. 'path' => [__FILE__],
  307. 'path-mode' => 'intersection',
  308. ], $config);
  309. static::assertCount(0, $resolver->getFinder());
  310. }
  311. public function testResolvePathWithFileThatIsExcludedByDirOverridePathMode()
  312. {
  313. $dir = \dirname(__DIR__);
  314. $config = new Config();
  315. $config->getFinder()
  316. ->in($dir)
  317. ->exclude(basename(__DIR__))
  318. ;
  319. $resolver = $this->createConfigurationResolver(
  320. ['path' => [__FILE__]],
  321. $config
  322. );
  323. static::assertCount(1, $resolver->getFinder());
  324. }
  325. public function testResolvePathWithFileThatIsExcludedByDirIntersectionPathMode()
  326. {
  327. $dir = \dirname(__DIR__);
  328. $config = new Config();
  329. $config->getFinder()
  330. ->in($dir)
  331. ->exclude(basename(__DIR__))
  332. ;
  333. $resolver = $this->createConfigurationResolver([
  334. 'path-mode' => 'intersection',
  335. 'path' => [__FILE__],
  336. ], $config);
  337. static::assertCount(0, $resolver->getFinder());
  338. }
  339. public function testResolvePathWithFileThatIsNotExcluded()
  340. {
  341. $dir = __DIR__;
  342. $config = new Config();
  343. $config->getFinder()
  344. ->in($dir)
  345. ->notPath('foo-'.basename(__FILE__))
  346. ;
  347. $resolver = $this->createConfigurationResolver(
  348. ['path' => [__FILE__]],
  349. $config
  350. );
  351. static::assertCount(1, $resolver->getFinder());
  352. }
  353. /**
  354. * @param array|\Exception $expected
  355. * @param null|Finder $configFinder
  356. * @param string $pathMode
  357. * @param null|string $configOption
  358. *
  359. * @dataProvider provideResolveIntersectionOfPathsCases
  360. */
  361. public function testResolveIntersectionOfPaths($expected, $configFinder, array $path, $pathMode, $configOption = null)
  362. {
  363. if ($expected instanceof \Exception) {
  364. $this->expectException(\get_class($expected));
  365. }
  366. if (null !== $configFinder) {
  367. $config = new Config();
  368. $config->setFinder($configFinder);
  369. } else {
  370. $config = null;
  371. }
  372. $resolver = $this->createConfigurationResolver([
  373. 'config' => $configOption,
  374. 'path' => $path,
  375. 'path-mode' => $pathMode,
  376. ], $config);
  377. $intersectionItems = array_map(
  378. static function (\SplFileInfo $file) {
  379. return $file->getRealPath();
  380. },
  381. iterator_to_array($resolver->getFinder(), false)
  382. );
  383. sort($expected);
  384. sort($intersectionItems);
  385. static::assertSame($expected, $intersectionItems);
  386. }
  387. public function provideResolveIntersectionOfPathsCases()
  388. {
  389. $dir = __DIR__.'/../Fixtures/ConfigurationResolverPathsIntersection';
  390. $cb = static function (array $items) use ($dir) {
  391. return array_map(
  392. static function ($item) use ($dir) {
  393. return realpath($dir.'/'.$item);
  394. },
  395. $items
  396. );
  397. };
  398. return [
  399. 'no path at all' => [
  400. new \LogicException(),
  401. Finder::create(),
  402. [],
  403. 'override',
  404. ],
  405. 'configured only by finder' => [
  406. // don't override if the argument is empty
  407. $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']),
  408. Finder::create()
  409. ->in($dir),
  410. [],
  411. 'override',
  412. ],
  413. 'configured only by argument' => [
  414. $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']),
  415. Finder::create(),
  416. [$dir],
  417. 'override',
  418. ],
  419. 'configured by finder, intersected with empty argument' => [
  420. [],
  421. Finder::create()
  422. ->in($dir),
  423. [],
  424. 'intersection',
  425. ],
  426. 'configured by finder, intersected with dir' => [
  427. $cb(['c/c1.php', 'c/d/cd1.php']),
  428. Finder::create()
  429. ->in($dir),
  430. [$dir.'/c'],
  431. 'intersection',
  432. ],
  433. 'configured by finder, intersected with file' => [
  434. $cb(['c/c1.php']),
  435. Finder::create()
  436. ->in($dir),
  437. [$dir.'/c/c1.php'],
  438. 'intersection',
  439. ],
  440. 'finder points to one dir while argument to another, not connected' => [
  441. [],
  442. Finder::create()
  443. ->in($dir.'/b'),
  444. [$dir.'/c'],
  445. 'intersection',
  446. ],
  447. 'finder with excluded dir, intersected with excluded file' => [
  448. [],
  449. Finder::create()
  450. ->in($dir)
  451. ->exclude('c'),
  452. [$dir.'/c/d/cd1.php'],
  453. 'intersection',
  454. ],
  455. 'finder with excluded dir, intersected with dir containing excluded one' => [
  456. $cb(['c/c1.php']),
  457. Finder::create()
  458. ->in($dir)
  459. ->exclude('c/d'),
  460. [$dir.'/c'],
  461. 'intersection',
  462. ],
  463. 'finder with excluded file, intersected with dir containing excluded one' => [
  464. $cb(['c/d/cd1.php']),
  465. Finder::create()
  466. ->in($dir)
  467. ->notPath('c/c1.php'),
  468. [$dir.'/c'],
  469. 'intersection',
  470. ],
  471. 'configured by finder, intersected with non-existing path' => [
  472. new \LogicException(),
  473. Finder::create()
  474. ->in($dir),
  475. ['non_existing_dir'],
  476. 'intersection',
  477. ],
  478. 'configured by config file, overridden by multiple files' => [
  479. $cb(['d/d1.php', 'd/d2.php']),
  480. null,
  481. [$dir.'/d/d1.php', $dir.'/d/d2.php'],
  482. 'override',
  483. $dir.'/d/.php_cs',
  484. ],
  485. 'configured by config file, intersected with multiple files' => [
  486. $cb(['d/d1.php', 'd/d2.php']),
  487. null,
  488. [$dir.'/d/d1.php', $dir.'/d/d2.php'],
  489. 'intersection',
  490. $dir.'/d/.php_cs',
  491. ],
  492. 'configured by config file, overridden by non-existing dir' => [
  493. new \LogicException(),
  494. null,
  495. [$dir.'/d/fff'],
  496. 'override',
  497. $dir.'/d/.php_cs',
  498. ],
  499. 'configured by config file, intersected with non-existing dir' => [
  500. new \LogicException(),
  501. null,
  502. [$dir.'/d/fff'],
  503. 'intersection',
  504. $dir.'/d/.php_cs',
  505. ],
  506. 'configured by config file, overridden by non-existing file' => [
  507. new \LogicException(),
  508. null,
  509. [$dir.'/d/fff.php'],
  510. 'override',
  511. $dir.'/d/.php_cs',
  512. ],
  513. 'configured by config file, intersected with non-existing file' => [
  514. new \LogicException(),
  515. null,
  516. [$dir.'/d/fff.php'],
  517. 'intersection',
  518. $dir.'/d/.php_cs',
  519. ],
  520. 'configured by config file, overridden by multiple files and dirs' => [
  521. $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']),
  522. null,
  523. [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'],
  524. 'override',
  525. $dir.'/d/.php_cs',
  526. ],
  527. 'configured by config file, intersected with multiple files and dirs' => [
  528. $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']),
  529. null,
  530. [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'],
  531. 'intersection',
  532. $dir.'/d/.php_cs',
  533. ],
  534. ];
  535. }
  536. /**
  537. * @param bool $expectedResult
  538. *
  539. * @dataProvider provideConfigFinderIsOverriddenCases
  540. */
  541. public function testConfigFinderIsOverridden(array $options, $expectedResult)
  542. {
  543. $resolver = $this->createConfigurationResolver($options);
  544. static::assertSame($expectedResult, $resolver->configFinderIsOverridden());
  545. $resolver = $this->createConfigurationResolver($options);
  546. $resolver->getFinder();
  547. static::assertSame($expectedResult, $resolver->configFinderIsOverridden());
  548. }
  549. public function provideConfigFinderIsOverriddenCases()
  550. {
  551. $root = __DIR__.'/../..';
  552. return [
  553. [
  554. [
  555. 'config' => $root.'/.php_cs.dist',
  556. ],
  557. false,
  558. ],
  559. [
  560. [
  561. 'config' => $root.'/.php_cs.dist',
  562. 'path' => [$root.'/src'],
  563. ],
  564. true,
  565. ],
  566. [
  567. [],
  568. false,
  569. ],
  570. [
  571. [
  572. 'path' => [$root.'/src'],
  573. ],
  574. false,
  575. ],
  576. [
  577. [
  578. 'config' => $root.'/.php_cs.dist',
  579. 'path' => [$root.'/src'],
  580. 'path-mode' => ConfigurationResolver::PATH_MODE_INTERSECTION,
  581. ],
  582. false,
  583. ],
  584. // scenario when loaded config is not setting custom finder
  585. [
  586. [
  587. 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_3/.php_cs.dist',
  588. 'path' => [$root.'/src'],
  589. ],
  590. false,
  591. ],
  592. // scenario when loaded config contains not fully defined finder
  593. [
  594. [
  595. 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_9/.php_cs',
  596. 'path' => [$root.'/src'],
  597. ],
  598. false,
  599. ],
  600. ];
  601. }
  602. public function testResolveIsDryRunViaStdIn()
  603. {
  604. $resolver = $this->createConfigurationResolver([
  605. 'dry-run' => false,
  606. 'path' => ['-'],
  607. ]);
  608. static::assertTrue($resolver->isDryRun());
  609. }
  610. public function testResolveIsDryRunViaNegativeOption()
  611. {
  612. $resolver = $this->createConfigurationResolver(['dry-run' => false]);
  613. static::assertFalse($resolver->isDryRun());
  614. }
  615. public function testResolveIsDryRunViaPositiveOption()
  616. {
  617. $resolver = $this->createConfigurationResolver(['dry-run' => true]);
  618. static::assertTrue($resolver->isDryRun());
  619. }
  620. /**
  621. * @param bool $expected
  622. * @param bool $configValue
  623. * @param null|bool|string $passed
  624. *
  625. * @dataProvider provideResolveBooleanOptionCases
  626. */
  627. public function testResolveUsingCacheWithConfigOption($expected, $configValue, $passed)
  628. {
  629. $config = new Config();
  630. $config->setUsingCache($configValue);
  631. $resolver = $this->createConfigurationResolver(
  632. ['using-cache' => $passed],
  633. $config
  634. );
  635. static::assertSame($expected, $resolver->getUsingCache());
  636. }
  637. public function testResolveUsingCacheWithPositiveConfigAndNoOption()
  638. {
  639. $config = new Config();
  640. $config->setUsingCache(true);
  641. $resolver = $this->createConfigurationResolver(
  642. [],
  643. $config
  644. );
  645. static::assertTrue($resolver->getUsingCache());
  646. }
  647. public function testResolveUsingCacheWithNegativeConfigAndNoOption()
  648. {
  649. $config = new Config();
  650. $config->setUsingCache(false);
  651. $resolver = $this->createConfigurationResolver(
  652. [],
  653. $config
  654. );
  655. static::assertFalse($resolver->getUsingCache());
  656. }
  657. public function testResolveCacheFileWithoutConfigAndOption()
  658. {
  659. $config = new Config();
  660. $default = $config->getCacheFile();
  661. $resolver = $this->createConfigurationResolver(
  662. [],
  663. $config
  664. );
  665. static::assertSame($default, $resolver->getCacheFile());
  666. }
  667. public function testResolveCacheFileWithConfig()
  668. {
  669. $cacheFile = 'foo/bar.baz';
  670. $config = new Config();
  671. $config->setCacheFile($cacheFile);
  672. $resolver = $this->createConfigurationResolver(
  673. [],
  674. $config
  675. );
  676. static::assertSame($cacheFile, $resolver->getCacheFile());
  677. $cacheManager = $resolver->getCacheManager();
  678. static::assertInstanceOf(NullCacheManager::class, $cacheManager);
  679. $linter = $resolver->getLinter();
  680. static::assertInstanceOf(LinterInterface::class, $linter);
  681. }
  682. public function testResolveCacheFileWithOption()
  683. {
  684. $cacheFile = 'bar.baz';
  685. $config = new Config();
  686. $config->setCacheFile($cacheFile);
  687. $resolver = $this->createConfigurationResolver(
  688. ['cache-file' => $cacheFile],
  689. $config
  690. );
  691. static::assertSame($cacheFile, $resolver->getCacheFile());
  692. }
  693. public function testResolveCacheFileWithConfigAndOption()
  694. {
  695. $configCacheFile = 'foo/bar.baz';
  696. $optionCacheFile = 'bar.baz';
  697. $config = new Config();
  698. $config->setCacheFile($configCacheFile);
  699. $resolver = $this->createConfigurationResolver(
  700. ['cache-file' => $optionCacheFile],
  701. $config
  702. );
  703. static::assertSame($optionCacheFile, $resolver->getCacheFile());
  704. }
  705. /**
  706. * @param bool $expected
  707. * @param bool $configValue
  708. * @param null|bool|string $passed
  709. *
  710. * @dataProvider provideResolveBooleanOptionCases
  711. */
  712. public function testResolveAllowRiskyWithConfigOption($expected, $configValue, $passed)
  713. {
  714. $config = new Config();
  715. $config->setRiskyAllowed($configValue);
  716. $resolver = $this->createConfigurationResolver(
  717. ['allow-risky' => $passed],
  718. $config
  719. );
  720. static::assertSame($expected, $resolver->getRiskyAllowed());
  721. }
  722. public function testResolveAllowRiskyWithNegativeConfigAndPositiveOption()
  723. {
  724. $config = new Config();
  725. $config->setRiskyAllowed(false);
  726. $resolver = $this->createConfigurationResolver(
  727. ['allow-risky' => 'yes'],
  728. $config
  729. );
  730. static::assertTrue($resolver->getRiskyAllowed());
  731. }
  732. public function testResolveAllowRiskyWithNegativeConfigAndNegativeOption()
  733. {
  734. $config = new Config();
  735. $config->setRiskyAllowed(false);
  736. $resolver = $this->createConfigurationResolver(
  737. ['allow-risky' => 'no'],
  738. $config
  739. );
  740. static::assertFalse($resolver->getRiskyAllowed());
  741. }
  742. public function testResolveAllowRiskyWithPositiveConfigAndNoOption()
  743. {
  744. $config = new Config();
  745. $config->setRiskyAllowed(true);
  746. $resolver = $this->createConfigurationResolver(
  747. [],
  748. $config
  749. );
  750. static::assertTrue($resolver->getRiskyAllowed());
  751. }
  752. public function testResolveAllowRiskyWithNegativeConfigAndNoOption()
  753. {
  754. $config = new Config();
  755. $config->setRiskyAllowed(false);
  756. $resolver = $this->createConfigurationResolver(
  757. [],
  758. $config
  759. );
  760. static::assertFalse($resolver->getRiskyAllowed());
  761. }
  762. public function testResolveRulesWithConfig()
  763. {
  764. $config = new Config();
  765. $config->setRules([
  766. 'braces' => true,
  767. 'strict_comparison' => false,
  768. ]);
  769. $resolver = $this->createConfigurationResolver(
  770. [],
  771. $config
  772. );
  773. static::assertSameRules(
  774. [
  775. 'braces' => true,
  776. ],
  777. $resolver->getRules()
  778. );
  779. }
  780. public function testResolveRulesWithOption()
  781. {
  782. $resolver = $this->createConfigurationResolver(['rules' => 'braces,-strict_comparison']);
  783. static::assertSameRules(
  784. [
  785. 'braces' => true,
  786. ],
  787. $resolver->getRules()
  788. );
  789. }
  790. public function testResolveRulesWithUnknownRules()
  791. {
  792. $this->expectException(
  793. \PhpCsFixer\ConfigurationException\InvalidConfigurationException::class
  794. );
  795. $this->expectExceptionMessage(
  796. 'The rules contain unknown fixers: "bar", "binary_operator_space" (did you mean "binary_operator_spaces"?).'
  797. );
  798. $resolver = $this->createConfigurationResolver(['rules' => 'braces,-bar,binary_operator_space']);
  799. $resolver->getRules();
  800. }
  801. public function testResolveRulesWithConfigAndOption()
  802. {
  803. $config = new Config();
  804. $config->setRules([
  805. 'braces' => true,
  806. 'strict_comparison' => false,
  807. ]);
  808. $resolver = $this->createConfigurationResolver(
  809. ['rules' => 'blank_line_before_statement'],
  810. $config
  811. );
  812. static::assertSameRules(
  813. [
  814. 'blank_line_before_statement' => true,
  815. ],
  816. $resolver->getRules()
  817. );
  818. }
  819. public function testResolveCommandLineInputOverridesDefault()
  820. {
  821. $command = new FixCommand(new ToolInfo());
  822. $definition = $command->getDefinition();
  823. $arguments = $definition->getArguments();
  824. static::assertCount(1, $arguments, 'Expected one argument, possibly test needs updating.');
  825. static::assertArrayHasKey('path', $arguments);
  826. $options = $definition->getOptions();
  827. static::assertSame(
  828. ['path-mode', 'allow-risky', 'config', 'dry-run', 'rules', 'using-cache', 'cache-file', 'diff', 'diff-format', 'format', 'stop-on-violation', 'show-progress'],
  829. array_keys($options),
  830. 'Expected options mismatch, possibly test needs updating.'
  831. );
  832. $resolver = $this->createConfigurationResolver([
  833. 'path-mode' => 'intersection',
  834. 'allow-risky' => 'yes',
  835. 'config' => null,
  836. 'dry-run' => true,
  837. 'rules' => 'php_unit_construct',
  838. 'using-cache' => false,
  839. 'diff' => true,
  840. 'diff-format' => 'udiff',
  841. 'format' => 'json',
  842. 'stop-on-violation' => true,
  843. ]);
  844. static::assertTrue($resolver->shouldStopOnViolation());
  845. static::assertTrue($resolver->getRiskyAllowed());
  846. static::assertTrue($resolver->isDryRun());
  847. static::assertSame(['php_unit_construct' => true], $resolver->getRules());
  848. static::assertFalse($resolver->getUsingCache());
  849. static::assertNull($resolver->getCacheFile());
  850. static::assertInstanceOf(\PhpCsFixer\Differ\UnifiedDiffer::class, $resolver->getDiffer());
  851. static::assertSame('json', $resolver->getReporter()->getFormat());
  852. }
  853. /**
  854. * @param string $expected
  855. * @param null|bool|string $diffConfig
  856. * @param null|string $differConfig
  857. *
  858. * @dataProvider provideDifferCases
  859. */
  860. public function testResolveDiffer($expected, $diffConfig, $differConfig = null)
  861. {
  862. $resolver = $this->createConfigurationResolver([
  863. 'diff' => $diffConfig,
  864. 'diff-format' => $differConfig,
  865. ]);
  866. static::assertInstanceOf($expected, $resolver->getDiffer());
  867. }
  868. public function provideDifferCases()
  869. {
  870. return [
  871. [
  872. \PhpCsFixer\Differ\NullDiffer::class,
  873. false,
  874. ],
  875. [
  876. \PhpCsFixer\Differ\NullDiffer::class,
  877. null,
  878. ],
  879. [
  880. \PhpCsFixer\Differ\SebastianBergmannDiffer::class,
  881. true,
  882. ],
  883. [
  884. \PhpCsFixer\Differ\SebastianBergmannDiffer::class,
  885. 'sbd',
  886. ],
  887. [
  888. \PhpCsFixer\Differ\SebastianBergmannDiffer::class,
  889. true,
  890. 'sbd',
  891. ],
  892. [
  893. \PhpCsFixer\Differ\SebastianBergmannDiffer::class,
  894. false,
  895. 'sbd',
  896. ],
  897. [
  898. \PhpCsFixer\Differ\SebastianBergmannDiffer::class,
  899. null,
  900. 'sbd',
  901. ],
  902. [
  903. \PhpCsFixer\Differ\UnifiedDiffer::class,
  904. true,
  905. 'udiff',
  906. ],
  907. [
  908. \PhpCsFixer\Differ\UnifiedDiffer::class,
  909. false,
  910. 'udiff',
  911. ],
  912. [
  913. \PhpCsFixer\Differ\UnifiedDiffer::class,
  914. null,
  915. 'udiff',
  916. ],
  917. ];
  918. }
  919. public function testResolveUnknownDiffer()
  920. {
  921. $resolver = $this->createConfigurationResolver([
  922. 'diff-format' => 'XXX',
  923. ]);
  924. $this->expectException(\InvalidArgumentException::class);
  925. $this->expectExceptionMessageRegExp('#^"diff\-format" must be any of "null", "sbd", "udiff", got "XXX"\.$#');
  926. $resolver->getDiffer();
  927. }
  928. public function testResolveConfigFileOverridesDefault()
  929. {
  930. $dir = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_8';
  931. $resolver = $this->createConfigurationResolver(['path' => [$dir.\DIRECTORY_SEPARATOR.'.php_cs']]);
  932. static::assertTrue($resolver->getRiskyAllowed());
  933. static::assertSame(['php_unit_construct' => true], $resolver->getRules());
  934. static::assertFalse($resolver->getUsingCache());
  935. static::assertNull($resolver->getCacheFile());
  936. static::assertSame('xml', $resolver->getReporter()->getFormat());
  937. }
  938. /**
  939. * @group legacy
  940. * @expectedDeprecation Expected "yes" or "no" for option "allow-risky", other values are deprecated and support will be removed in 3.0. Got "yes please", this implicitly set the option to "false".
  941. */
  942. public function testDeprecationOfPassingOtherThanNoOrYes()
  943. {
  944. $resolver = $this->createConfigurationResolver(['allow-risky' => 'yes please']);
  945. static::assertFalse($resolver->getRiskyAllowed());
  946. }
  947. public function provideResolveBooleanOptionCases()
  948. {
  949. return [
  950. [true, true, 'yes'],
  951. [true, true, true],
  952. [true, false, 'yes'],
  953. [true, false, true],
  954. [false, true, 'no'],
  955. [false, true, false],
  956. [false, false, 'no'],
  957. [false, false, false],
  958. [true, true, null],
  959. [false, false, null],
  960. ];
  961. }
  962. public function testWithEmptyRules()
  963. {
  964. $resolver = $this->createConfigurationResolver(['rules' => '']);
  965. $this->expectException(InvalidConfigurationException::class);
  966. $this->expectExceptionMessageRegExp('/^Empty rules value is not allowed\.$/');
  967. $resolver->getRules();
  968. }
  969. /**
  970. * @param array|bool $ruleConfig
  971. *
  972. * @dataProvider provideDeprecatedFixerConfiguredCases
  973. *
  974. * @group legacy
  975. * @expectedDeprecation Rule "Vendor4/foo" is deprecated. Use "testA" and "testB" instead.
  976. */
  977. public function testDeprecatedFixerConfigured($ruleConfig)
  978. {
  979. $fixer = new DeprecatedFixer();
  980. $config = new Config();
  981. $config->registerCustomFixers([$fixer]);
  982. $config->setRules([$fixer->getName() => $ruleConfig]);
  983. $resolver = $this->createConfigurationResolver([], $config);
  984. $resolver->getFixers();
  985. }
  986. public function provideDeprecatedFixerConfiguredCases()
  987. {
  988. return [
  989. [true],
  990. [['foo' => true]],
  991. [false],
  992. ];
  993. }
  994. public function provideGetDirectoryCases()
  995. {
  996. return [
  997. [null, '/my/path/my/file', 'path/my/file'],
  998. ['/my/path2/dir/.php_cs.cache', '/my/path2/dir/dir2/file', 'dir2/file'],
  999. ['dir/.php_cs.cache', '/my/path/dir/dir3/file', 'dir3/file'],
  1000. ];
  1001. }
  1002. /**
  1003. * @dataProvider provideGetDirectoryCases
  1004. *
  1005. * @param null|string $cacheFile
  1006. * @param string $file
  1007. * @param string $expectedPathRelativeToFile
  1008. */
  1009. public function testGetDirectory($cacheFile, $file, $expectedPathRelativeToFile)
  1010. {
  1011. if (null !== $cacheFile) {
  1012. $cacheFile = $this->normalizePath($cacheFile);
  1013. }
  1014. $file = $this->normalizePath($file);
  1015. $expectedPathRelativeToFile = $this->normalizePath($expectedPathRelativeToFile);
  1016. $config = new Config();
  1017. if (null === $cacheFile) {
  1018. $config->setUsingCache(false);
  1019. } else {
  1020. $config->setCacheFile($cacheFile);
  1021. }
  1022. $resolver = new ConfigurationResolver($config, [], $this->normalizePath('/my/path'), new ToolInfo());
  1023. $directory = $resolver->getDirectory();
  1024. static::assertSame($expectedPathRelativeToFile, $directory->getRelativePathTo($file));
  1025. }
  1026. private function normalizePath($path)
  1027. {
  1028. return str_replace('/', \DIRECTORY_SEPARATOR, $path);
  1029. }
  1030. private static function assertSameRules(array $expected, array $actual, $message = '')
  1031. {
  1032. ksort($expected);
  1033. ksort($actual);
  1034. static::assertSame($expected, $actual, $message);
  1035. }
  1036. private function getFixtureDir()
  1037. {
  1038. return realpath(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'ConfigurationResolverConfigFile'.\DIRECTORY_SEPARATOR).'/';
  1039. }
  1040. private function createConfigurationResolver(array $options, Config $config = null, $cwdPath = '')
  1041. {
  1042. if (null === $config) {
  1043. $config = new Config();
  1044. }
  1045. return new ConfigurationResolver(
  1046. $config,
  1047. $options,
  1048. $cwdPath,
  1049. new ToolInfo()
  1050. );
  1051. }
  1052. }