AbstractFixerTestCase.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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\Test;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\AbstractProxyFixer;
  15. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  16. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  17. use PhpCsFixer\Fixer\Whitespace\SingleBlankLineAtEofFixer;
  18. use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
  19. use PhpCsFixer\FixerDefinition\CodeSampleInterface;
  20. use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
  21. use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
  22. use PhpCsFixer\Linter\CachingLinter;
  23. use PhpCsFixer\Linter\Linter;
  24. use PhpCsFixer\Linter\LinterInterface;
  25. use PhpCsFixer\Linter\ProcessLinter;
  26. use PhpCsFixer\PhpunitConstraintIsIdenticalString\Constraint\IsIdenticalString;
  27. use PhpCsFixer\Preg;
  28. use PhpCsFixer\StdinFileInfo;
  29. use PhpCsFixer\Tests\Fixer\ClassNotation\ClassAttributesSeparationFixerTest;
  30. use PhpCsFixer\Tests\Fixer\ClassNotation\ClassDefinitionFixerTest;
  31. use PhpCsFixer\Tests\Fixer\Comment\HeaderCommentFixerTest;
  32. use PhpCsFixer\Tests\Fixer\Comment\NoEmptyCommentFixerTest;
  33. use PhpCsFixer\Tests\Fixer\Comment\SingleLineCommentStyleFixerTest;
  34. use PhpCsFixer\Tests\Fixer\ConstantNotation\NativeConstantInvocationFixerTest;
  35. use PhpCsFixer\Tests\Fixer\ControlStructure\NoBreakCommentFixerTest;
  36. use PhpCsFixer\Tests\Fixer\ControlStructure\NoUnneededControlParenthesesFixerTest;
  37. use PhpCsFixer\Tests\Fixer\ControlStructure\NoUselessElseFixerTest;
  38. use PhpCsFixer\Tests\Fixer\ControlStructure\YodaStyleFixerTest;
  39. use PhpCsFixer\Tests\Fixer\DoctrineAnnotation\DoctrineAnnotationArrayAssignmentFixerTest;
  40. use PhpCsFixer\Tests\Fixer\DoctrineAnnotation\DoctrineAnnotationBracesFixerTest;
  41. use PhpCsFixer\Tests\Fixer\DoctrineAnnotation\DoctrineAnnotationIndentationFixerTest;
  42. use PhpCsFixer\Tests\Fixer\DoctrineAnnotation\DoctrineAnnotationSpacesFixerTest;
  43. use PhpCsFixer\Tests\Fixer\FunctionNotation\FunctionDeclarationFixerTest;
  44. use PhpCsFixer\Tests\Fixer\FunctionNotation\MethodArgumentSpaceFixerTest;
  45. use PhpCsFixer\Tests\Fixer\FunctionNotation\NativeFunctionInvocationFixerTest;
  46. use PhpCsFixer\Tests\Fixer\FunctionNotation\ReturnTypeDeclarationFixerTest;
  47. use PhpCsFixer\Tests\Fixer\Import\FullyQualifiedStrictTypesFixerTest;
  48. use PhpCsFixer\Tests\Fixer\Import\GlobalNamespaceImportFixerTest;
  49. use PhpCsFixer\Tests\Fixer\Import\OrderedImportsFixerTest;
  50. use PhpCsFixer\Tests\Fixer\Import\SingleImportPerStatementFixerTest;
  51. use PhpCsFixer\Tests\Fixer\LanguageConstruct\FunctionToConstantFixerTest;
  52. use PhpCsFixer\Tests\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixerTest;
  53. use PhpCsFixer\Tests\Fixer\ListNotation\ListSyntaxFixerTest;
  54. use PhpCsFixer\Tests\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixerTest;
  55. use PhpCsFixer\Tests\Fixer\Operator\BinaryOperatorSpacesFixerTest;
  56. use PhpCsFixer\Tests\Fixer\Operator\ConcatSpaceFixerTest;
  57. use PhpCsFixer\Tests\Fixer\Operator\IncrementStyleFixerTest;
  58. use PhpCsFixer\Tests\Fixer\Operator\NewWithParenthesesFixerTest;
  59. use PhpCsFixer\Tests\Fixer\Operator\NoUselessConcatOperatorFixerTest;
  60. use PhpCsFixer\Tests\Fixer\Phpdoc\AlignMultilineCommentFixerTest;
  61. use PhpCsFixer\Tests\Fixer\Phpdoc\GeneralPhpdocTagRenameFixerTest;
  62. use PhpCsFixer\Tests\Fixer\Phpdoc\NoBlankLinesAfterPhpdocFixerTest;
  63. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocAddMissingParamAnnotationFixerTest;
  64. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocNoAliasTagFixerTest;
  65. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocNoEmptyReturnFixerTest;
  66. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocNoPackageFixerTest;
  67. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocOrderByValueFixerTest;
  68. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocOrderFixerTest;
  69. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocParamOrderFixerTest;
  70. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocReturnSelfReferenceFixerTest;
  71. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocSeparationFixerTest;
  72. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocSummaryFixerTest;
  73. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocTrimFixerTest;
  74. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocTypesOrderFixerTest;
  75. use PhpCsFixer\Tests\Fixer\Phpdoc\PhpdocVarWithoutNameFixerTest;
  76. use PhpCsFixer\Tests\Fixer\PhpTag\EchoTagSyntaxFixerTest;
  77. use PhpCsFixer\Tests\Fixer\PhpTag\NoClosingTagFixerTest;
  78. use PhpCsFixer\Tests\Fixer\PhpUnit\PhpUnitConstructFixerTest;
  79. use PhpCsFixer\Tests\Fixer\PhpUnit\PhpUnitDedicateAssertFixerTest;
  80. use PhpCsFixer\Tests\Fixer\PhpUnit\PhpUnitMethodCasingFixerTest;
  81. use PhpCsFixer\Tests\Fixer\PhpUnit\PhpUnitTestCaseStaticMethodCallsFixerTest;
  82. use PhpCsFixer\Tests\Fixer\ReturnNotation\ReturnAssignmentFixerTest;
  83. use PhpCsFixer\Tests\Fixer\Semicolon\MultilineWhitespaceBeforeSemicolonsFixerTest;
  84. use PhpCsFixer\Tests\Fixer\Semicolon\NoEmptyStatementFixerTest;
  85. use PhpCsFixer\Tests\Fixer\Semicolon\SemicolonAfterInstructionFixerTest;
  86. use PhpCsFixer\Tests\Fixer\Semicolon\SpaceAfterSemicolonFixerTest;
  87. use PhpCsFixer\Tests\Fixer\Whitespace\BlankLineBeforeStatementFixerTest;
  88. use PhpCsFixer\Tests\Fixer\Whitespace\IndentationTypeFixerTest;
  89. use PhpCsFixer\Tests\Fixer\Whitespace\NoExtraBlankLinesFixerTest;
  90. use PhpCsFixer\Tests\Fixer\Whitespace\NoSpacesAroundOffsetFixerTest;
  91. use PhpCsFixer\Tests\Fixer\Whitespace\SpacesInsideParenthesesFixerTest;
  92. use PhpCsFixer\Tests\Fixer\Whitespace\StatementIndentationFixerTest;
  93. use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
  94. use PhpCsFixer\Tests\TestCase;
  95. use PhpCsFixer\Tokenizer\Token;
  96. use PhpCsFixer\Tokenizer\Tokens;
  97. /**
  98. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  99. *
  100. * @internal
  101. */
  102. abstract class AbstractFixerTestCase extends TestCase
  103. {
  104. use AssertTokensTrait;
  105. /**
  106. * @var null|LinterInterface
  107. */
  108. protected $linter;
  109. /**
  110. * @var null|AbstractFixer
  111. */
  112. protected $fixer;
  113. /**
  114. * do not modify this structure without prior discussion.
  115. *
  116. * @var array<string, array<string, bool>>
  117. */
  118. private array $allowedRequiredOptions = [
  119. 'header_comment' => ['header' => true],
  120. ];
  121. /**
  122. * do not modify this structure without prior discussion.
  123. *
  124. * @var array<string, bool>
  125. */
  126. private array $allowedFixersWithoutDefaultCodeSample = [
  127. 'general_phpdoc_annotation_remove' => true,
  128. 'general_phpdoc_tag_rename' => true,
  129. ];
  130. protected function setUp(): void
  131. {
  132. parent::setUp();
  133. $this->linter = $this->getLinter();
  134. $this->fixer = $this->createFixer();
  135. }
  136. protected function tearDown(): void
  137. {
  138. parent::tearDown();
  139. $this->linter = null;
  140. $this->fixer = null;
  141. }
  142. final public function testIsRisky(): void
  143. {
  144. if ($this->fixer->isRisky()) {
  145. self::assertValidDescription($this->fixer->getName(), 'risky description', $this->fixer->getDefinition()->getRiskyDescription());
  146. } else {
  147. self::assertNull($this->fixer->getDefinition()->getRiskyDescription(), sprintf('[%s] Fixer is not risky so no description of it expected.', $this->fixer->getName()));
  148. }
  149. if ($this->fixer instanceof AbstractProxyFixer) {
  150. return;
  151. }
  152. $reflection = new \ReflectionMethod($this->fixer, 'isRisky');
  153. // If fixer is not risky then the method `isRisky` from `AbstractFixer` must be used
  154. self::assertSame(
  155. !$this->fixer->isRisky(),
  156. AbstractFixer::class === $reflection->getDeclaringClass()->getName()
  157. );
  158. }
  159. final public function testFixerDefinitions(): void
  160. {
  161. $fixerName = $this->fixer->getName();
  162. $definition = $this->fixer->getDefinition();
  163. $fixerIsConfigurable = $this->fixer instanceof ConfigurableFixerInterface;
  164. self::assertValidDescription($fixerName, 'summary', $definition->getSummary());
  165. if (null !== $definition->getDescription()) {
  166. self::assertValidDescription($fixerName, 'description', $definition->getDescription());
  167. }
  168. $samples = $definition->getCodeSamples();
  169. self::assertNotEmpty($samples, sprintf('[%s] Code samples are required.', $fixerName));
  170. $configSamplesProvided = [];
  171. $dummyFileInfo = new StdinFileInfo();
  172. foreach ($samples as $sampleCounter => $sample) {
  173. self::assertInstanceOf(CodeSampleInterface::class, $sample, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  174. self::assertIsInt($sampleCounter);
  175. $code = $sample->getCode();
  176. self::assertNotEmpty($code, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  177. self::assertStringStartsNotWith("\n", $code, sprintf('[%s] Sample #%d must not start with linebreak', $fixerName, $sampleCounter));
  178. if (!$this->fixer instanceof SingleBlankLineAtEofFixer) {
  179. self::assertStringEndsWith("\n", $code, sprintf('[%s] Sample #%d must end with linebreak', $fixerName, $sampleCounter));
  180. }
  181. $config = $sample->getConfiguration();
  182. if (null !== $config) {
  183. self::assertTrue($fixerIsConfigurable, sprintf('[%s] Sample #%d has configuration, but the fixer is not configurable.', $fixerName, $sampleCounter));
  184. $configSamplesProvided[$sampleCounter] = $config;
  185. } elseif ($fixerIsConfigurable) {
  186. if (!$sample instanceof VersionSpecificCodeSampleInterface) {
  187. self::assertArrayNotHasKey('default', $configSamplesProvided, sprintf('[%s] Multiple non-versioned samples with default configuration.', $fixerName));
  188. }
  189. $configSamplesProvided['default'] = true;
  190. }
  191. if ($sample instanceof VersionSpecificCodeSampleInterface) {
  192. $supportedPhpVersions = [7_04_00, 8_00_00, 8_01_00, 8_02_00, 8_03_00, 8_04_00];
  193. $hasSuitableSupportedVersion = false;
  194. foreach ($supportedPhpVersions as $version) {
  195. if ($sample->isSuitableFor($version)) {
  196. $hasSuitableSupportedVersion = true;
  197. }
  198. }
  199. self::assertTrue($hasSuitableSupportedVersion, 'Version specific code sample must be suitable for at least 1 supported PHP version.');
  200. $hasUnsuitableSupportedVersion = false;
  201. foreach ($supportedPhpVersions as $version) {
  202. if (!$sample->isSuitableFor($version)) {
  203. $hasUnsuitableSupportedVersion = true;
  204. }
  205. }
  206. self::assertTrue($hasUnsuitableSupportedVersion, 'Version specific code sample must be unsuitable for at least 1 supported PHP version.');
  207. if (!$sample->isSuitableFor(\PHP_VERSION_ID)) {
  208. continue;
  209. }
  210. }
  211. if ($fixerIsConfigurable) {
  212. // always re-configure as the fixer might have been configured with diff. configuration form previous sample
  213. $this->fixer->configure($config ?? []);
  214. }
  215. Tokens::clearCache();
  216. $tokens = Tokens::fromCode($code);
  217. $this->fixer->fix(
  218. $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : $dummyFileInfo,
  219. $tokens
  220. );
  221. self::assertTrue($tokens->isChanged(), sprintf('[%s] Sample #%d is not changed during fixing.', $fixerName, $sampleCounter));
  222. $duplicatedCodeSample = array_search(
  223. $sample,
  224. \array_slice($samples, 0, $sampleCounter),
  225. true
  226. );
  227. self::assertFalse(
  228. $duplicatedCodeSample,
  229. sprintf('[%s] Sample #%d duplicates #%d.', $fixerName, $sampleCounter, $duplicatedCodeSample)
  230. );
  231. }
  232. if ($fixerIsConfigurable) {
  233. if (isset($configSamplesProvided['default'])) {
  234. self::assertSame('default', array_key_first($configSamplesProvided), sprintf('[%s] First sample must be for the default configuration.', $fixerName));
  235. } elseif (!isset($this->allowedFixersWithoutDefaultCodeSample[$fixerName])) {
  236. self::assertArrayHasKey($fixerName, $this->allowedRequiredOptions, sprintf('[%s] Has no sample for default configuration.', $fixerName));
  237. }
  238. if (\count($configSamplesProvided) < 2) {
  239. self::fail(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
  240. }
  241. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  242. foreach ($options as $option) {
  243. self::assertMatchesRegularExpression('/^[a-z_]+[a-z]$/', $option->getName(), sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
  244. self::assertMatchesRegularExpression(
  245. '/^[A-Z].+\.$/s',
  246. $option->getDescription(),
  247. sprintf('[%s] Description of option "%s" must start with capital letter and end with dot.', $fixerName, $option->getName())
  248. );
  249. }
  250. }
  251. self::assertIsInt($this->fixer->getPriority());
  252. }
  253. final public function testFixersAreFinal(): void
  254. {
  255. $reflection = new \ReflectionClass($this->fixer);
  256. self::assertTrue(
  257. $reflection->isFinal(),
  258. sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName())
  259. );
  260. }
  261. final public function testDeprecatedFixersHaveCorrectSummary(): void
  262. {
  263. self::assertStringNotContainsString(
  264. 'DEPRECATED',
  265. $this->fixer->getDefinition()->getSummary(),
  266. 'Fixer cannot contain word "DEPRECATED" in summary'
  267. );
  268. $reflection = new \ReflectionClass($this->fixer);
  269. $comment = $reflection->getDocComment();
  270. if ($this->fixer instanceof DeprecatedFixerInterface) {
  271. self::assertIsString($comment, sprintf('Missing class PHPDoc for deprecated fixer "%s".', $this->fixer->getName()));
  272. self::assertStringContainsString('@deprecated', $comment);
  273. } elseif (\is_string($comment)) {
  274. self::assertStringNotContainsString('@deprecated', $comment);
  275. }
  276. }
  277. /**
  278. * Blur filter that find candidate fixer for performance optimization to use only `insertSlices` instead of multiple `insertAt` if there is no other collection manipulation.
  279. */
  280. public function testFixerUseInsertSlicesWhenOnlyInsertionsArePerformed(): void
  281. {
  282. $reflection = new \ReflectionClass($this->fixer);
  283. $filePath = $reflection->getFileName();
  284. if (false === $filePath) {
  285. throw new \RuntimeException('Cannot determine sourcefile for class.');
  286. }
  287. $tokens = Tokens::fromCode(file_get_contents($filePath));
  288. $sequences = $this->findAllTokenSequences($tokens, [[T_VARIABLE, '$tokens'], [T_OBJECT_OPERATOR], [T_STRING]]);
  289. $usedMethods = array_unique(array_map(static function (array $sequence): string {
  290. $last = end($sequence);
  291. return $last->getContent();
  292. }, $sequences));
  293. // if there is no `insertAt`, it's not a candidate
  294. if (!\in_array('insertAt', $usedMethods, true)) {
  295. $this->expectNotToPerformAssertions();
  296. return;
  297. }
  298. $usedMethods = array_filter($usedMethods, static fn (string $method): bool => !Preg::match('/^(count|find|generate|get|is|rewind)/', $method));
  299. $allowedMethods = ['insertAt'];
  300. $nonAllowedMethods = array_diff($usedMethods, $allowedMethods);
  301. if ([] === $nonAllowedMethods) {
  302. $fixerName = $this->fixer->getName();
  303. if (\in_array($fixerName, [
  304. // DO NOT add anything to this list at ease, align with core contributors whether it makes sense to insert tokens individually or by bulk for your case.
  305. // The original list of the fixers being exceptions and insert tokens individually came from legacy reasons when it was the only available methods to insert tokens.
  306. 'blank_line_after_namespace',
  307. 'blank_line_after_opening_tag',
  308. 'blank_line_before_statement',
  309. 'class_attributes_separation',
  310. 'date_time_immutable',
  311. 'declare_strict_types',
  312. 'doctrine_annotation_braces',
  313. 'doctrine_annotation_spaces',
  314. 'final_internal_class',
  315. 'final_public_method_for_abstract_class',
  316. 'function_typehint_space',
  317. 'heredoc_indentation',
  318. 'method_chaining_indentation',
  319. 'native_constant_invocation',
  320. 'new_with_braces',
  321. 'new_with_parentheses',
  322. 'no_short_echo_tag',
  323. 'not_operator_with_space',
  324. 'not_operator_with_successor_space',
  325. 'php_unit_internal_class',
  326. 'php_unit_no_expectation_annotation',
  327. 'php_unit_set_up_tear_down_visibility',
  328. 'php_unit_size_class',
  329. 'php_unit_test_annotation',
  330. 'php_unit_test_class_requires_covers',
  331. 'phpdoc_to_param_type',
  332. 'phpdoc_to_property_type',
  333. 'phpdoc_to_return_type',
  334. 'random_api_migration',
  335. 'semicolon_after_instruction',
  336. 'single_line_after_imports',
  337. 'static_lambda',
  338. 'strict_param',
  339. 'void_return',
  340. ], true)) {
  341. self::markTestIncomplete(sprintf('Fixer "%s" may be optimized to use `Tokens::insertSlices` instead of `%s`, please help and optimize it.', $fixerName, implode(', ', $allowedMethods)));
  342. }
  343. self::fail(sprintf('Fixer "%s" shall be optimized to use `Tokens::insertSlices` instead of `%s`.', $fixerName, implode(', ', $allowedMethods)));
  344. }
  345. $this->addToAssertionCount(1);
  346. }
  347. final public function testFixerConfigurationDefinitions(): void
  348. {
  349. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  350. $this->expectNotToPerformAssertions(); // not applied to the fixer without configuration
  351. return;
  352. }
  353. $configurationDefinition = $this->fixer->getConfigurationDefinition();
  354. foreach ($configurationDefinition->getOptions() as $option) {
  355. self::assertInstanceOf(FixerOptionInterface::class, $option);
  356. self::assertNotEmpty($option->getDescription());
  357. self::assertValidDescription($this->fixer->getName(), 'option:'.$option->getName(), $option->getDescription());
  358. self::assertSame(
  359. !isset($this->allowedRequiredOptions[$this->fixer->getName()][$option->getName()]),
  360. $option->hasDefault(),
  361. sprintf(
  362. $option->hasDefault()
  363. ? 'Option `%s` of fixer `%s` is wrongly listed in `$allowedRequiredOptions` structure, as it is not required. If you just changed that option to not be required anymore, please adjust mentioned structure.'
  364. : 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `$allowedRequiredOptions` structure.',
  365. $option->getName(),
  366. $this->fixer->getName()
  367. )
  368. );
  369. self::assertStringNotContainsString(
  370. 'DEPRECATED',
  371. $option->getDescription(),
  372. 'Option description cannot contain word "DEPRECATED"'
  373. );
  374. }
  375. }
  376. final public function testProperMethodNaming(): void
  377. {
  378. if ($this->fixer instanceof DeprecatedFixerInterface) {
  379. self::markTestSkipped('Not worth refactoring tests for deprecated fixers.');
  380. }
  381. // should only shrink, baseline of classes violating method naming
  382. $exceptionClasses = [
  383. AlignMultilineCommentFixerTest::class,
  384. BinaryOperatorSpacesFixerTest::class,
  385. BlankLineBeforeStatementFixerTest::class,
  386. BlankLinesBeforeNamespaceFixerTest::class,
  387. ClassAttributesSeparationFixerTest::class,
  388. ClassDefinitionFixerTest::class,
  389. ConcatSpaceFixerTest::class,
  390. DoctrineAnnotationArrayAssignmentFixerTest::class,
  391. DoctrineAnnotationBracesFixerTest::class,
  392. DoctrineAnnotationIndentationFixerTest::class,
  393. DoctrineAnnotationSpacesFixerTest::class,
  394. EchoTagSyntaxFixerTest::class,
  395. FullyQualifiedStrictTypesFixerTest::class,
  396. FunctionDeclarationFixerTest::class,
  397. FunctionToConstantFixerTest::class,
  398. GeneralPhpdocTagRenameFixerTest::class,
  399. GlobalNamespaceImportFixerTest::class,
  400. HeaderCommentFixerTest::class,
  401. IncrementStyleFixerTest::class,
  402. IndentationTypeFixerTest::class,
  403. ListSyntaxFixerTest::class,
  404. MethodArgumentSpaceFixerTest::class,
  405. MultilineWhitespaceBeforeSemicolonsFixerTest::class,
  406. NativeConstantInvocationFixerTest::class,
  407. NativeFunctionInvocationFixerTest::class,
  408. NewWithParenthesesFixerTest::class,
  409. NoBlankLinesAfterPhpdocFixerTest::class,
  410. NoBreakCommentFixerTest::class,
  411. NoClosingTagFixerTest::class,
  412. NoEmptyCommentFixerTest::class,
  413. NoEmptyStatementFixerTest::class,
  414. NoExtraBlankLinesFixerTest::class,
  415. NoSpacesAroundOffsetFixerTest::class,
  416. NoUnneededControlParenthesesFixerTest::class,
  417. NoUselessConcatOperatorFixerTest::class,
  418. NoUselessElseFixerTest::class,
  419. OrderedImportsFixerTest::class,
  420. PhpdocAddMissingParamAnnotationFixerTest::class,
  421. PhpdocNoAliasTagFixerTest::class,
  422. PhpdocNoEmptyReturnFixerTest::class,
  423. PhpdocNoPackageFixerTest::class,
  424. PhpdocOrderByValueFixerTest::class,
  425. PhpdocOrderFixerTest::class,
  426. PhpdocParamOrderFixerTest::class,
  427. PhpdocReturnSelfReferenceFixerTest::class,
  428. PhpdocSeparationFixerTest::class,
  429. PhpdocSummaryFixerTest::class,
  430. PhpdocTrimFixerTest::class,
  431. PhpdocTypesOrderFixerTest::class,
  432. PhpdocVarWithoutNameFixerTest::class,
  433. PhpUnitConstructFixerTest::class,
  434. PhpUnitDedicateAssertFixerTest::class,
  435. PhpUnitMethodCasingFixerTest::class,
  436. PhpUnitTestCaseStaticMethodCallsFixerTest::class,
  437. ReturnAssignmentFixerTest::class,
  438. ReturnTypeDeclarationFixerTest::class,
  439. SemicolonAfterInstructionFixerTest::class,
  440. SingleImportPerStatementFixerTest::class,
  441. SingleLineCommentStyleFixerTest::class,
  442. SingleSpaceAroundConstructFixerTest::class,
  443. SpaceAfterSemicolonFixerTest::class,
  444. SpacesInsideParenthesesFixerTest::class,
  445. StatementIndentationFixerTest::class,
  446. YodaStyleFixerTest::class,
  447. ];
  448. $names = ['Fix', 'Fix74Deprecated', 'FixPre80', 'Fix80', 'FixPre81', 'Fix81', 'Fix82', 'Fix83', 'Fix84', 'WithWhitespacesConfig', 'InvalidConfiguration'];
  449. $methodNames = ['testConfigure'];
  450. foreach ($names as $name) {
  451. $methodNames[] = 'test'.$name;
  452. $methodNames[] = 'provide'.$name.'Cases';
  453. }
  454. $reflectionClass = new \ReflectionObject($this);
  455. $extraMethods = array_map(
  456. static fn (\ReflectionMethod $method): string => $method->getName(),
  457. array_filter(
  458. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  459. static fn (\ReflectionMethod $method): bool => $method->getDeclaringClass()->getName() === $reflectionClass->getName()
  460. && !\in_array($method->getName(), $methodNames, true)
  461. )
  462. );
  463. if (\in_array(static::class, $exceptionClasses, true)) {
  464. self::assertNotSame(
  465. [],
  466. $extraMethods,
  467. sprintf('Class "%s" have correct method names, remove it from exceptions list.', static::class),
  468. );
  469. self::markTestSkipped('Not covered yet.');
  470. }
  471. self::assertTrue(method_exists($this, 'testFix'), sprintf('Method testFix does not exist in %s.', static::class));
  472. self::assertTrue(method_exists($this, 'provideFixCases'), sprintf('Method provideFixCases does not exist in %s.', static::class));
  473. self::assertSame(
  474. [],
  475. $extraMethods,
  476. sprintf('Methods "%s" should not be present in %s.', implode('". "', $extraMethods), static::class),
  477. );
  478. }
  479. protected function createFixer(): AbstractFixer
  480. {
  481. $fixerClassName = preg_replace('/^(PhpCsFixer)\\\\Tests(\\\\.+)Test$/', '$1$2', static::class);
  482. return new $fixerClassName();
  483. }
  484. /**
  485. * Tests if a fixer fixes a given string to match the expected result.
  486. *
  487. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  488. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  489. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  490. * as the latter covers both of them.
  491. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  492. * not test anything.
  493. *
  494. * @param string $expected The expected fixer output
  495. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  496. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  497. */
  498. protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
  499. {
  500. if ($expected === $input) {
  501. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  502. }
  503. $file ??= new \SplFileInfo(__FILE__);
  504. $fileIsSupported = $this->fixer->supports($file);
  505. if (null !== $input) {
  506. self::assertNull($this->lintSource($input));
  507. Tokens::clearCache();
  508. $tokens = Tokens::fromCode($input);
  509. if ($fileIsSupported) {
  510. self::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  511. self::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  512. $this->fixer->fix($file, $tokens);
  513. }
  514. self::assertThat(
  515. $tokens->generateCode(),
  516. new IsIdenticalString($expected),
  517. 'Code build on input code must match expected code.'
  518. );
  519. self::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  520. $tokens->clearEmptyTokens();
  521. self::assertSameSize(
  522. $tokens,
  523. array_unique(array_map(static fn (Token $token): string => spl_object_hash($token), $tokens->toArray())),
  524. 'Token items inside Tokens collection must be unique.'
  525. );
  526. Tokens::clearCache();
  527. $expectedTokens = Tokens::fromCode($expected);
  528. self::assertTokens($expectedTokens, $tokens);
  529. }
  530. self::assertNull($this->lintSource($expected));
  531. Tokens::clearCache();
  532. $tokens = Tokens::fromCode($expected);
  533. if ($fileIsSupported) {
  534. $this->fixer->fix($file, $tokens);
  535. }
  536. self::assertThat(
  537. $tokens->generateCode(),
  538. new IsIdenticalString($expected),
  539. 'Code build on expected code must not change.'
  540. );
  541. self::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  542. }
  543. protected function lintSource(string $source): ?string
  544. {
  545. try {
  546. $this->linter->lintSource($source)->check();
  547. } catch (\Exception $e) {
  548. return $e->getMessage()."\n\nSource:\n{$source}";
  549. }
  550. return null;
  551. }
  552. protected static function assertCorrectCasing(string $haystack, string $needle, string $fixerName, string $descriptionType): void
  553. {
  554. self::assertSame(
  555. substr_count(strtolower($haystack), strtolower($needle)),
  556. substr_count($haystack, $needle),
  557. sprintf('[%s] `%s` must be in correct casing in %s.', $fixerName, $needle, $descriptionType)
  558. );
  559. }
  560. private function getLinter(): LinterInterface
  561. {
  562. static $linter = null;
  563. if (null === $linter) {
  564. $linter = new CachingLinter(
  565. getenv('FAST_LINT_TEST_CASES') ? new Linter() : new ProcessLinter()
  566. );
  567. }
  568. return $linter;
  569. }
  570. private static function assertValidDescription(string $fixerName, string $descriptionType, string $description): void
  571. {
  572. // Description:
  573. // "Option `a` and `b_c` are allowed."
  574. // becomes:
  575. // "Option `_` and `_` are allowed."
  576. // so values in backticks are excluded from check
  577. $descriptionWithExcludedNames = preg_replace('/`([^`]+)`/', '`_`', $description);
  578. self::assertMatchesRegularExpression('/^[A-Z`].+\.$/s', $description, sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
  579. self::assertStringNotContainsString('phpdocs', $descriptionWithExcludedNames, sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType));
  580. self::assertCorrectCasing($descriptionWithExcludedNames, 'PHPDoc', $fixerName, $descriptionType);
  581. self::assertCorrectCasing($descriptionWithExcludedNames, 'PHPUnit', $fixerName, $descriptionType);
  582. self::assertFalse(strpos($descriptionType, '``'), sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
  583. }
  584. /**
  585. * @param list<array{0: int, 1?: string}> $sequence
  586. *
  587. * @return list<non-empty-array<int, Token>>
  588. */
  589. private function findAllTokenSequences(Tokens $tokens, array $sequence): array
  590. {
  591. $lastIndex = 0;
  592. $sequences = [];
  593. while ($found = $tokens->findSequence($sequence, $lastIndex)) {
  594. $keys = array_keys($found);
  595. $sequences[] = $found;
  596. $lastIndex = $keys[2];
  597. }
  598. return $sequences;
  599. }
  600. }