RuleSetTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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\RuleSet;
  13. use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  16. use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion;
  17. use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface;
  18. use PhpCsFixer\FixerFactory;
  19. use PhpCsFixer\RuleSet\RuleSet;
  20. use PhpCsFixer\RuleSet\RuleSetDescriptionInterface;
  21. use PhpCsFixer\RuleSet\RuleSets;
  22. use PhpCsFixer\Tests\Test\TestCaseUtils;
  23. use PhpCsFixer\Tests\TestCase;
  24. /**
  25. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  26. *
  27. * @internal
  28. *
  29. * @group legacy
  30. *
  31. * @covers \PhpCsFixer\RuleSet\RuleSet
  32. */
  33. final class RuleSetTest extends TestCase
  34. {
  35. /**
  36. * Options for which order of array elements matters.
  37. *
  38. * @var list<string>
  39. */
  40. private const ORDER_MATTERS = [
  41. 'ordered_imports.imports_order',
  42. 'phpdoc_order.order',
  43. ];
  44. /**
  45. * @param array<string, mixed>|true $ruleConfig
  46. *
  47. * @dataProvider provideAllRulesFromSetsCases
  48. */
  49. public function testIfAllRulesInSetsExists(string $setName, string $ruleName, $ruleConfig): void
  50. {
  51. $factory = new FixerFactory();
  52. $factory->registerBuiltInFixers();
  53. $fixers = [];
  54. foreach ($factory->getFixers() as $fixer) {
  55. $fixers[$fixer->getName()] = $fixer;
  56. }
  57. self::assertArrayHasKey($ruleName, $fixers, \sprintf('RuleSet "%s" contains unknown rule.', $setName));
  58. if (true === $ruleConfig) {
  59. return; // rule doesn't need configuration.
  60. }
  61. $fixer = $fixers[$ruleName];
  62. self::assertInstanceOf(ConfigurableFixerInterface::class, $fixer, \sprintf('RuleSet "%s" contains configuration for rule "%s" which cannot be configured.', $setName, $ruleName));
  63. try {
  64. $fixer->configure($ruleConfig); // test fixer accepts the configuration
  65. } catch (InvalidForEnvFixerConfigurationException $exception) {
  66. // ignore
  67. }
  68. }
  69. /**
  70. * @param array<string, mixed>|true $ruleConfig
  71. *
  72. * @dataProvider provideAllRulesFromSetsCases
  73. */
  74. public function testThatDefaultConfigIsNotPassed(string $setName, string $ruleName, $ruleConfig): void
  75. {
  76. $fixer = TestCaseUtils::getFixerByName($ruleName);
  77. if (!$fixer instanceof ConfigurableFixerInterface || \is_bool($ruleConfig)) {
  78. $this->expectNotToPerformAssertions();
  79. return;
  80. }
  81. $defaultConfig = [];
  82. foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) {
  83. if ($option instanceof DeprecatedFixerOptionInterface) {
  84. continue;
  85. }
  86. $defaultConfig[$option->getName()] = $option->getDefault();
  87. }
  88. self::assertNotSame(
  89. $this->sortNestedArray($defaultConfig, $ruleName),
  90. $this->sortNestedArray($ruleConfig, $ruleName),
  91. \sprintf('Rule "%s" (in RuleSet "%s") has default config passed.', $ruleName, $setName)
  92. );
  93. }
  94. /**
  95. * @dataProvider provideAllRulesFromSetsCases
  96. */
  97. public function testThatThereIsNoDeprecatedFixerInRuleSet(string $setName, string $ruleName): void
  98. {
  99. $fixer = TestCaseUtils::getFixerByName($ruleName);
  100. self::assertNotInstanceOf(DeprecatedFixerInterface::class, $fixer, \sprintf('RuleSet "%s" contains deprecated rule "%s".', $setName, $ruleName));
  101. }
  102. public static function provideAllRulesFromSetsCases(): iterable
  103. {
  104. foreach (RuleSets::getSetDefinitionNames() as $setName) {
  105. $ruleSet = new RuleSet([$setName => true]);
  106. foreach ($ruleSet->getRules() as $rule => $config) {
  107. yield $setName.':'.$rule => [
  108. $setName,
  109. $rule,
  110. $config,
  111. ];
  112. }
  113. }
  114. }
  115. public function testGetBuildInSetDefinitionNames(): void
  116. {
  117. $setNames = RuleSets::getSetDefinitionNames();
  118. self::assertNotEmpty($setNames);
  119. }
  120. public function testResolveRulesWithInvalidSet(): void
  121. {
  122. $this->expectException(\InvalidArgumentException::class);
  123. $this->expectExceptionMessage('Set "@foo" does not exist.');
  124. new RuleSet(['@foo' => true]);
  125. }
  126. public function testResolveRulesWithMissingRuleValue(): void
  127. {
  128. $this->expectException(\InvalidArgumentException::class);
  129. $this->expectExceptionMessage('Missing value for "braces" rule/set.');
  130. // @phpstan-ignore-next-line
  131. new RuleSet(['braces']);
  132. }
  133. public function testResolveRulesWithSet(): void
  134. {
  135. $ruleSet = new RuleSet([
  136. '@PSR1' => true,
  137. 'braces' => true,
  138. 'encoding' => false,
  139. 'line_ending' => true,
  140. 'strict_comparison' => true,
  141. ]);
  142. self::assertSameRules(
  143. [
  144. 'braces' => true,
  145. 'full_opening_tag' => true,
  146. 'line_ending' => true,
  147. 'strict_comparison' => true,
  148. ],
  149. $ruleSet->getRules()
  150. );
  151. }
  152. public function testResolveRulesWithNestedSet(): void
  153. {
  154. $ruleSet = new RuleSet([
  155. '@PHP70Migration' => true,
  156. 'strict_comparison' => true,
  157. ]);
  158. self::assertSameRules(
  159. [
  160. 'array_syntax' => true,
  161. 'strict_comparison' => true,
  162. 'ternary_to_null_coalescing' => true,
  163. ],
  164. $ruleSet->getRules()
  165. );
  166. }
  167. public function testResolveRulesWithDisabledSet(): void
  168. {
  169. $ruleSet = new RuleSet([
  170. '@PHP70Migration' => true,
  171. '@PHP54Migration' => false,
  172. 'strict_comparison' => true,
  173. ]);
  174. self::assertSameRules(
  175. [
  176. 'strict_comparison' => true,
  177. 'ternary_to_null_coalescing' => true,
  178. ],
  179. $ruleSet->getRules()
  180. );
  181. }
  182. /**
  183. * @param array<string, array<string, mixed>|bool> $set
  184. *
  185. * @dataProvider provideRiskyRulesInSetCases
  186. */
  187. public function testRiskyRulesInSet(array $set, bool $safe): void
  188. {
  189. /** @TODO 4.0 Remove this expectations */
  190. $expectedDeprecations = [
  191. '@PER' => 'Rule set "@PER" is deprecated. Use "@PER-CS" instead.',
  192. '@PER:risky' => 'Rule set "@PER:risky" is deprecated. Use "@PER-CS:risky" instead.',
  193. ];
  194. if (\array_key_exists(array_key_first($set), $expectedDeprecations)) {
  195. $this->expectDeprecation($expectedDeprecations[array_key_first($set)]);
  196. }
  197. try {
  198. $fixers = (new FixerFactory())
  199. ->registerBuiltInFixers()
  200. ->useRuleSet(new RuleSet($set))
  201. ->getFixers()
  202. ;
  203. } catch (InvalidForEnvFixerConfigurationException $exception) {
  204. self::markTestSkipped($exception->getMessage());
  205. }
  206. $fixerNames = [];
  207. foreach ($fixers as $fixer) {
  208. if ($safe === $fixer->isRisky()) {
  209. $fixerNames[] = $fixer->getName();
  210. }
  211. }
  212. self::assertCount(
  213. 0,
  214. $fixerNames,
  215. \sprintf(
  216. 'Set should only contain %s fixers, got: \'%s\'.',
  217. $safe ? 'safe' : 'risky',
  218. implode('\', \'', $fixerNames)
  219. )
  220. );
  221. }
  222. public static function provideRiskyRulesInSetCases(): iterable
  223. {
  224. foreach (RuleSets::getSetDefinitionNames() as $name) {
  225. yield $name => [
  226. [$name => true],
  227. !str_contains($name, ':risky'),
  228. ];
  229. }
  230. yield '@Symfony:risky_and_@Symfony' => [
  231. [
  232. '@Symfony:risky' => true,
  233. '@Symfony' => false,
  234. ],
  235. false,
  236. ];
  237. }
  238. public function testInvalidConfigNestedSets(): void
  239. {
  240. $this->expectException(\UnexpectedValueException::class);
  241. $this->expectExceptionMessageMatches('#^Nested rule set "@PSR1" configuration must be a boolean\.$#');
  242. new RuleSet(
  243. ['@PSR1' => ['@PSR2' => 'no']]
  244. );
  245. }
  246. public function testGetMissingRuleConfiguration(): void
  247. {
  248. $ruleSet = new RuleSet();
  249. $this->expectException(\InvalidArgumentException::class);
  250. $this->expectExceptionMessageMatches('#^Rule "_not_exists" is not in the set\.$#');
  251. $ruleSet->getRuleConfiguration('_not_exists');
  252. }
  253. /**
  254. * @dataProvider provideDuplicateRuleConfigurationInSetDefinitionsCases
  255. */
  256. public function testDuplicateRuleConfigurationInSetDefinitions(RuleSetDescriptionInterface $set): void
  257. {
  258. $rules = [];
  259. $setRules = [];
  260. foreach ($set->getRules() as $ruleName => $ruleConfig) {
  261. if (str_starts_with($ruleName, '@')) {
  262. if (true !== $ruleConfig && false !== $ruleConfig) {
  263. throw new \LogicException('Disallowed configuration for RuleSet.');
  264. }
  265. $setRules = array_merge($setRules, $this->resolveSet($ruleName, $ruleConfig));
  266. } else {
  267. $rules[$ruleName] = $ruleConfig;
  268. }
  269. }
  270. $duplicates = [];
  271. foreach ($rules as $ruleName => $ruleConfig) {
  272. if (!\array_key_exists($ruleName, $setRules)) {
  273. continue;
  274. }
  275. if ($ruleConfig !== $setRules[$ruleName]) {
  276. continue;
  277. }
  278. $duplicates[] = $ruleName;
  279. }
  280. if (0 === \count($duplicates)) {
  281. $this->addToAssertionCount(1);
  282. return;
  283. }
  284. self::fail(\sprintf(
  285. '"%s" defines rules the same as it extends from: %s',
  286. $set->getName(),
  287. implode(', ', $duplicates),
  288. ));
  289. }
  290. /**
  291. * @return iterable<string, array{RuleSetDescriptionInterface}>
  292. */
  293. public static function provideDuplicateRuleConfigurationInSetDefinitionsCases(): iterable
  294. {
  295. foreach (RuleSets::getSetDefinitions() as $name => $set) {
  296. yield $name => [$set];
  297. }
  298. }
  299. /**
  300. * @dataProvider providePhpUnitTargetVersionHasSetCases
  301. */
  302. public function testPhpUnitTargetVersionHasSet(string $version): void
  303. {
  304. self::assertContains(
  305. \sprintf('@PHPUnit%sMigration:risky', str_replace('.', '', $version)),
  306. RuleSets::getSetDefinitionNames(),
  307. \sprintf('PHPUnit target version %s is missing its set in %s.', $version, RuleSet::class)
  308. );
  309. }
  310. /**
  311. * @return iterable<array{string}>
  312. */
  313. public static function providePhpUnitTargetVersionHasSetCases(): iterable
  314. {
  315. foreach ((new \ReflectionClass(PhpUnitTargetVersion::class))->getConstants() as $constant) {
  316. if ('newest' === $constant) {
  317. continue;
  318. }
  319. yield [$constant];
  320. }
  321. }
  322. public function testEmptyName(): void
  323. {
  324. $this->expectException(\InvalidArgumentException::class);
  325. $this->expectExceptionMessage('Rule/set name must not be empty.');
  326. new RuleSet(['' => true]);
  327. }
  328. public function testInvalidConfig(): void
  329. {
  330. $this->expectException(\InvalidArgumentException::class);
  331. $this->expectExceptionMessage('[@Symfony:risky] Set must be enabled (true) or disabled (false). Other values are not allowed. To disable the set, use "FALSE" instead of "NULL".');
  332. // @phpstan-ignore-next-line
  333. new RuleSet(['@Symfony:risky' => null]);
  334. }
  335. /**
  336. * @param array<array-key, mixed> $array
  337. *
  338. * @return array<array-key, mixed> $array
  339. */
  340. private function sortNestedArray(array $array, string $ruleName): array
  341. {
  342. $this->doSort($array, $ruleName);
  343. return $array;
  344. }
  345. /**
  346. * Sorts an array of fixer definition recursively.
  347. *
  348. * Sometimes keys are all string, sometimes they are integers - we need to account for that.
  349. *
  350. * @param array<array-key, mixed> $data
  351. */
  352. private function doSort(array &$data, string $path): void
  353. {
  354. // if order matters do not sort!
  355. if (\in_array($path, self::ORDER_MATTERS, true)) {
  356. return;
  357. }
  358. $keys = array_keys($data);
  359. if ($this->allInteger($keys)) {
  360. sort($data);
  361. } else {
  362. ksort($data);
  363. }
  364. foreach ($data as $key => $value) {
  365. if (\is_array($value)) {
  366. $this->doSort(
  367. $data[$key],
  368. $path.('' !== $path ? '.' : '').$key
  369. );
  370. }
  371. }
  372. }
  373. /**
  374. * @param array<int|string, mixed> $values
  375. */
  376. private function allInteger(array $values): bool
  377. {
  378. foreach ($values as $value) {
  379. if (!\is_int($value)) {
  380. return false;
  381. }
  382. }
  383. return true;
  384. }
  385. /**
  386. * @return array<string, array<string, mixed>|bool>
  387. */
  388. private function resolveSet(string $setName, bool $setValue): array
  389. {
  390. $rules = RuleSets::getSetDefinition($setName)->getRules();
  391. foreach ($rules as $name => $value) {
  392. if (str_starts_with($name, '@')) {
  393. $set = $this->resolveSet($name, $setValue);
  394. unset($rules[$name]);
  395. $rules = array_merge($rules, $set);
  396. } elseif (!$setValue) {
  397. $rules[$name] = false;
  398. } else {
  399. $rules[$name] = $value;
  400. }
  401. }
  402. return $rules;
  403. }
  404. /**
  405. * @param array<string, array<string, mixed>|bool> $expected
  406. * @param array<string, array<string, mixed>|bool> $actual
  407. */
  408. private static function assertSameRules(array $expected, array $actual): void
  409. {
  410. ksort($expected);
  411. ksort($actual);
  412. self::assertSame($expected, $actual);
  413. }
  414. }