FixerFactoryTest.php 18 KB

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