AbstractFixerTestCase.php 31 KB

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