FixerFactoryTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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 fn (FixerFactory $factory): string => $factory->generateConflictMessage([
  276. 'a' => ['b'],
  277. 'b' => ['a'],
  278. 'c' => ['d', 'e', 'f'],
  279. 'd' => ['c', 'g', 'h'],
  280. 'e' => ['a'],
  281. ]), null, FixerFactory::class)($factory),
  282. );
  283. }
  284. public function testSetWhitespacesConfig(): void
  285. {
  286. $factory = new FixerFactory();
  287. $config = new WhitespacesFixerConfig();
  288. $fixer = new class($config) implements WhitespacesAwareFixerInterface {
  289. private WhitespacesFixerConfig $config;
  290. public function __construct(WhitespacesFixerConfig $config)
  291. {
  292. $this->config = $config;
  293. }
  294. public function isCandidate(Tokens $tokens): bool
  295. {
  296. throw new \LogicException('Not implemented.');
  297. }
  298. public function isRisky(): bool
  299. {
  300. throw new \LogicException('Not implemented.');
  301. }
  302. public function fix(\SplFileInfo $file, Tokens $tokens): void
  303. {
  304. throw new \LogicException('Not implemented.');
  305. }
  306. public function getDefinition(): FixerDefinitionInterface
  307. {
  308. throw new \LogicException('Not implemented.');
  309. }
  310. public function getName(): string
  311. {
  312. return 'foo';
  313. }
  314. public function getPriority(): int
  315. {
  316. throw new \LogicException('Not implemented.');
  317. }
  318. public function supports(\SplFileInfo $file): bool
  319. {
  320. throw new \LogicException('Not implemented.');
  321. }
  322. public function setWhitespacesConfig(WhitespacesFixerConfig $config): void
  323. {
  324. TestCase::assertSame($this->config, $config);
  325. }
  326. };
  327. $factory->registerFixer($fixer, false);
  328. $factory->setWhitespacesConfig($config);
  329. }
  330. public function testRegisterFixerInvalidName(): void
  331. {
  332. $factory = new FixerFactory();
  333. $fixer = $this->createFixerDouble('0');
  334. $this->expectException(\UnexpectedValueException::class);
  335. $this->expectExceptionMessage('Fixer named "0" has invalid name.');
  336. $factory->registerFixer($fixer, false);
  337. }
  338. public function testConfigureNonConfigurableFixer(): void
  339. {
  340. $factory = new FixerFactory();
  341. $fixer = $this->createFixerDouble('non_configurable');
  342. $factory->registerFixer($fixer, false);
  343. $this->expectException(InvalidFixerConfigurationException::class);
  344. $this->expectExceptionMessage('[non_configurable] Is not configurable.');
  345. $factory->useRuleSet(new RuleSet([
  346. 'non_configurable' => ['bar' => 'baz'],
  347. ]));
  348. }
  349. /**
  350. * @param mixed $value
  351. *
  352. * @dataProvider provideConfigureFixerWithNonArrayCases
  353. */
  354. public function testConfigureFixerWithNonArray($value): void
  355. {
  356. $factory = new FixerFactory();
  357. $fixer = new class implements ConfigurableFixerInterface {
  358. public function configure(array $configuration): void
  359. {
  360. throw new \LogicException('Not implemented.');
  361. }
  362. public function getConfigurationDefinition(): FixerConfigurationResolverInterface
  363. {
  364. throw new \LogicException('Not implemented.');
  365. }
  366. public function isCandidate(Tokens $tokens): bool
  367. {
  368. throw new \LogicException('Not implemented.');
  369. }
  370. public function isRisky(): bool
  371. {
  372. throw new \LogicException('Not implemented.');
  373. }
  374. public function fix(\SplFileInfo $file, Tokens $tokens): void
  375. {
  376. throw new \LogicException('Not implemented.');
  377. }
  378. public function getDefinition(): FixerDefinitionInterface
  379. {
  380. throw new \LogicException('Not implemented.');
  381. }
  382. public function getName(): string
  383. {
  384. return 'foo';
  385. }
  386. public function getPriority(): int
  387. {
  388. throw new \LogicException('Not implemented.');
  389. }
  390. public function supports(\SplFileInfo $file): bool
  391. {
  392. throw new \LogicException('Not implemented.');
  393. }
  394. };
  395. $factory->registerFixer($fixer, false);
  396. $this->expectException(InvalidFixerConfigurationException::class);
  397. $this->expectExceptionMessage(
  398. '[foo] Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'
  399. );
  400. $factory->useRuleSet(new RuleSet([
  401. 'foo' => $value,
  402. ]));
  403. }
  404. /**
  405. * @return iterable<array{float|int|\stdClass|string}>
  406. */
  407. public static function provideConfigureFixerWithNonArrayCases(): iterable
  408. {
  409. yield ['bar'];
  410. yield [new \stdClass()];
  411. yield [5];
  412. yield [5.5];
  413. }
  414. public function testConfigurableFixerIsConfigured(): void
  415. {
  416. $fixer = new class implements ConfigurableFixerInterface {
  417. public function configure(array $configuration): void
  418. {
  419. TestCase::assertSame(['bar' => 'baz'], $configuration);
  420. }
  421. public function getConfigurationDefinition(): FixerConfigurationResolverInterface
  422. {
  423. throw new \LogicException('Not implemented.');
  424. }
  425. public function isCandidate(Tokens $tokens): bool
  426. {
  427. throw new \LogicException('Not implemented.');
  428. }
  429. public function isRisky(): bool
  430. {
  431. throw new \LogicException('Not implemented.');
  432. }
  433. public function fix(\SplFileInfo $file, Tokens $tokens): void
  434. {
  435. throw new \LogicException('Not implemented.');
  436. }
  437. public function getDefinition(): FixerDefinitionInterface
  438. {
  439. throw new \LogicException('Not implemented.');
  440. }
  441. public function getName(): string
  442. {
  443. return 'foo';
  444. }
  445. public function getPriority(): int
  446. {
  447. throw new \LogicException('Not implemented.');
  448. }
  449. public function supports(\SplFileInfo $file): bool
  450. {
  451. throw new \LogicException('Not implemented.');
  452. }
  453. };
  454. $factory = new FixerFactory();
  455. $factory->registerFixer($fixer, false);
  456. $factory->useRuleSet(new RuleSet([
  457. 'foo' => ['bar' => 'baz'],
  458. ]));
  459. }
  460. private function createFixerDouble(string $name, int $priority = 0): FixerInterface
  461. {
  462. return new class($name, $priority) implements FixerInterface {
  463. private string $name;
  464. private int $priority;
  465. public function __construct(string $name, int $priority)
  466. {
  467. $this->name = $name;
  468. $this->priority = $priority;
  469. }
  470. public function isCandidate(Tokens $tokens): bool
  471. {
  472. throw new \LogicException('Not implemented.');
  473. }
  474. public function isRisky(): bool
  475. {
  476. throw new \LogicException('Not implemented.');
  477. }
  478. public function fix(\SplFileInfo $file, Tokens $tokens): void
  479. {
  480. throw new \LogicException('Not implemented.');
  481. }
  482. public function getDefinition(): FixerDefinitionInterface
  483. {
  484. throw new \LogicException('Not implemented.');
  485. }
  486. public function getName(): string
  487. {
  488. return $this->name;
  489. }
  490. public function getPriority(): int
  491. {
  492. return $this->priority;
  493. }
  494. public function supports(\SplFileInfo $file): bool
  495. {
  496. throw new \LogicException('Not implemented.');
  497. }
  498. };
  499. }
  500. }