FixerFactoryTest.php 19 KB

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