RuleSetTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. '@PSR2' => true,
  156. 'strict_comparison' => true,
  157. ]);
  158. self::assertSameRules(
  159. [
  160. 'blank_line_after_namespace' => true,
  161. 'class_definition' => true,
  162. 'constant_case' => true,
  163. 'control_structure_braces' => true,
  164. 'control_structure_continuation_position' => true,
  165. 'braces_position' => true,
  166. 'elseif' => true,
  167. 'encoding' => true,
  168. 'full_opening_tag' => true,
  169. 'function_declaration' => true,
  170. 'indentation_type' => true,
  171. 'line_ending' => true,
  172. 'lowercase_keywords' => true,
  173. 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'],
  174. 'no_break_comment' => true,
  175. 'no_closing_tag' => true,
  176. 'no_multiple_statements_per_line' => true,
  177. 'no_space_around_double_colon' => true,
  178. 'no_spaces_after_function_name' => true,
  179. 'no_trailing_whitespace' => true,
  180. 'no_trailing_whitespace_in_comment' => true,
  181. 'single_blank_line_at_eof' => true,
  182. 'single_class_element_per_statement' => ['elements' => ['property']],
  183. 'single_import_per_statement' => true,
  184. 'single_line_after_imports' => true,
  185. 'spaces_inside_parentheses' => true,
  186. 'statement_indentation' => true,
  187. 'strict_comparison' => true,
  188. 'switch_case_semicolon_to_colon' => true,
  189. 'switch_case_space' => true,
  190. 'visibility_required' => ['elements' => ['method', 'property']],
  191. ],
  192. $ruleSet->getRules()
  193. );
  194. }
  195. public function testResolveRulesWithDisabledSet(): void
  196. {
  197. $ruleSet = new RuleSet([
  198. '@PSR2' => true,
  199. '@PSR1' => false,
  200. 'encoding' => true,
  201. ]);
  202. self::assertSameRules(
  203. [
  204. 'blank_line_after_namespace' => true,
  205. 'constant_case' => true,
  206. 'class_definition' => true,
  207. 'control_structure_braces' => true,
  208. 'control_structure_continuation_position' => true,
  209. 'braces_position' => true,
  210. 'elseif' => true,
  211. 'encoding' => true,
  212. 'function_declaration' => true,
  213. 'indentation_type' => true,
  214. 'line_ending' => true,
  215. 'lowercase_keywords' => true,
  216. 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'],
  217. 'no_break_comment' => true,
  218. 'no_closing_tag' => true,
  219. 'no_multiple_statements_per_line' => true,
  220. 'no_spaces_after_function_name' => true,
  221. 'no_space_around_double_colon' => true,
  222. 'no_trailing_whitespace' => true,
  223. 'no_trailing_whitespace_in_comment' => true,
  224. 'single_blank_line_at_eof' => true,
  225. 'single_class_element_per_statement' => ['elements' => ['property']],
  226. 'single_import_per_statement' => true,
  227. 'single_line_after_imports' => true,
  228. 'spaces_inside_parentheses' => true,
  229. 'statement_indentation' => true,
  230. 'switch_case_semicolon_to_colon' => true,
  231. 'switch_case_space' => true,
  232. 'visibility_required' => ['elements' => ['method', 'property']],
  233. ],
  234. $ruleSet->getRules()
  235. );
  236. }
  237. /**
  238. * @param array<string, array<string, mixed>|bool> $set
  239. *
  240. * @dataProvider provideRiskyRulesInSetCases
  241. */
  242. public function testRiskyRulesInSet(array $set, bool $safe): void
  243. {
  244. /** @TODO 4.0 Remove this expectations */
  245. $expectedDeprecations = [
  246. '@PER' => 'Rule set "@PER" is deprecated. Use "@PER-CS" instead.',
  247. '@PER:risky' => 'Rule set "@PER:risky" is deprecated. Use "@PER-CS:risky" instead.',
  248. ];
  249. if (\array_key_exists(array_key_first($set), $expectedDeprecations)) {
  250. $this->expectDeprecation($expectedDeprecations[array_key_first($set)]);
  251. }
  252. try {
  253. $fixers = (new FixerFactory())
  254. ->registerBuiltInFixers()
  255. ->useRuleSet(new RuleSet($set))
  256. ->getFixers()
  257. ;
  258. } catch (InvalidForEnvFixerConfigurationException $exception) {
  259. self::markTestSkipped($exception->getMessage());
  260. }
  261. $fixerNames = [];
  262. foreach ($fixers as $fixer) {
  263. if ($safe === $fixer->isRisky()) {
  264. $fixerNames[] = $fixer->getName();
  265. }
  266. }
  267. self::assertCount(
  268. 0,
  269. $fixerNames,
  270. sprintf(
  271. 'Set should only contain %s fixers, got: \'%s\'.',
  272. $safe ? 'safe' : 'risky',
  273. implode('\', \'', $fixerNames)
  274. )
  275. );
  276. }
  277. public static function provideRiskyRulesInSetCases(): iterable
  278. {
  279. foreach (RuleSets::getSetDefinitionNames() as $name) {
  280. yield $name => [
  281. [$name => true],
  282. !str_contains($name, ':risky'),
  283. ];
  284. }
  285. yield '@Symfony:risky_and_@Symfony' => [
  286. [
  287. '@Symfony:risky' => true,
  288. '@Symfony' => false,
  289. ],
  290. false,
  291. ];
  292. }
  293. public function testInvalidConfigNestedSets(): void
  294. {
  295. $this->expectException(\UnexpectedValueException::class);
  296. $this->expectExceptionMessageMatches('#^Nested rule set "@PSR1" configuration must be a boolean\.$#');
  297. new RuleSet(
  298. ['@PSR1' => ['@PSR2' => 'no']]
  299. );
  300. }
  301. public function testGetMissingRuleConfiguration(): void
  302. {
  303. $ruleSet = new RuleSet();
  304. $this->expectException(\InvalidArgumentException::class);
  305. $this->expectExceptionMessageMatches('#^Rule "_not_exists" is not in the set\.$#');
  306. $ruleSet->getRuleConfiguration('_not_exists');
  307. }
  308. /**
  309. * @dataProvider provideDuplicateRuleConfigurationInSetDefinitionsCases
  310. */
  311. public function testDuplicateRuleConfigurationInSetDefinitions(RuleSetDescriptionInterface $set): void
  312. {
  313. $rules = [];
  314. $setRules = [];
  315. foreach ($set->getRules() as $ruleName => $ruleConfig) {
  316. if (str_starts_with($ruleName, '@')) {
  317. if (true !== $ruleConfig && false !== $ruleConfig) {
  318. throw new \LogicException('Disallowed configuration for RuleSet.');
  319. }
  320. $setRules = array_merge($setRules, $this->resolveSet($ruleName, $ruleConfig));
  321. } else {
  322. $rules[$ruleName] = $ruleConfig;
  323. }
  324. }
  325. $duplicates = [];
  326. foreach ($rules as $ruleName => $ruleConfig) {
  327. if (!\array_key_exists($ruleName, $setRules)) {
  328. continue;
  329. }
  330. if ($ruleConfig !== $setRules[$ruleName]) {
  331. continue;
  332. }
  333. $duplicates[] = $ruleName;
  334. }
  335. if (0 === \count($duplicates)) {
  336. $this->addToAssertionCount(1);
  337. return;
  338. }
  339. self::fail(sprintf(
  340. '"%s" defines rules the same as it extends from: %s',
  341. $set->getName(),
  342. implode(', ', $duplicates),
  343. ));
  344. }
  345. public static function provideDuplicateRuleConfigurationInSetDefinitionsCases(): iterable
  346. {
  347. foreach (RuleSets::getSetDefinitions() as $name => $set) {
  348. yield $name => [$set];
  349. }
  350. }
  351. /**
  352. * @dataProvider providePhpUnitTargetVersionHasSetCases
  353. */
  354. public function testPhpUnitTargetVersionHasSet(string $version): void
  355. {
  356. self::assertContains(
  357. sprintf('@PHPUnit%sMigration:risky', str_replace('.', '', $version)),
  358. RuleSets::getSetDefinitionNames(),
  359. sprintf('PHPUnit target version %s is missing its set in %s.', $version, RuleSet::class)
  360. );
  361. }
  362. public static function providePhpUnitTargetVersionHasSetCases(): iterable
  363. {
  364. foreach ((new \ReflectionClass(PhpUnitTargetVersion::class))->getConstants() as $constant) {
  365. if ('newest' === $constant) {
  366. continue;
  367. }
  368. yield [$constant];
  369. }
  370. }
  371. public function testEmptyName(): void
  372. {
  373. $this->expectException(\InvalidArgumentException::class);
  374. $this->expectExceptionMessage('Rule/set name must not be empty.');
  375. new RuleSet(['' => true]);
  376. }
  377. public function testInvalidConfig(): void
  378. {
  379. $this->expectException(\InvalidArgumentException::class);
  380. $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".');
  381. // @phpstan-ignore-next-line
  382. new RuleSet(['@Symfony:risky' => null]);
  383. }
  384. /**
  385. * @param array<array-key, mixed> $array
  386. *
  387. * @return array<array-key, mixed> $array
  388. */
  389. private function sortNestedArray(array $array, string $ruleName): array
  390. {
  391. $this->doSort($array, $ruleName);
  392. return $array;
  393. }
  394. /**
  395. * Sorts an array of fixer definition recursively.
  396. *
  397. * Sometimes keys are all string, sometimes they are integers - we need to account for that.
  398. *
  399. * @param array<array-key, mixed> $data
  400. */
  401. private function doSort(array &$data, string $path): void
  402. {
  403. // if order matters do not sort!
  404. if (\in_array($path, self::ORDER_MATTERS, true)) {
  405. return;
  406. }
  407. $keys = array_keys($data);
  408. if ($this->allInteger($keys)) {
  409. sort($data);
  410. } else {
  411. ksort($data);
  412. }
  413. foreach ($data as $key => $value) {
  414. if (\is_array($value)) {
  415. $this->doSort(
  416. $data[$key],
  417. $path.('' !== $path ? '.' : '').$key
  418. );
  419. }
  420. }
  421. }
  422. /**
  423. * @param array<int|string, mixed> $values
  424. */
  425. private function allInteger(array $values): bool
  426. {
  427. foreach ($values as $value) {
  428. if (!\is_int($value)) {
  429. return false;
  430. }
  431. }
  432. return true;
  433. }
  434. /**
  435. * @return array<string, array<string, mixed>|bool>
  436. */
  437. private function resolveSet(string $setName, bool $setValue): array
  438. {
  439. $rules = RuleSets::getSetDefinition($setName)->getRules();
  440. foreach ($rules as $name => $value) {
  441. if (str_starts_with($name, '@')) {
  442. $set = $this->resolveSet($name, $setValue);
  443. unset($rules[$name]);
  444. $rules = array_merge($rules, $set);
  445. } elseif (!$setValue) {
  446. $rules[$name] = false;
  447. } else {
  448. $rules[$name] = $value;
  449. }
  450. }
  451. return $rules;
  452. }
  453. /**
  454. * @param array<string, array<string, mixed>|bool> $expected
  455. * @param array<string, array<string, mixed>|bool> $actual
  456. */
  457. private static function assertSameRules(array $expected, array $actual): void
  458. {
  459. ksort($expected);
  460. ksort($actual);
  461. self::assertSame($expected, $actual);
  462. }
  463. }