FixerFactoryTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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\FixerFactory;
  17. use PhpCsFixer\RuleSet\RuleSet;
  18. use PhpCsFixer\RuleSet\RuleSetInterface;
  19. use PhpCsFixer\WhitespacesFixerConfig;
  20. /**
  21. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  22. *
  23. * @internal
  24. *
  25. * @covers \PhpCsFixer\FixerFactory
  26. */
  27. final class FixerFactoryTest extends TestCase
  28. {
  29. public function testInterfaceIsFluent(): void
  30. {
  31. $factory = new FixerFactory();
  32. $testInstance = $factory->registerBuiltInFixers();
  33. self::assertSame($factory, $testInstance);
  34. $testInstance = $factory->registerCustomFixers(
  35. [$this->createFixerDouble('Foo/f1'), $this->createFixerDouble('Foo/f2')]
  36. );
  37. self::assertSame($factory, $testInstance);
  38. $testInstance = $factory->registerFixer(
  39. $this->createFixerDouble('f3'),
  40. false
  41. );
  42. self::assertSame($factory, $testInstance);
  43. $ruleSetProphecy = $this->prophesize(RuleSetInterface::class);
  44. $ruleSetProphecy->getRules()->willReturn([]);
  45. $testInstance = $factory->useRuleSet(
  46. $ruleSetProphecy->reveal()
  47. );
  48. self::assertSame($factory, $testInstance);
  49. }
  50. /**
  51. * @covers \PhpCsFixer\FixerFactory::registerBuiltInFixers
  52. */
  53. public function testRegisterBuiltInFixers(): void
  54. {
  55. $factory = new FixerFactory();
  56. $factory->registerBuiltInFixers();
  57. $fixerClasses = array_filter(
  58. get_declared_classes(),
  59. static function (string $className): bool {
  60. $class = new \ReflectionClass($className);
  61. return !$class->isAbstract() && $class->implementsInterface(FixerInterface::class) && str_starts_with($class->getNamespaceName(), 'PhpCsFixer\\Fixer\\');
  62. }
  63. );
  64. sort($fixerClasses);
  65. $fixers = array_map(
  66. static fn (FixerInterface $fixer): string => \get_class($fixer),
  67. $factory->getFixers()
  68. );
  69. sort($fixers);
  70. self::assertSame($fixerClasses, $fixers);
  71. }
  72. /**
  73. * @covers \PhpCsFixer\FixerFactory::getFixers
  74. */
  75. public function testThatFixersAreSorted(): void
  76. {
  77. $factory = new FixerFactory();
  78. $fxs = [
  79. $this->createFixerDouble('f1', 0),
  80. $this->createFixerDouble('f2', -10),
  81. $this->createFixerDouble('f3', 10),
  82. $this->createFixerDouble('f4', -10),
  83. ];
  84. foreach ($fxs as $fx) {
  85. $factory->registerFixer($fx, false);
  86. }
  87. // There are no rules that forces $fxs[1] to be prioritized before $fxs[3]. We should not test against that
  88. self::assertSame([$fxs[2], $fxs[0]], \array_slice($factory->getFixers(), 0, 2));
  89. }
  90. /**
  91. * @covers \PhpCsFixer\FixerFactory::getFixers
  92. * @covers \PhpCsFixer\FixerFactory::registerCustomFixers
  93. * @covers \PhpCsFixer\FixerFactory::registerFixer
  94. */
  95. public function testThatCanRegisterAndGetFixers(): void
  96. {
  97. $factory = new FixerFactory();
  98. $f1 = $this->createFixerDouble('f1');
  99. $f2 = $this->createFixerDouble('Foo/f2');
  100. $f3 = $this->createFixerDouble('Foo/f3');
  101. $factory->registerFixer($f1, false);
  102. $factory->registerCustomFixers([$f2, $f3]);
  103. self::assertTrue(\in_array($f1, $factory->getFixers(), true));
  104. self::assertTrue(\in_array($f2, $factory->getFixers(), true));
  105. self::assertTrue(\in_array($f3, $factory->getFixers(), true));
  106. }
  107. /**
  108. * @covers \PhpCsFixer\FixerFactory::registerFixer
  109. */
  110. public function testRegisterFixerWithOccupiedName(): void
  111. {
  112. $this->expectException(\UnexpectedValueException::class);
  113. $this->expectExceptionMessage('Fixer named "non_unique_name" is already registered.');
  114. $factory = new FixerFactory();
  115. $f1 = $this->createFixerDouble('non_unique_name');
  116. $f2 = $this->createFixerDouble('non_unique_name');
  117. $factory->registerFixer($f1, false);
  118. $factory->registerFixer($f2, false);
  119. }
  120. /**
  121. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  122. */
  123. public function testUseRuleSet(): void
  124. {
  125. $factory = (new FixerFactory())
  126. ->registerBuiltInFixers()
  127. ->useRuleSet(new RuleSet([]))
  128. ;
  129. self::assertCount(0, $factory->getFixers());
  130. $factory = (new FixerFactory())
  131. ->registerBuiltInFixers()
  132. ->useRuleSet(new RuleSet(['strict_comparison' => true, 'blank_line_before_statement' => false]))
  133. ;
  134. $fixers = $factory->getFixers();
  135. self::assertCount(1, $fixers);
  136. self::assertSame('strict_comparison', $fixers[0]->getName());
  137. }
  138. /**
  139. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  140. */
  141. public function testUseRuleSetWithNonExistingRule(): void
  142. {
  143. $this->expectException(\UnexpectedValueException::class);
  144. $this->expectExceptionMessage('Rule "non_existing_rule" does not exist.');
  145. $factory = (new FixerFactory())
  146. ->registerBuiltInFixers()
  147. ->useRuleSet(new RuleSet(['non_existing_rule' => true]))
  148. ;
  149. $factory->getFixers();
  150. }
  151. /**
  152. * @covers \PhpCsFixer\FixerFactory::useRuleSet
  153. */
  154. public function testUseRuleSetWithInvalidConfigForRule(): void
  155. {
  156. $this->expectException(InvalidFixerConfigurationException::class);
  157. $this->expectExceptionMessage('Configuration must be an array and may not be empty.');
  158. $testRuleSet = new class() implements RuleSetInterface {
  159. public function __construct(array $set = [])
  160. {
  161. if ([] !== $set) {
  162. throw new \RuntimeException('Set is not used in test.');
  163. }
  164. }
  165. public function getRuleConfiguration(string $rule): ?array
  166. {
  167. return $this->getRules()[$rule];
  168. }
  169. public function getRules(): array
  170. {
  171. return ['header_comment' => []];
  172. }
  173. public function hasRule(string $rule): bool
  174. {
  175. return isset($this->getRules()[$rule]);
  176. }
  177. };
  178. $factory = (new FixerFactory())
  179. ->registerBuiltInFixers()
  180. ->useRuleSet($testRuleSet)
  181. ;
  182. $factory->getFixers();
  183. }
  184. public function testHasRule(): void
  185. {
  186. $factory = new FixerFactory();
  187. $f1 = $this->createFixerDouble('f1');
  188. $f2 = $this->createFixerDouble('Foo/f2');
  189. $f3 = $this->createFixerDouble('Foo/f3');
  190. $factory->registerFixer($f1, false);
  191. $factory->registerCustomFixers([$f2, $f3]);
  192. self::assertTrue($factory->hasRule('f1'), 'Should have f1 fixer');
  193. self::assertTrue($factory->hasRule('Foo/f2'), 'Should have f2 fixer');
  194. self::assertTrue($factory->hasRule('Foo/f3'), 'Should have f3 fixer');
  195. self::assertFalse($factory->hasRule('dummy'), 'Should not have dummy fixer');
  196. }
  197. public function testHasRuleWithChangedRuleSet(): void
  198. {
  199. $factory = new FixerFactory();
  200. $f1 = $this->createFixerDouble('f1');
  201. $f2 = $this->createFixerDouble('f2');
  202. $factory->registerFixer($f1, false);
  203. $factory->registerFixer($f2, false);
  204. self::assertTrue($factory->hasRule('f1'), 'Should have f1 fixer');
  205. self::assertTrue($factory->hasRule('f2'), 'Should have f2 fixer');
  206. $factory->useRuleSet(new RuleSet(['f2' => true]));
  207. self::assertFalse($factory->hasRule('f1'), 'Should not have f1 fixer');
  208. self::assertTrue($factory->hasRule('f2'), 'Should have f2 fixer');
  209. }
  210. /**
  211. * @dataProvider provideConflictingFixersCases
  212. */
  213. public function testConflictingFixers(RuleSet $ruleSet): void
  214. {
  215. $this->expectException(\UnexpectedValueException::class);
  216. $this->expectExceptionMessageMatches('#^Rule contains conflicting fixers:\n#');
  217. (new FixerFactory())
  218. ->registerBuiltInFixers()->useRuleSet($ruleSet)
  219. ;
  220. }
  221. public static function provideConflictingFixersCases(): iterable
  222. {
  223. yield [new RuleSet(['no_blank_lines_before_namespace' => true, 'single_blank_line_before_namespace' => true])];
  224. yield [new RuleSet(['single_blank_line_before_namespace' => true, 'no_blank_lines_before_namespace' => true])];
  225. }
  226. public function testNoDoubleConflictReporting(): void
  227. {
  228. $factory = new FixerFactory();
  229. $method = new \ReflectionMethod($factory, 'generateConflictMessage');
  230. $method->setAccessible(true);
  231. self::assertSame(
  232. 'Rule contains conflicting fixers:
  233. - "a" with "b"
  234. - "c" with "d", "e" and "f"
  235. - "d" with "g" and "h"
  236. - "e" with "a"',
  237. $method->invoke(
  238. $factory,
  239. [
  240. 'a' => ['b'],
  241. 'b' => ['a'],
  242. 'c' => ['d', 'e', 'f'],
  243. 'd' => ['c', 'g', 'h'],
  244. 'e' => ['a'],
  245. ]
  246. )
  247. );
  248. }
  249. public function testSetWhitespacesConfig(): void
  250. {
  251. $factory = new FixerFactory();
  252. $config = new WhitespacesFixerConfig();
  253. $fixer = $this->prophesize(\PhpCsFixer\Fixer\WhitespacesAwareFixerInterface::class);
  254. $fixer->getName()->willReturn('foo');
  255. $fixer->setWhitespacesConfig($config)->shouldBeCalled();
  256. $factory->registerFixer($fixer->reveal(), false);
  257. $factory->setWhitespacesConfig($config);
  258. }
  259. public function testRegisterFixerInvalidName(): void
  260. {
  261. $factory = new FixerFactory();
  262. $fixer = $this->createFixerDouble('0');
  263. $this->expectException(\UnexpectedValueException::class);
  264. $this->expectExceptionMessage('Fixer named "0" has invalid name.');
  265. $factory->registerFixer($fixer, false);
  266. }
  267. public function testConfigureNonConfigurableFixer(): void
  268. {
  269. $factory = new FixerFactory();
  270. $fixer = $this->createFixerDouble('non_configurable');
  271. $factory->registerFixer($fixer, false);
  272. $this->expectException(InvalidFixerConfigurationException::class);
  273. $this->expectExceptionMessage('[non_configurable] Is not configurable.');
  274. $factory->useRuleSet(new RuleSet([
  275. 'non_configurable' => ['bar' => 'baz'],
  276. ]));
  277. }
  278. /**
  279. * @param mixed $value
  280. *
  281. * @dataProvider provideConfigureFixerWithNonArrayCases
  282. */
  283. public function testConfigureFixerWithNonArray($value): void
  284. {
  285. $factory = new FixerFactory();
  286. $fixer = $this->prophesize(ConfigurableFixerInterface::class);
  287. $fixer->getName()->willReturn('foo');
  288. $factory->registerFixer($fixer->reveal(), false);
  289. $this->expectException(InvalidFixerConfigurationException::class);
  290. $this->expectExceptionMessage(
  291. '[foo] Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'
  292. );
  293. $factory->useRuleSet(new RuleSet([
  294. 'foo' => $value,
  295. ]));
  296. }
  297. public static function provideConfigureFixerWithNonArrayCases(): iterable
  298. {
  299. yield ['bar'];
  300. yield [new \stdClass()];
  301. yield [5];
  302. yield [5.5];
  303. }
  304. public function testConfigurableFixerIsConfigured(): void
  305. {
  306. $fixer = $this->prophesize(ConfigurableFixerInterface::class);
  307. $fixer->getName()->willReturn('foo');
  308. $fixer->configure(['bar' => 'baz'])->shouldBeCalled();
  309. $factory = new FixerFactory();
  310. $factory->registerFixer($fixer->reveal(), false);
  311. $factory->useRuleSet(new RuleSet([
  312. 'foo' => ['bar' => 'baz'],
  313. ]));
  314. }
  315. private function createFixerDouble(string $name, int $priority = 0): FixerInterface
  316. {
  317. $fixer = $this->prophesize(\PhpCsFixer\Fixer\FixerInterface::class);
  318. $fixer->getName()->willReturn($name);
  319. $fixer->getPriority()->willReturn($priority);
  320. return $fixer->reveal();
  321. }
  322. }