AbstractFixerTestCase.php 31 KB

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