AbstractFixerTestCase.php 31 KB

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