FixerFactoryTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Tests;
  13. use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\Fixer\FixerInterface;
  16. use PhpCsFixer\Fixer\InternalFixerInterface;
  17. use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
  18. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
  19. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  20. use PhpCsFixer\FixerFactory;
  21. use PhpCsFixer\RuleSet\RuleSet;
  22. use PhpCsFixer\RuleSet\RuleSetInterface;
  23. use PhpCsFixer\Tokenizer\Tokens;
  24. use PhpCsFixer\WhitespacesFixerConfig;
  25. /**
  26. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  27. *
  28. * @internal
  29. *
  30. * @covers \PhpCsFixer\FixerFactory
  31. */
  32. final class FixerFactoryTest extends TestCase
  33. {
  34. public function testInterfaceIsFluent(): void
  35. {
  36. $factory = new FixerFactory();
  37. $testInstance = $factory->registerBuiltInFixers();
  38. self::assertSame($factory, $testInstance);
  39. $testInstance = $factory->registerCustomFixers(
  40. [$this->createFixerDouble('Foo/f1'), $this->createFixerDouble('Foo/f2')]
  41. );
  42. self::assertSame($factory, $testInstance);
  43. $testInstance = $factory->registerFixer(
  44. $this->createFixerDouble('f3'),
  45. false
  46. );
  47. self::assertSame($factory, $testInstance);
  48. $ruleSet = new class([]) implements RuleSetInterface {
  49. /** @var array<string, array<string, mixed>|true> */
  50. private array $set;
  51. /** @param array<string, array<string, mixed>|true> $set */
  52. public function __construct(array $set = [])
  53. {
  54. $this->set = $set;
  55. }
  56. public function getRuleConfiguration(string $rule): ?array
  57. {
  58. throw new \LogicException('Not implemented.');
  59. }
  60. public function getRules(): array
  61. {
  62. return $this->set;
  63. }
  64. public function hasRule(string $rule): bool
  65. {
  66. throw new \LogicException('Not implemented.');
  67. }
  68. };
  69. $testInstance = $factory->useRuleSet(
  70. $ruleSet
  71. );
  72. self::assertSame($factory, $testInstance);
  73. }
  74. /**
  75. * @covers \PhpCsFixer\FixerFactory::registerBuiltInFixers
  76. */
  77. public function testRegisterBuiltInFixers(): void
  78. {
  79. $factory = new FixerFactory();
  80. $factory->registerBuiltInFixers();
  81. $fixerClasses = array_filter(
  82. get_declared_classes(),
  83. static function (string $className): bool {
  84. $class = new \ReflectionClass($className);
  85. return !$class->isAbstract()
  86. && !$class->isAnonymous()
  87. && $class->implementsInterface(FixerInterface::class)
  88. && !$class->implementsInterface(InternalFixerInterface::class)
  89. && str_starts_with($class->getNamespaceName(), 'PhpCsFixer\Fixer\\');
  90. }
  91. );
  92. sort($fixerClasses);
  93. $fixers = array_map(
  94. static fn (FixerInterface $fixer): string => \get_class($fixer),
  95. $factory->getFixers()
  96. );
  97. sort($fixers);
  98. self::assertSame($fixerClasses, $fixers);
  99. }
  100. /**
  101. * @covers \PhpCsFixer\FixerFactory::getFixers
  102. */
  103. public function testThatFixersAreSorted(): void
  104. {
  105. $factory = new FixerFactory();
  106. $fxs = [
  107. $this->createFixerDouble('f1', 0),
  108. $this->createFixerDouble('f2', -10),
  109. $this->createFixerDouble('f3', 10),
  110. $this->createFixerDouble('f4', -10),
  111. ];
  112. foreach ($fxs as $fx) {
  113. $factory->registerFixer($fx, false);
  114. }
  115. // There are no rules that forces $fxs[1] to be prioritized before $fxs[3]. We should not test against that
  116. self::assertSame([$fxs[2], $fxs[0]], \array_slice($factory->getFixers(), 0, 2));
  117. }
  118. /**
  119. * @covers \PhpCsFixer\FixerFactory::getFixers
  120. * @covers \PhpCsFixer\FixerFactory::registerCustomFixers
  121. * @covers \PhpCsFixer\FixerFactory::registerFixer
  122. */
  123. public function testThatCanRegisterAndGetFixers(): void
  124. {
  125. $factory = new FixerFactory();
  126. $f1 = $this->createFixerDouble('f1');
  127. $f2 = $this->createFixerDouble('Foo/f2');
  128. $f3 = $this->createFixerDouble('Foo/f3');
  129. $factory->registerFixer($f1, false);
  130. $factory->registerCustomFixers([$f2, $f3]);
  131. self::assertTrue(\in_array($f1, $factory->getFixers(), true));
  132. self::assertTrue(\in_array($f2, $factory->getFixers(), true));
  133. self::assertTrue(\in_array($f3, $factory->getFixers(), true));
  134. }
  135. /**
  136. * @covers \PhpCsFixer\FixerFactory::registerFixer
  137. */
  138. public function testRegisterFixerWithOccupiedName(): void
  139. {
  140. $this->expectException(\UnexpectedValueException::class);
  141. $this->expectExceptionMessage('Fixer named "non_unique_name" is already registered.');
  142. $factory = new FixerFactory();
  143. $f1 = $this->createFixerDouble('non_unique_name');
  144. $f2 = $this->createFixerDouble('non_unique_name');
  145. $factory->registerFixer($f1, false);
  146. $factory->registerFixer($f2, false);
  147. }
  148. /**
  149. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  150. */
  151. public function testUseRuleSet(): void
  152. {
  153. $factory = (new FixerFactory())
  154. ->registerBuiltInFixers()
  155. ->useRuleSet(new RuleSet([]))
  156. ;
  157. self::assertCount(0, $factory->getFixers());
  158. $factory = (new FixerFactory())
  159. ->registerBuiltInFixers()
  160. ->useRuleSet(new RuleSet(['strict_comparison' => true, 'blank_line_before_statement' => false]))
  161. ;
  162. $fixers = $factory->getFixers();
  163. self::assertCount(1, $fixers);
  164. self::assertSame('strict_comparison', $fixers[0]->getName());
  165. }
  166. /**
  167. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  168. */
  169. public function testUseRuleSetWithNonExistingRule(): void
  170. {
  171. $this->expectException(\UnexpectedValueException::class);
  172. $this->expectExceptionMessage('Rule "non_existing_rule" does not exist.');
  173. $factory = (new FixerFactory())
  174. ->registerBuiltInFixers()
  175. ->useRuleSet(new RuleSet(['non_existing_rule' => true]))
  176. ;
  177. $factory->getFixers();
  178. }
  179. /**
  180. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  181. */
  182. public function testUseRuleSetWithInvalidConfigForRule(): void
  183. {
  184. $this->expectException(InvalidFixerConfigurationException::class);
  185. $this->expectExceptionMessage('Configuration must be an array and may not be empty.');
  186. $testRuleSet = new class implements RuleSetInterface {
  187. public function __construct(array $set = [])
  188. {
  189. if ([] !== $set) {
  190. throw new \RuntimeException('Set is not used in test.');
  191. }
  192. }
  193. /**
  194. * @return array<string, mixed>
  195. */
  196. public function getRuleConfiguration(string $rule): ?array
  197. {
  198. if (!$this->hasRule($rule)) {
  199. throw new \InvalidArgumentException(\sprintf('Rule "%s" is not in the set.', $rule));
  200. }
  201. if (true === $this->getRules()[$rule]) {
  202. return null;
  203. }
  204. return $this->getRules()[$rule];
  205. }
  206. public function getRules(): array
  207. {
  208. return ['header_comment' => []];
  209. }
  210. public function hasRule(string $rule): bool
  211. {
  212. return isset($this->getRules()[$rule]);
  213. }
  214. };
  215. $factory = (new FixerFactory())
  216. ->registerBuiltInFixers()
  217. ->useRuleSet($testRuleSet)
  218. ;
  219. $factory->getFixers();
  220. }
  221. public function testHasRule(): void
  222. {
  223. $factory = new FixerFactory();
  224. $f1 = $this->createFixerDouble('f1');
  225. $f2 = $this->createFixerDouble('Foo/f2');
  226. $f3 = $this->createFixerDouble('Foo/f3');
  227. $factory->registerFixer($f1, false);
  228. $factory->registerCustomFixers([$f2, $f3]);
  229. self::assertTrue($factory->hasRule('f1'), 'Should have f1 fixer');
  230. self::assertTrue($factory->hasRule('Foo/f2'), 'Should have f2 fixer');
  231. self::assertTrue($factory->hasRule('Foo/f3'), 'Should have f3 fixer');
  232. self::assertFalse($factory->hasRule('dummy'), 'Should not have dummy fixer');
  233. }
  234. public function testHasRuleWithChangedRuleSet(): void
  235. {
  236. $factory = new FixerFactory();
  237. $f1 = $this->createFixerDouble('f1');
  238. $f2 = $this->createFixerDouble('f2');
  239. $factory->registerFixer($f1, false);
  240. $factory->registerFixer($f2, false);
  241. self::assertTrue($factory->hasRule('f1'), 'Should have f1 fixer');
  242. self::assertTrue($factory->hasRule('f2'), 'Should have f2 fixer');
  243. $factory->useRuleSet(new RuleSet(['f2' => true]));
  244. self::assertFalse($factory->hasRule('f1'), 'Should not have f1 fixer');
  245. self::assertTrue($factory->hasRule('f2'), 'Should have f2 fixer');
  246. }
  247. /**
  248. * @dataProvider provideConflictingFixersCases
  249. */
  250. public function testConflictingFixers(RuleSet $ruleSet): void
  251. {
  252. $this->expectException(\UnexpectedValueException::class);
  253. $this->expectExceptionMessageMatches('#^Rule contains conflicting fixers:\n#');
  254. (new FixerFactory())
  255. ->registerBuiltInFixers()->useRuleSet($ruleSet)
  256. ;
  257. }
  258. /**
  259. * @return iterable<array{RuleSet}>
  260. */
  261. public static function provideConflictingFixersCases(): iterable
  262. {
  263. yield [new RuleSet(['no_blank_lines_before_namespace' => true, 'single_blank_line_before_namespace' => true])];
  264. yield [new RuleSet(['single_blank_line_before_namespace' => true, 'no_blank_lines_before_namespace' => true])];
  265. }
  266. public function testNoDoubleConflictReporting(): void
  267. {
  268. $factory = new FixerFactory();
  269. self::assertSame(
  270. 'Rule contains conflicting fixers:
  271. - "a" with "b"
  272. - "c" with "d", "e" and "f"
  273. - "d" with "g" and "h"
  274. - "e" with "a"',
  275. \Closure::bind(static function (FixerFactory $factory): string {
  276. return $factory->generateConflictMessage([
  277. 'a' => ['b'],
  278. 'b' => ['a'],
  279. 'c' => ['d', 'e', 'f'],
  280. 'd' => ['c', 'g', 'h'],
  281. 'e' => ['a'],
  282. ]);
  283. }, null, FixerFactory::class)($factory),
  284. );
  285. }
  286. public function testSetWhitespacesConfig(): void
  287. {
  288. $factory = new FixerFactory();
  289. $config = new WhitespacesFixerConfig();
  290. $fixer = new class($config) implements WhitespacesAwareFixerInterface {
  291. private WhitespacesFixerConfig $config;
  292. public function __construct(WhitespacesFixerConfig $config)
  293. {
  294. $this->config = $config;
  295. }
  296. public function isCandidate(Tokens $tokens): bool
  297. {
  298. throw new \LogicException('Not implemented.');
  299. }
  300. public function isRisky(): bool
  301. {
  302. throw new \LogicException('Not implemented.');
  303. }
  304. public function fix(\SplFileInfo $file, Tokens $tokens): void
  305. {
  306. throw new \LogicException('Not implemented.');
  307. }
  308. public function getDefinition(): FixerDefinitionInterface
  309. {
  310. throw new \LogicException('Not implemented.');
  311. }
  312. public function getName(): string
  313. {
  314. return 'foo';
  315. }
  316. public function getPriority(): int
  317. {
  318. throw new \LogicException('Not implemented.');
  319. }
  320. public function supports(\SplFileInfo $file): bool
  321. {
  322. throw new \LogicException('Not implemented.');
  323. }
  324. public function setWhitespacesConfig(WhitespacesFixerConfig $config): void
  325. {
  326. TestCase::assertSame($this->config, $config);
  327. }
  328. };
  329. $factory->registerFixer($fixer, false);
  330. $factory->setWhitespacesConfig($config);
  331. }
  332. public function testRegisterFixerInvalidName(): void
  333. {
  334. $factory = new FixerFactory();
  335. $fixer = $this->createFixerDouble('0');
  336. $this->expectException(\UnexpectedValueException::class);
  337. $this->expectExceptionMessage('Fixer named "0" has invalid name.');
  338. $factory->registerFixer($fixer, false);
  339. }
  340. public function testConfigureNonConfigurableFixer(): void
  341. {
  342. $factory = new FixerFactory();
  343. $fixer = $this->createFixerDouble('non_configurable');
  344. $factory->registerFixer($fixer, false);
  345. $this->expectException(InvalidFixerConfigurationException::class);
  346. $this->expectExceptionMessage('[non_configurable] Is not configurable.');
  347. $factory->useRuleSet(new RuleSet([
  348. 'non_configurable' => ['bar' => 'baz'],
  349. ]));
  350. }
  351. /**
  352. * @param mixed $value
  353. *
  354. * @dataProvider provideConfigureFixerWithNonArrayCases
  355. */
  356. public function testConfigureFixerWithNonArray($value): void
  357. {
  358. $factory = new FixerFactory();
  359. $fixer = new class implements ConfigurableFixerInterface {
  360. public function configure(array $configuration): void
  361. {
  362. throw new \LogicException('Not implemented.');
  363. }
  364. public function getConfigurationDefinition(): FixerConfigurationResolverInterface
  365. {
  366. throw new \LogicException('Not implemented.');
  367. }
  368. public function isCandidate(Tokens $tokens): bool
  369. {
  370. throw new \LogicException('Not implemented.');
  371. }
  372. public function isRisky(): bool
  373. {
  374. throw new \LogicException('Not implemented.');
  375. }
  376. public function fix(\SplFileInfo $file, Tokens $tokens): void
  377. {
  378. throw new \LogicException('Not implemented.');
  379. }
  380. public function getDefinition(): FixerDefinitionInterface
  381. {
  382. throw new \LogicException('Not implemented.');
  383. }
  384. public function getName(): string
  385. {
  386. return 'foo';
  387. }
  388. public function getPriority(): int
  389. {
  390. throw new \LogicException('Not implemented.');
  391. }
  392. public function supports(\SplFileInfo $file): bool
  393. {
  394. throw new \LogicException('Not implemented.');
  395. }
  396. };
  397. $factory->registerFixer($fixer, false);
  398. $this->expectException(InvalidFixerConfigurationException::class);
  399. $this->expectExceptionMessage(
  400. '[foo] Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'
  401. );
  402. $factory->useRuleSet(new RuleSet([
  403. 'foo' => $value,
  404. ]));
  405. }
  406. /**
  407. * @return iterable<array{float|int|\stdClass|string}>
  408. */
  409. public static function provideConfigureFixerWithNonArrayCases(): iterable
  410. {
  411. yield ['bar'];
  412. yield [new \stdClass()];
  413. yield [5];
  414. yield [5.5];
  415. }
  416. public function testConfigurableFixerIsConfigured(): void
  417. {
  418. $fixer = new class implements ConfigurableFixerInterface {
  419. public function configure(array $configuration): void
  420. {
  421. TestCase::assertSame(['bar' => 'baz'], $configuration);
  422. }
  423. public function getConfigurationDefinition(): FixerConfigurationResolverInterface
  424. {
  425. throw new \LogicException('Not implemented.');
  426. }
  427. public function isCandidate(Tokens $tokens): bool
  428. {
  429. throw new \LogicException('Not implemented.');
  430. }
  431. public function isRisky(): bool
  432. {
  433. throw new \LogicException('Not implemented.');
  434. }
  435. public function fix(\SplFileInfo $file, Tokens $tokens): void
  436. {
  437. throw new \LogicException('Not implemented.');
  438. }
  439. public function getDefinition(): FixerDefinitionInterface
  440. {
  441. throw new \LogicException('Not implemented.');
  442. }
  443. public function getName(): string
  444. {
  445. return 'foo';
  446. }
  447. public function getPriority(): int
  448. {
  449. throw new \LogicException('Not implemented.');
  450. }
  451. public function supports(\SplFileInfo $file): bool
  452. {
  453. throw new \LogicException('Not implemented.');
  454. }
  455. };
  456. $factory = new FixerFactory();
  457. $factory->registerFixer($fixer, false);
  458. $factory->useRuleSet(new RuleSet([
  459. 'foo' => ['bar' => 'baz'],
  460. ]));
  461. }
  462. private function createFixerDouble(string $name, int $priority = 0): FixerInterface
  463. {
  464. return new class($name, $priority) implements FixerInterface {
  465. private string $name;
  466. private int $priority;
  467. public function __construct(string $name, int $priority)
  468. {
  469. $this->name = $name;
  470. $this->priority = $priority;
  471. }
  472. public function isCandidate(Tokens $tokens): bool
  473. {
  474. throw new \LogicException('Not implemented.');
  475. }
  476. public function isRisky(): bool
  477. {
  478. throw new \LogicException('Not implemented.');
  479. }
  480. public function fix(\SplFileInfo $file, Tokens $tokens): void
  481. {
  482. throw new \LogicException('Not implemented.');
  483. }
  484. public function getDefinition(): FixerDefinitionInterface
  485. {
  486. throw new \LogicException('Not implemented.');
  487. }
  488. public function getName(): string
  489. {
  490. return $this->name;
  491. }
  492. public function getPriority(): int
  493. {
  494. return $this->priority;
  495. }
  496. public function supports(\SplFileInfo $file): bool
  497. {
  498. throw new \LogicException('Not implemented.');
  499. }
  500. };
  501. }
  502. }