ProjectCodeTest.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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\AutoReview;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
  15. use PhpCsFixer\AbstractPhpdocTypesFixer;
  16. use PhpCsFixer\AbstractProxyFixer;
  17. use PhpCsFixer\Console\Command\FixCommand;
  18. use PhpCsFixer\DocBlock\Annotation;
  19. use PhpCsFixer\DocBlock\DocBlock;
  20. use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
  21. use PhpCsFixer\Fixer\ConfigurableFixerTrait;
  22. use PhpCsFixer\Fixer\PhpUnit\PhpUnitNamespacedFixer;
  23. use PhpCsFixer\FixerFactory;
  24. use PhpCsFixer\Preg;
  25. use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
  26. use PhpCsFixer\Tests\Test\AbstractIntegrationTestCase;
  27. use PhpCsFixer\Tests\TestCase;
  28. use PhpCsFixer\Tokenizer\Token;
  29. use PhpCsFixer\Tokenizer\Tokens;
  30. use PhpCsFixer\Tokenizer\TokensAnalyzer;
  31. use Symfony\Component\Finder\Finder;
  32. use Symfony\Component\Finder\SplFileInfo;
  33. /**
  34. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  35. *
  36. * @internal
  37. *
  38. * @coversNothing
  39. *
  40. * @group auto-review
  41. * @group covers-nothing
  42. */
  43. final class ProjectCodeTest extends TestCase
  44. {
  45. /**
  46. * @var null|array<string, array{class-string<TestCase>}>
  47. */
  48. private static ?array $testClassCases = null;
  49. /**
  50. * @var null|array<string, array{class-string}>
  51. */
  52. private static ?array $srcClassCases = null;
  53. /**
  54. * @var null|array<string, array{class-string, string}>
  55. */
  56. private static ?array $dataProviderMethodCases = null;
  57. /**
  58. * @var array<class-string, Tokens>
  59. */
  60. private static array $tokensCache = [];
  61. public static function tearDownAfterClass(): void
  62. {
  63. self::$srcClassCases = null;
  64. self::$testClassCases = null;
  65. self::$tokensCache = [];
  66. }
  67. /**
  68. * @dataProvider provideThatSrcClassHaveTestClassCases
  69. */
  70. public function testThatSrcClassHaveTestClass(string $className): void
  71. {
  72. $testClassName = 'PhpCsFixer\Tests'.substr($className, 10).'Test';
  73. self::assertTrue(class_exists($testClassName), \sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
  74. }
  75. /**
  76. * @dataProvider provideThatSrcClassesNotAbuseInterfacesCases
  77. *
  78. * @param class-string $className
  79. */
  80. public function testThatSrcClassesNotAbuseInterfaces(string $className): void
  81. {
  82. $rc = new \ReflectionClass($className);
  83. $allowedMethods = array_map(
  84. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  85. $rc->getInterfaces()
  86. );
  87. if (\count($allowedMethods) > 0) {
  88. $allowedMethods = array_unique(array_merge(...array_values($allowedMethods)));
  89. }
  90. $allowedMethods[] = '__construct';
  91. $allowedMethods[] = '__destruct';
  92. $allowedMethods[] = '__wakeup';
  93. $exceptionMethods = [
  94. 'configure', // due to AbstractFixer::configure
  95. 'getConfigurationDefinition', // due to AbstractFixer::getConfigurationDefinition
  96. 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
  97. 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
  98. 'createConfigurationDefinition', // due to AbstractProxyFixer calling `createConfigurationDefinition` of proxied rule
  99. ];
  100. $definedMethods = $this->getPublicMethodNames($rc);
  101. $extraMethods = array_diff(
  102. $definedMethods,
  103. $allowedMethods,
  104. $exceptionMethods
  105. );
  106. sort($extraMethods);
  107. self::assertEmpty(
  108. $extraMethods,
  109. \sprintf(
  110. "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
  111. $className,
  112. implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraMethods))
  113. )
  114. );
  115. }
  116. /**
  117. * @dataProvider provideSrcClassCases
  118. *
  119. * @param class-string $className
  120. */
  121. public function testThatSrcClassesNotExposeProperties(string $className): void
  122. {
  123. $rc = new \ReflectionClass($className);
  124. self::assertEmpty(
  125. $rc->getProperties(\ReflectionProperty::IS_PUBLIC),
  126. \sprintf('Class \'%s\' should not have public properties.', $className)
  127. );
  128. if ($rc->isFinal()) {
  129. return;
  130. }
  131. $allowedProps = [];
  132. $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
  133. if (false !== $rc->getParentClass()) {
  134. $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
  135. }
  136. $allowedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $allowedProps);
  137. $definedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $definedProps);
  138. $exceptionPropsPerClass = [
  139. AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'],
  140. AbstractPhpdocToTypeDeclarationFixer::class => ['configuration'],
  141. AbstractPhpdocTypesFixer::class => ['tags'],
  142. AbstractProxyFixer::class => ['proxyFixers'],
  143. ConfigurableFixerTrait::class => ['configuration'],
  144. FixCommand::class => ['defaultDescription', 'defaultName'], // TODO: PHP 8.0+, remove properties and test when PHP 8+ is required
  145. ];
  146. $extraProps = array_diff(
  147. $definedProps,
  148. $allowedProps,
  149. $exceptionPropsPerClass[$className] ?? []
  150. );
  151. sort($extraProps);
  152. self::assertEmpty(
  153. $extraProps,
  154. \sprintf(
  155. "Class '%s' should not have protected properties.\nViolations:\n%s",
  156. $className,
  157. implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraProps))
  158. )
  159. );
  160. }
  161. /**
  162. * @dataProvider provideTestClassCases
  163. */
  164. public function testThatTestClassExtendsPhpCsFixerTestCaseClass(string $className): void
  165. {
  166. self::assertTrue(is_subclass_of($className, TestCase::class), \sprintf('Expected test class "%s" to be a subclass of "%s".', $className, TestCase::class));
  167. }
  168. /**
  169. * @dataProvider provideTestClassCases
  170. *
  171. * @param class-string<TestCase> $testClassName
  172. */
  173. public function testThatTestClassesAreTraitOrAbstractOrFinal(string $testClassName): void
  174. {
  175. $rc = new \ReflectionClass($testClassName);
  176. self::assertTrue(
  177. $rc->isTrait() || $rc->isAbstract() || $rc->isFinal(),
  178. \sprintf('Test class %s should be trait, abstract or final.', $testClassName)
  179. );
  180. }
  181. /**
  182. * @dataProvider provideTestClassCases
  183. *
  184. * @param class-string<TestCase> $testClassName
  185. */
  186. public function testThatTestClassesAreInternal(string $testClassName): void
  187. {
  188. $rc = new \ReflectionClass($testClassName);
  189. $doc = new DocBlock($rc->getDocComment());
  190. self::assertNotEmpty(
  191. $doc->getAnnotationsOfType('internal'),
  192. \sprintf('Test class %s should have internal annotation.', $testClassName)
  193. );
  194. }
  195. /**
  196. * @dataProvider provideTestClassCases
  197. *
  198. * @param class-string<TestCase> $testClassName
  199. */
  200. public function testThatTestClassesPublicMethodsAreCorrectlyNamed(string $testClassName): void
  201. {
  202. $reflectionClass = new \ReflectionClass($testClassName);
  203. $publicMethods = array_filter(
  204. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  205. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName()
  206. );
  207. if ([] === $publicMethods) {
  208. $this->expectNotToPerformAssertions(); // no methods to test, all good!
  209. return;
  210. }
  211. foreach ($publicMethods as $method) {
  212. self::assertMatchesRegularExpression(
  213. '/^(test|expect|provide|setUpBeforeClass$|tearDownAfterClass$|__construct$)/',
  214. $method->getName(),
  215. \sprintf('Public method "%s::%s" is not properly named.', $reflectionClass->getName(), $method->getName())
  216. );
  217. }
  218. }
  219. /**
  220. * @dataProvider provideDataProviderMethodCases
  221. *
  222. * @param class-string<TestCase> $testClassName
  223. */
  224. public function testThatTestDataProvidersAreUsed(string $testClassName, string $dataProviderName): void
  225. {
  226. $usedDataProviderMethodNames = [];
  227. foreach ($this->getUsedDataProviderMethodNames($testClassName) as $providerName) {
  228. $usedDataProviderMethodNames[] = $providerName;
  229. }
  230. self::assertContains(
  231. $dataProviderName,
  232. $usedDataProviderMethodNames,
  233. \sprintf('Data provider "%s::%s" is not used.', $testClassName, $dataProviderName),
  234. );
  235. }
  236. /**
  237. * @dataProvider provideDataProviderMethodCases
  238. */
  239. public function testThatTestDataProvidersAreCorrectlyNamed(string $testClassName, string $dataProviderName): void
  240. {
  241. self::assertMatchesRegularExpression('/^provide[A-Z]\S+Cases$/', $dataProviderName, \sprintf(
  242. 'Data provider "%s::%s" is not correctly named.',
  243. $testClassName,
  244. $dataProviderName,
  245. ));
  246. }
  247. /**
  248. * @return iterable<string, array{string, string}>
  249. */
  250. public static function provideDataProviderMethodCases(): iterable
  251. {
  252. if (null === self::$dataProviderMethodCases) {
  253. self::$dataProviderMethodCases = [];
  254. foreach (self::provideTestClassCases() as $testClassName) {
  255. $testClassName = reset($testClassName);
  256. $reflectionClass = new \ReflectionClass($testClassName);
  257. $dataProviderNames = array_filter(
  258. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  259. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName() && str_starts_with($reflectionMethod->getName(), 'provide')
  260. );
  261. foreach ($dataProviderNames as $dataProviderName) {
  262. self::$dataProviderMethodCases[$testClassName.'::'.$dataProviderName->getName()] = [$testClassName, $dataProviderName->getName()];
  263. }
  264. }
  265. }
  266. yield from self::$dataProviderMethodCases;
  267. }
  268. /**
  269. * @dataProvider provideTestClassCases
  270. *
  271. * @param class-string<TestCase> $testClassName
  272. */
  273. public function testThatTestClassCoversAreCorrect(string $testClassName): void
  274. {
  275. $reflectionClass = new \ReflectionClass($testClassName);
  276. if ($reflectionClass->isAbstract() || $reflectionClass->isInterface()) {
  277. $this->expectNotToPerformAssertions();
  278. return;
  279. }
  280. $doc = $reflectionClass->getDocComment();
  281. self::assertNotFalse($doc);
  282. if (Preg::match('/@coversNothing/', $doc)) {
  283. return;
  284. }
  285. $covers = Preg::matchAll('/@covers (\S*)/', $doc, $matches);
  286. self::assertGreaterThanOrEqual(1, $covers, \sprintf('Missing @covers in PHPDoc of test class "%s".', $testClassName));
  287. array_shift($matches);
  288. /** @var class-string $class */
  289. $class = '\\'.str_replace('PhpCsFixer\Tests\\', 'PhpCsFixer\\', substr($testClassName, 0, -4));
  290. $parentClass = (new \ReflectionClass($class))->getParentClass();
  291. $parentClassName = false === $parentClass ? null : '\\'.$parentClass->getName();
  292. foreach ($matches as $match) {
  293. $classMatch = array_shift($match);
  294. self::assertTrue(
  295. $classMatch === $class || $parentClassName === $classMatch,
  296. \sprintf('Unexpected @covers "%s" for "%s".', $classMatch, $testClassName)
  297. );
  298. }
  299. }
  300. /**
  301. * @dataProvider provideSrcClassCases
  302. * @dataProvider provideTestClassCases
  303. *
  304. * @param class-string $className
  305. */
  306. public function testThereIsNoUsageOfExtract(string $className): void
  307. {
  308. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  309. $message = \sprintf('Class %s must not use "extract()", explicitly extract only the keys that are needed - you never know what\'s else inside.', $className);
  310. self::assertNotContains('extract', $calledFunctions, $message);
  311. }
  312. /**
  313. * @dataProvider provideThereIsNoPregFunctionUsedDirectlyCases
  314. *
  315. * @param class-string $className
  316. */
  317. public function testThereIsNoPregFunctionUsedDirectly(string $className): void
  318. {
  319. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  320. $message = \sprintf('Class %s must not use preg_*, it shall use Preg::* instead.', $className);
  321. self::assertNotContains('preg_filter', $calledFunctions, $message);
  322. self::assertNotContains('preg_grep', $calledFunctions, $message);
  323. self::assertNotContains('preg_match', $calledFunctions, $message);
  324. self::assertNotContains('preg_match_all', $calledFunctions, $message);
  325. self::assertNotContains('preg_replace', $calledFunctions, $message);
  326. self::assertNotContains('preg_replace_callback', $calledFunctions, $message);
  327. self::assertNotContains('preg_split', $calledFunctions, $message);
  328. }
  329. /**
  330. * @dataProvider provideTestClassCases
  331. *
  332. * @param class-string $className
  333. */
  334. public function testThereIsNoUsageOfSetAccessible(string $className): void
  335. {
  336. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  337. $message = \sprintf('Class %s must not use "setAccessible()", use "Closure::bind()" instead.', $className);
  338. self::assertNotContains('setAccessible', $calledFunctions, $message);
  339. }
  340. /**
  341. * @dataProvider provideTestClassCases
  342. *
  343. * @param class-string<TestCase> $className
  344. */
  345. public function testNoPHPUnitMockUsed(string $className): void
  346. {
  347. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  348. $message = \sprintf('Class %s must not use PHPUnit\'s mock, it shall use anonymous class instead.', $className);
  349. self::assertNotContains('getMockBuilder', $calledFunctions, $message);
  350. self::assertNotContains('createMock', $calledFunctions, $message);
  351. self::assertNotContains('createMockForIntersectionOfInterfaces', $calledFunctions, $message);
  352. self::assertNotContains('createPartialMock', $calledFunctions, $message);
  353. self::assertNotContains('createTestProxy', $calledFunctions, $message);
  354. self::assertNotContains('getMockForAbstractClass', $calledFunctions, $message);
  355. self::assertNotContains('getMockFromWsdl', $calledFunctions, $message);
  356. self::assertNotContains('getMockForTrait', $calledFunctions, $message);
  357. self::assertNotContains('getMockClass', $calledFunctions, $message);
  358. self::assertNotContains('createConfiguredMock', $calledFunctions, $message);
  359. self::assertNotContains('getObjectForTrait', $calledFunctions, $message);
  360. }
  361. /**
  362. * @dataProvider provideTestClassCases
  363. *
  364. * @param class-string<TestCase> $testClassName
  365. */
  366. public function testExpectedInputOrder(string $testClassName): void
  367. {
  368. $reflectionClass = new \ReflectionClass($testClassName);
  369. $publicMethods = array_filter(
  370. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  371. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName()
  372. );
  373. if ([] === $publicMethods) {
  374. $this->expectNotToPerformAssertions(); // no methods to test, all good!
  375. return;
  376. }
  377. /** @var \ReflectionMethod $method */
  378. foreach ($publicMethods as $method) {
  379. $parameters = $method->getParameters();
  380. if (\count($parameters) < 2) {
  381. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  382. continue;
  383. }
  384. $expected = [
  385. 'expected' => false,
  386. 'input' => false,
  387. ];
  388. for ($i = \count($parameters) - 1; $i >= 0; --$i) {
  389. $name = $parameters[$i]->getName();
  390. if (isset($expected[$name])) {
  391. $expected[$name] = $i;
  392. }
  393. }
  394. $expectedFound = array_filter($expected, static fn ($item): bool => false !== $item);
  395. if (\count($expectedFound) < 2) {
  396. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  397. continue;
  398. }
  399. self::assertLessThan(
  400. $expected['input'],
  401. $expected['expected'],
  402. \sprintf('Public method "%s::%s" has parameter \'input\' before \'expected\'.', $reflectionClass->getName(), $method->getName())
  403. );
  404. }
  405. }
  406. /**
  407. * @dataProvider provideDataProviderMethodCases
  408. *
  409. * @param class-string<TestCase> $testClassName
  410. * @param non-empty-string $dataProviderName
  411. */
  412. public function testDataProvidersAreNonPhpVersionConditional(string $testClassName, string $dataProviderName): void
  413. {
  414. $tokens = $this->createTokensForClass($testClassName);
  415. $tokensAnalyzer = new TokensAnalyzer($tokens);
  416. $dataProviderElements = array_filter($tokensAnalyzer->getClassyElements(), static function (array $v, int $k) use ($tokens, $dataProviderName) {
  417. $nextToken = $tokens[$tokens->getNextMeaningfulToken($k)];
  418. // element is data provider method
  419. return 'method' === $v['type'] && $nextToken->equals([T_STRING, $dataProviderName]);
  420. }, ARRAY_FILTER_USE_BOTH);
  421. if (1 !== \count($dataProviderElements)) {
  422. throw new \UnexpectedValueException(\sprintf('Data provider "%s::%s" should be found exactly once, got %d times.', $testClassName, $dataProviderName, \count($dataProviderElements)));
  423. }
  424. $methodIndex = array_key_first($dataProviderElements);
  425. $startIndex = $tokens->getNextTokenOfKind($methodIndex, ['{']);
  426. $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);
  427. $versionTokens = array_filter($tokens->findGivenKind(T_STRING, $startIndex, $endIndex), static function (Token $v): bool {
  428. return $v->equalsAny([
  429. [T_STRING, 'PHP_VERSION_ID'],
  430. [T_STRING, 'PHP_MAJOR_VERSION'],
  431. [T_STRING, 'PHP_MINOR_VERSION'],
  432. [T_STRING, 'PHP_RELEASE_VERSION'],
  433. [T_STRING, 'phpversion'],
  434. ], false);
  435. });
  436. self::assertCount(
  437. 0,
  438. $versionTokens,
  439. \sprintf(
  440. 'Data provider "%s::%s" should not check PHP version and provide different cases depends on it. It leads to situation when DataProvider provides "sometimes 10, sometimes 11" test cases, depends on PHP version. That makes John Doe to see "you run 10/10" and thinking all tests are executed, instead of actually seeing "you run 10/11 and 1 skipped".',
  441. $testClassName,
  442. $dataProviderName,
  443. ),
  444. );
  445. }
  446. /**
  447. * @dataProvider provideDataProviderMethodCases
  448. */
  449. public function testDataProvidersDeclaredReturnType(string $testClassName, string $dataProviderName): void
  450. {
  451. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  452. self::assertSame('iterable', $dataProvider->hasReturnType() && $dataProvider->getReturnType() instanceof \ReflectionNamedType ? $dataProvider->getReturnType()->getName() : null, \sprintf('Data provider "%s::%s" must provide `iterable` as return in method prototype.', $testClassName, $dataProviderName));
  453. $doc = new DocBlock(false !== $dataProvider->getDocComment() ? $dataProvider->getDocComment() : '/** */');
  454. $returnDocs = $doc->getAnnotationsOfType('return');
  455. if (\count($returnDocs) > 1) {
  456. throw new \UnexpectedValueException(\sprintf('Multiple "%s::%s@return" annotations.', $testClassName, $dataProviderName));
  457. }
  458. if (1 !== \count($returnDocs)) {
  459. $this->addToAssertionCount(1); // no @return annotation, all good!
  460. return;
  461. }
  462. $returnDoc = $returnDocs[0];
  463. $types = $returnDoc->getTypes();
  464. self::assertCount(1, $types, \sprintf('Data provider "%s::%s@return" must provide single type.', $testClassName, $dataProviderName));
  465. self::assertMatchesRegularExpression('/^iterable\</', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable.', $testClassName, $dataProviderName));
  466. self::assertMatchesRegularExpression('/^iterable\<(?:(?:int\|)?string, )?array\{/', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable of tuples (eg `iterable<string, array{string, string}>`).', $testClassName, $dataProviderName));
  467. }
  468. /**
  469. * @dataProvider provideSrcClassCases
  470. * @dataProvider provideTestClassCases
  471. *
  472. * @param class-string $className
  473. */
  474. public function testAllCodeContainSingleClassy(string $className): void
  475. {
  476. $headerTypes = [
  477. T_ABSTRACT,
  478. T_AS,
  479. T_COMMENT,
  480. T_DECLARE,
  481. T_DOC_COMMENT,
  482. T_FINAL,
  483. T_LNUMBER,
  484. T_NAMESPACE,
  485. T_NS_SEPARATOR,
  486. T_OPEN_TAG,
  487. T_STRING,
  488. T_USE,
  489. T_WHITESPACE,
  490. ];
  491. if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required
  492. $headerTypes[] = T_READONLY;
  493. }
  494. $tokens = $this->createTokensForClass($className);
  495. $classyIndex = null;
  496. self::assertTrue($tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()), \sprintf('File for "%s" should contains a classy.', $className));
  497. $count = \count($tokens);
  498. for ($index = 1; $index < $count; ++$index) {
  499. if ($tokens[$index]->isClassy()) {
  500. $classyIndex = $index;
  501. break;
  502. }
  503. if (\defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(T_ATTRIBUTE)) {
  504. $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
  505. continue;
  506. }
  507. if (!$tokens[$index]->isGivenKind($headerTypes) && !$tokens[$index]->equalsAny([';', '=', '(', ')'])) {
  508. self::fail(\sprintf('File for "%s" should only contains single classy, found "%s" @ %d.', $className, $tokens[$index]->toJson(), $index));
  509. }
  510. }
  511. self::assertNotNull($classyIndex, \sprintf('File for "%s" does not contain a classy.', $className));
  512. $nextTokenOfKind = $tokens->getNextTokenOfKind($classyIndex, ['{']);
  513. if (!\is_int($nextTokenOfKind)) {
  514. throw new \UnexpectedValueException('Classy without {} - braces.');
  515. }
  516. $classyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextTokenOfKind);
  517. self::assertNull($tokens->getNextMeaningfulToken($classyEndIndex), \sprintf('File for "%s" should only contains a single classy.', $className));
  518. }
  519. /**
  520. * @dataProvider provideSrcClassCases
  521. *
  522. * @param class-string $className
  523. */
  524. public function testInheritdocIsNotAbused(string $className): void
  525. {
  526. $rc = new \ReflectionClass($className);
  527. $allowedMethods = array_map(
  528. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  529. $rc->getInterfaces()
  530. );
  531. if (\count($allowedMethods) > 0) {
  532. $allowedMethods = array_merge(...array_values($allowedMethods));
  533. }
  534. $parentClass = $rc;
  535. while (false !== $parentClass = $parentClass->getParentClass()) {
  536. foreach ($parentClass->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  537. $allowedMethods[] = $method->getName();
  538. }
  539. }
  540. $allowedMethods = array_unique($allowedMethods);
  541. $methodsWithInheritdoc = array_filter(
  542. $rc->getMethods(),
  543. static fn (\ReflectionMethod $rm): bool => false !== $rm->getDocComment() && stripos($rm->getDocComment(), '@inheritdoc')
  544. );
  545. $methodsWithInheritdoc = array_map(
  546. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  547. $methodsWithInheritdoc
  548. );
  549. $extraMethods = array_diff($methodsWithInheritdoc, $allowedMethods);
  550. self::assertEmpty(
  551. $extraMethods,
  552. \sprintf(
  553. "Class '%s' should not have methods with '@inheritdoc' in PHPDoc that are not inheriting PHPDoc.\nViolations:\n%s",
  554. $className,
  555. implode("\n", array_map(static fn ($item): string => " * {$item}", $extraMethods))
  556. )
  557. );
  558. }
  559. /**
  560. * @return iterable<string, array{class-string}>
  561. */
  562. public static function provideSrcClassCases(): iterable
  563. {
  564. if (null === self::$srcClassCases) {
  565. $cases = self::getSrcClasses();
  566. self::$srcClassCases = array_combine(
  567. $cases,
  568. array_map(static fn (string $case): array => [$case], $cases),
  569. );
  570. }
  571. yield from self::$srcClassCases;
  572. }
  573. /**
  574. * @return iterable<array{string}>
  575. */
  576. public static function provideThatSrcClassesNotAbuseInterfacesCases(): iterable
  577. {
  578. return array_map(
  579. static fn (string $item): array => [$item],
  580. array_filter(self::getSrcClasses(), static function (string $className): bool {
  581. $rc = new \ReflectionClass($className);
  582. $doc = false !== $rc->getDocComment()
  583. ? new DocBlock($rc->getDocComment())
  584. : null;
  585. if (
  586. $rc->isInterface()
  587. || (null !== $doc && \count($doc->getAnnotationsOfType('internal')) > 0)
  588. || \in_array($className, [
  589. \PhpCsFixer\Finder::class,
  590. AbstractFixerTestCase::class,
  591. AbstractIntegrationTestCase::class,
  592. Tokens::class,
  593. ], true)
  594. ) {
  595. return false;
  596. }
  597. $interfaces = $rc->getInterfaces();
  598. $interfacesCount = \count($interfaces);
  599. if (0 === $interfacesCount) {
  600. return false;
  601. }
  602. if (1 === $interfacesCount) {
  603. $interface = reset($interfaces);
  604. if (\Stringable::class === $interface->getName()) {
  605. return false;
  606. }
  607. }
  608. return true;
  609. })
  610. );
  611. }
  612. /**
  613. * @return iterable<array{string}>
  614. */
  615. public static function provideThatSrcClassHaveTestClassCases(): iterable
  616. {
  617. return array_map(
  618. static fn (string $item): array => [$item],
  619. array_filter(
  620. self::getSrcClasses(),
  621. static function (string $className): bool {
  622. $rc = new \ReflectionClass($className);
  623. return !$rc->isTrait() && !$rc->isAbstract() && !$rc->isInterface() && \count($rc->getMethods(\ReflectionMethod::IS_PUBLIC)) > 0;
  624. }
  625. )
  626. );
  627. }
  628. public function testAllTestsForShortOpenTagAreHandled(): void
  629. {
  630. $testClassesWithShortOpenTag = array_filter(
  631. self::getTestClasses(),
  632. fn (string $className): bool => str_contains($this->getFileContentForClass($className), 'short_open_tag') && self::class !== $className
  633. );
  634. $testFilesWithShortOpenTag = array_map(
  635. fn (string $className): string => './'.$this->getFilePathForClass($className),
  636. $testClassesWithShortOpenTag
  637. );
  638. $phpunitXmlContent = file_get_contents(__DIR__.'/../../phpunit.xml.dist');
  639. $phpunitFiles = (array) simplexml_load_string($phpunitXmlContent)->xpath('testsuites/testsuite[@name="short-open-tag"]')[0]->file;
  640. sort($testFilesWithShortOpenTag);
  641. sort($phpunitFiles);
  642. self::assertSame($testFilesWithShortOpenTag, $phpunitFiles);
  643. }
  644. /**
  645. * @dataProvider provideTestClassCases
  646. *
  647. * @param class-string $className
  648. */
  649. public function testThatTestMethodsAreNotDuplicated(string $className): void
  650. {
  651. $class = new \ReflectionClass($className);
  652. $alreadyFoundMethods = [];
  653. $duplicates = [];
  654. foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  655. if (!str_starts_with($method->getName(), 'test')) {
  656. continue;
  657. }
  658. $startLine = (int) $method->getStartLine();
  659. $length = (int) $method->getEndLine() - $startLine;
  660. if (3 === $length) { // open and closing brace are included - this checks for single line methods
  661. continue;
  662. }
  663. /** @var list<string> $source */
  664. $source = file((string) $method->getFileName());
  665. $candidateContent = implode('', \array_slice($source, $startLine, $length));
  666. if (str_contains($candidateContent, '$this->doTest(')) {
  667. continue;
  668. }
  669. $foundInDuplicates = false;
  670. foreach ($alreadyFoundMethods as $methodKey => $methodContent) {
  671. if ($candidateContent === $methodContent) {
  672. $duplicates[] = \sprintf('%s is duplicate of %s', $methodKey, $method->getName());
  673. $foundInDuplicates = true;
  674. }
  675. }
  676. if (!$foundInDuplicates) {
  677. $alreadyFoundMethods[$method->getName()] = $candidateContent;
  678. }
  679. }
  680. self::assertSame(
  681. [],
  682. $duplicates,
  683. \sprintf(
  684. "Duplicated methods found in %s:\n - %s",
  685. $className,
  686. implode("\n - ", $duplicates)
  687. )
  688. );
  689. }
  690. /**
  691. * @dataProvider provideDataProviderMethodCases
  692. *
  693. * @param class-string<TestCase> $testClassName
  694. */
  695. public function testThatDataFromDataProvidersIsNotDuplicated(string $testClassName, string $dataProviderName): void
  696. {
  697. $exceptions = [ // should only shrink
  698. 'PhpCsFixer\Tests\AutoReview\CommandTest::provideCommandHasNameConstCases',
  699. 'PhpCsFixer\Tests\AutoReview\DocumentationTest::provideFixerDocumentationFileIsUpToDateCases',
  700. 'PhpCsFixer\Tests\AutoReview\FixerFactoryTest::providePriorityIntegrationTestFilesAreListedInPriorityGraphCases',
  701. 'PhpCsFixer\Tests\Console\Command\DescribeCommandTest::provideExecuteOutputCases',
  702. 'PhpCsFixer\Tests\Console\Command\HelpCommandTest::provideGetDisplayableAllowedValuesCases',
  703. 'PhpCsFixer\Tests\Documentation\FixerDocumentGeneratorTest::provideGenerateRuleSetsDocumentationCases',
  704. 'PhpCsFixer\Tests\Fixer\Basic\EncodingFixerTest::provideFixCases',
  705. 'PhpCsFixer\Tests\UtilsTest::provideStableSortCases',
  706. ];
  707. if (\in_array($testClassName.'::'.$dataProviderName, $exceptions, true)) {
  708. $this->addToAssertionCount(1);
  709. return;
  710. }
  711. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  712. $duplicates = [];
  713. $alreadyFoundCases = [];
  714. foreach ($dataProvider->invoke($dataProvider->getDeclaringClass()->newInstanceWithoutConstructor()) as $candidateKey => $candidateData) {
  715. $candidateData = serialize($candidateData);
  716. $foundInDuplicates = false;
  717. foreach ($alreadyFoundCases as $caseKey => $caseData) {
  718. if ($candidateData === $caseData) {
  719. $duplicates[] = \sprintf(
  720. 'Duplicate in %s::%s: %s and %s.'.PHP_EOL,
  721. $testClassName,
  722. $dataProviderName,
  723. \is_int($caseKey) ? '#'.$caseKey : '"'.$caseKey.'"',
  724. \is_int($candidateKey) ? '#'.$candidateKey : '"'.$candidateKey.'"',
  725. );
  726. $foundInDuplicates = true;
  727. }
  728. }
  729. if (!$foundInDuplicates) {
  730. $alreadyFoundCases[$candidateKey] = $candidateData;
  731. }
  732. }
  733. self::assertSame([], $duplicates);
  734. }
  735. /**
  736. * @return iterable<string, array{class-string<TestCase>}>
  737. */
  738. public static function provideTestClassCases(): iterable
  739. {
  740. if (null === self::$testClassCases) {
  741. $cases = self::getTestClasses();
  742. self::$testClassCases = array_combine(
  743. $cases,
  744. array_map(static fn (string $case): array => [$case], $cases),
  745. );
  746. }
  747. yield from self::$testClassCases;
  748. }
  749. /**
  750. * @return iterable<array{string}>
  751. */
  752. public static function provideThereIsNoPregFunctionUsedDirectlyCases(): iterable
  753. {
  754. return array_map(
  755. static fn (string $item): array => [$item],
  756. array_filter(
  757. self::getSrcClasses(),
  758. static fn (string $className): bool => Preg::class !== $className,
  759. ),
  760. );
  761. }
  762. /**
  763. * @dataProvider providePhpUnitFixerExtendsAbstractPhpUnitFixerCases
  764. *
  765. * @param class-string $className
  766. */
  767. public function testPhpUnitFixerExtendsAbstractPhpUnitFixer(string $className): void
  768. {
  769. $reflection = new \ReflectionClass($className);
  770. self::assertTrue($reflection->isSubclassOf(AbstractPhpUnitFixer::class));
  771. }
  772. /**
  773. * @return iterable<array{string}>
  774. */
  775. public static function providePhpUnitFixerExtendsAbstractPhpUnitFixerCases(): iterable
  776. {
  777. $factory = new FixerFactory();
  778. $factory->registerBuiltInFixers();
  779. foreach ($factory->getFixers() as $fixer) {
  780. if (!str_starts_with($fixer->getName(), 'php_unit_')) {
  781. continue;
  782. }
  783. // this one fixes usage of PHPUnit classes
  784. if ($fixer instanceof PhpUnitNamespacedFixer) {
  785. continue;
  786. }
  787. if ($fixer instanceof AbstractProxyFixer) {
  788. continue;
  789. }
  790. yield [\get_class($fixer)];
  791. }
  792. }
  793. /**
  794. * @dataProvider provideSrcClassCases
  795. * @dataProvider provideTestClassCases
  796. *
  797. * @param class-string $className
  798. */
  799. public function testConstantsAreInUpperCase(string $className): void
  800. {
  801. $rc = new \ReflectionClass($className);
  802. $reflectionClassConstants = $rc->getReflectionConstants();
  803. if (\count($reflectionClassConstants) < 1) {
  804. $this->expectNotToPerformAssertions();
  805. return;
  806. }
  807. foreach ($reflectionClassConstants as $constant) {
  808. $constantName = $constant->getName();
  809. self::assertSame(strtoupper($constantName), $constantName, $className);
  810. }
  811. }
  812. /**
  813. * @param class-string $className
  814. *
  815. * @return list<string>
  816. */
  817. private function extractFunctionNamesCalledInClass(string $className): array
  818. {
  819. $tokens = $this->createTokensForClass($className);
  820. $stringTokens = array_filter(
  821. $tokens->toArray(),
  822. static fn (Token $token): bool => $token->isGivenKind(T_STRING)
  823. );
  824. $strings = array_map(
  825. static fn (Token $token): string => $token->getContent(),
  826. $stringTokens
  827. );
  828. return array_unique($strings);
  829. }
  830. /**
  831. * @param class-string $className
  832. */
  833. private function getFilePathForClass(string $className): string
  834. {
  835. $file = $className;
  836. $file = preg_replace('#^PhpCsFixer\\\Tests\\\#', 'tests\\', $file);
  837. $file = preg_replace('#^PhpCsFixer\\\#', 'src\\', $file);
  838. return str_replace('\\', \DIRECTORY_SEPARATOR, $file).'.php';
  839. }
  840. /**
  841. * @param class-string $className
  842. */
  843. private function getFileContentForClass(string $className): string
  844. {
  845. return file_get_contents($this->getFilePathForClass($className));
  846. }
  847. /**
  848. * @param class-string $className
  849. */
  850. private function createTokensForClass(string $className): Tokens
  851. {
  852. if (!isset(self::$tokensCache[$className])) {
  853. self::$tokensCache[$className] = Tokens::fromCode(self::getFileContentForClass($className));
  854. }
  855. return self::$tokensCache[$className];
  856. }
  857. /**
  858. * @param class-string<TestCase> $testClassName
  859. *
  860. * @return iterable<string, string>
  861. */
  862. private function getUsedDataProviderMethodNames(string $testClassName): iterable
  863. {
  864. foreach ($this->getAnnotationsOfTestClass($testClassName, 'dataProvider') as $methodName => $dataProviderAnnotation) {
  865. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  866. yield $methodName => $matches['methodName'];
  867. }
  868. }
  869. }
  870. /**
  871. * @param class-string<TestCase> $testClassName
  872. *
  873. * @return iterable<string, Annotation>
  874. */
  875. private function getAnnotationsOfTestClass(string $testClassName, string $annotation): iterable
  876. {
  877. $tokens = $this->createTokensForClass($testClassName);
  878. foreach ($tokens as $index => $token) {
  879. if (!$token->isGivenKind(T_DOC_COMMENT)) {
  880. continue;
  881. }
  882. $methodName = $tokens[$tokens->getNextTokenOfKind($index, [[T_STRING]])]->getContent();
  883. $docBlock = new DocBlock($token->getContent());
  884. $dataProviderAnnotations = $docBlock->getAnnotationsOfType($annotation);
  885. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  886. yield $methodName => $dataProviderAnnotation;
  887. }
  888. }
  889. }
  890. /**
  891. * @return list<class-string>
  892. */
  893. private static function getSrcClasses(): array
  894. {
  895. static $classes;
  896. if (null !== $classes) {
  897. return $classes;
  898. }
  899. $finder = Finder::create()
  900. ->files()
  901. ->name('*.php')
  902. ->in(__DIR__.'/../../src')
  903. ->exclude([
  904. 'Resources',
  905. ])
  906. ;
  907. /** @var list<class-string> $classes */
  908. $classes = array_map(
  909. static fn (SplFileInfo $file): string => \sprintf(
  910. '%s\%s%s%s',
  911. 'PhpCsFixer',
  912. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  913. '' !== $file->getRelativePath() ? '\\' : '',
  914. $file->getBasename('.'.$file->getExtension())
  915. ),
  916. iterator_to_array($finder, false)
  917. );
  918. sort($classes);
  919. return $classes;
  920. }
  921. /**
  922. * @return list<class-string<TestCase>>
  923. */
  924. private static function getTestClasses(): array
  925. {
  926. static $classes;
  927. if (null !== $classes) {
  928. return $classes;
  929. }
  930. $finder = Finder::create()
  931. ->files()
  932. ->name('*Test.php')
  933. ->in(__DIR__.'/..')
  934. ->exclude([
  935. 'Fixtures',
  936. ])
  937. ;
  938. /** @var list<class-string<TestCase>> $classes */
  939. $classes = array_map(
  940. static fn (SplFileInfo $file): string => \sprintf(
  941. 'PhpCsFixer\Tests\%s%s%s',
  942. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  943. '' !== $file->getRelativePath() ? '\\' : '',
  944. $file->getBasename('.'.$file->getExtension())
  945. ),
  946. iterator_to_array($finder, false)
  947. );
  948. sort($classes);
  949. return $classes;
  950. }
  951. /**
  952. * @param \ReflectionClass<object> $rc
  953. *
  954. * @return list<string>
  955. */
  956. private function getPublicMethodNames(\ReflectionClass $rc): array
  957. {
  958. return array_map(
  959. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  960. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  961. );
  962. }
  963. }