RuleSetsTest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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\AbstractFixer;
  14. use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion;
  15. use PhpCsFixer\FixerFactory;
  16. use PhpCsFixer\RuleSet\RuleSet;
  17. use PhpCsFixer\RuleSet\RuleSets;
  18. use PhpCsFixer\Tests\TestCase;
  19. /**
  20. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  21. *
  22. * @internal
  23. *
  24. * @covers \PhpCsFixer\RuleSet\RuleSets
  25. */
  26. final class RuleSetsTest extends TestCase
  27. {
  28. public function testGetSetDefinitionNames(): void
  29. {
  30. static::assertSame(
  31. array_keys(RuleSets::getSetDefinitions()),
  32. RuleSets::getSetDefinitionNames()
  33. );
  34. }
  35. public function testGetSetDefinitions(): void
  36. {
  37. $sets = RuleSets::getSetDefinitions();
  38. foreach ($sets as $name => $set) {
  39. static::assertIsString($name);
  40. static::assertTrue('@' === $name[0]);
  41. static::assertIsArray($set->getRules());
  42. static::assertSame($set, RuleSets::getSetDefinition($name));
  43. }
  44. }
  45. public function testGetUnknownSetDefinition(): void
  46. {
  47. $name = 'Unknown';
  48. $this->expectException(\InvalidArgumentException::class);
  49. $this->expectExceptionMessageMatches(sprintf('#^Set "%s" does not exist\.$#', $name));
  50. RuleSets::getSetDefinition($name);
  51. }
  52. /**
  53. * @dataProvider provideSetDefinitionNameCases
  54. */
  55. public function testHasIntegrationTest(string $setDefinitionName): void
  56. {
  57. $setsWithoutTests = [
  58. '@PHP56Migration',
  59. '@PHP56Migration:risky',
  60. '@PHP70Migration',
  61. '@PHP70Migration:risky',
  62. '@PHP71Migration',
  63. '@PHP71Migration:risky',
  64. '@PHP73Migration',
  65. '@PHP80Migration',
  66. '@PhpCsFixer',
  67. '@PhpCsFixer:risky',
  68. '@PHPUnit48Migration',
  69. '@PHPUnit55Migration:risky',
  70. '@PHPUnit75Migration:risky',
  71. '@PHPUnit84Migration:risky',
  72. '@PSR1',
  73. ];
  74. if (\in_array($setDefinitionName, $setsWithoutTests, true)) {
  75. static::markTestIncomplete(sprintf('Set "%s" has no integration test.', $setDefinitionName));
  76. }
  77. $setDefinitionFileNamePrefix = str_replace(':', '-', $setDefinitionName);
  78. $dir = __DIR__.'/../../tests/Fixtures/Integration/set';
  79. $file = sprintf('%s/%s.test', $dir, $setDefinitionFileNamePrefix);
  80. static::assertFileExists($file);
  81. static::assertFileExists(sprintf('%s/%s.test-in.php', $dir, $setDefinitionFileNamePrefix));
  82. static::assertFileExists(sprintf('%s/%s.test-out.php', $dir, $setDefinitionFileNamePrefix));
  83. $template = '--TEST--
  84. Integration of %s.
  85. --RULESET--
  86. {"%s": true}
  87. ';
  88. static::assertStringStartsWith(
  89. sprintf($template, $setDefinitionName, $setDefinitionName),
  90. file_get_contents($file)
  91. );
  92. }
  93. /**
  94. * @dataProvider provideSetDefinitionNameCases
  95. */
  96. public function testBuildInSetDefinitionNames(string $setName): void
  97. {
  98. static::assertSame('@', substr($setName, 0, 1));
  99. }
  100. /**
  101. * @dataProvider provideSetDefinitionNameCases
  102. */
  103. public function testSetDefinitionsAreSorted(string $setDefinitionName): void
  104. {
  105. $setDefinition = RuleSets::getSetDefinitions()[$setDefinitionName]->getRules();
  106. $sortedSetDefinition = $setDefinition;
  107. $this->sort($sortedSetDefinition);
  108. static::assertSame($sortedSetDefinition, $setDefinition, sprintf(
  109. 'Failed to assert that the set definition for "%s" is sorted by key.',
  110. $setDefinitionName
  111. ));
  112. }
  113. public function testSetDefinitionsItselfIsSorted(): void
  114. {
  115. $setDefinition = array_keys(RuleSets::getSetDefinitions());
  116. $sortedSetDefinition = $setDefinition;
  117. $this->sort($sortedSetDefinition);
  118. static::assertSame($sortedSetDefinition, $setDefinition);
  119. }
  120. public function provideSetDefinitionNameCases(): array
  121. {
  122. $setDefinitionNames = RuleSets::getSetDefinitionNames();
  123. return array_map(static function (string $setDefinitionName) {
  124. return [$setDefinitionName];
  125. }, $setDefinitionNames);
  126. }
  127. /**
  128. * @dataProvider providePHPUnitMigrationSetDefinitionNameCases
  129. */
  130. public function testPHPUnitMigrationTargetVersions(string $setName): void
  131. {
  132. $ruleSet = new RuleSet([$setName => true]);
  133. foreach ($ruleSet->getRules() as $ruleName => $ruleConfig) {
  134. $targetVersion = true === $ruleConfig ? $this->getDefaultPHPUnitTargetOfRule($ruleName) : $ruleConfig['target'];
  135. static::assertPHPUnitVersionIsLargestAllowed($setName, $ruleName, $targetVersion);
  136. }
  137. }
  138. /**
  139. * @return string[][]
  140. */
  141. public function providePHPUnitMigrationSetDefinitionNameCases(): array
  142. {
  143. $setDefinitionNames = RuleSets::getSetDefinitionNames();
  144. $setDefinitionPHPUnitMigrationNames = array_filter($setDefinitionNames, static function (string $setDefinitionName) {
  145. return 1 === preg_match('/^@PHPUnit\d{2}Migration:risky$/', $setDefinitionName);
  146. });
  147. return array_map(static function (string $setDefinitionName) {
  148. return [$setDefinitionName];
  149. }, $setDefinitionPHPUnitMigrationNames);
  150. }
  151. private static function assertPHPUnitVersionIsLargestAllowed(string $setName, string $ruleName, string $actualTargetVersion): void
  152. {
  153. $maximumVersionForRuleset = preg_replace('/^@PHPUnit(\d)(\d)Migration:risky$/', '$1.$2', $setName);
  154. $fixer = self::getFixerByName($ruleName);
  155. foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) {
  156. if ('target' === $option->getName()) {
  157. $allowedVersionsForFixer = array_diff($option->getAllowedValues(), [PhpUnitTargetVersion::VERSION_NEWEST]);
  158. break;
  159. }
  160. }
  161. if (!isset($allowedVersionsForFixer)) {
  162. throw new \Exception(sprintf('The fixer "%s" does not have option "target".', $fixer->getName()));
  163. }
  164. $allowedVersionsForRuleset = array_filter(
  165. $allowedVersionsForFixer,
  166. static function (string $version) use ($maximumVersionForRuleset) {
  167. return strcmp($maximumVersionForRuleset, $version) >= 0;
  168. }
  169. );
  170. static::assertTrue(\in_array($actualTargetVersion, $allowedVersionsForRuleset, true), sprintf(
  171. 'Rule "%s" (in rule set "%s") has target "%s", but the rule set is not allowing it (allowed are only "%s")',
  172. $fixer->getName(),
  173. $setName,
  174. $actualTargetVersion,
  175. implode('", "', $allowedVersionsForRuleset)
  176. ));
  177. rsort($allowedVersionsForRuleset);
  178. $maximumAllowedVersionForRuleset = reset($allowedVersionsForRuleset);
  179. static::assertSame($maximumAllowedVersionForRuleset, $actualTargetVersion, sprintf(
  180. 'Rule "%s" (in rule set "%s") has target "%s", but there is higher available target "%s"',
  181. $fixer->getName(),
  182. $setName,
  183. $actualTargetVersion,
  184. $maximumAllowedVersionForRuleset
  185. ));
  186. }
  187. /**
  188. * Sorts an array of rule set definitions recursively.
  189. *
  190. * Sometimes keys are all string, sometimes they are integers - we need to account for that.
  191. */
  192. private function sort(array &$data): void
  193. {
  194. $this->doSort($data, '');
  195. }
  196. private function doSort(array &$data, string $path): void
  197. {
  198. if ('ordered_imports.imports_order' === $path) { // order matters
  199. return;
  200. }
  201. $keys = array_keys($data);
  202. if ($this->allInteger($keys)) {
  203. sort($data);
  204. } else {
  205. ksort($data);
  206. }
  207. foreach ($data as $key => $value) {
  208. if (\is_array($value)) {
  209. $this->doSort(
  210. $data[$key],
  211. $path.('' !== $path ? '.' : '').$key
  212. );
  213. }
  214. }
  215. }
  216. private function allInteger(array $values): bool
  217. {
  218. foreach ($values as $value) {
  219. if (!\is_int($value)) {
  220. return false;
  221. }
  222. }
  223. return true;
  224. }
  225. private function getDefaultPHPUnitTargetOfRule(string $ruleName): string
  226. {
  227. $targetVersion = null;
  228. $fixer = self::getFixerByName($ruleName);
  229. foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) {
  230. if ('target' === $option->getName()) {
  231. $targetVersion = $option->getDefault();
  232. break;
  233. }
  234. }
  235. if (null === $targetVersion) {
  236. throw new \Exception(sprintf('The fixer "%s" does not have option "target".', $fixer->getName()));
  237. }
  238. return $targetVersion;
  239. }
  240. private static function getFixerByName(string $name): AbstractFixer
  241. {
  242. $factory = new FixerFactory();
  243. $factory->registerBuiltInFixers();
  244. $factory->useRuleSet(new RuleSet([$name => true]));
  245. $fixers = $factory->getFixers();
  246. if (empty($fixers)) {
  247. throw new \RuntimeException('FixerFactory unexpectedly returned empty array.');
  248. }
  249. $fixer = current($fixers);
  250. if (!$fixer instanceof AbstractFixer) {
  251. throw new \RuntimeException(sprintf('Fixer class for "%s" rule does not extend "%s".', $name, AbstractFixer::class));
  252. }
  253. return $fixer;
  254. }
  255. }