RuleSetTest.php 17 KB

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