AbstractFixerTestCase.php 31 KB

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