ProjectCodeTest.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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'],
  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<TestCase> $className
  333. */
  334. public function testNoPHPUnitMockUsed(string $className): void
  335. {
  336. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  337. $message = \sprintf('Class %s must not use PHPUnit\'s mock, it shall use anonymous class instead.', $className);
  338. self::assertNotContains('getMockBuilder', $calledFunctions, $message);
  339. self::assertNotContains('createMock', $calledFunctions, $message);
  340. self::assertNotContains('createMockForIntersectionOfInterfaces', $calledFunctions, $message);
  341. self::assertNotContains('createPartialMock', $calledFunctions, $message);
  342. self::assertNotContains('createTestProxy', $calledFunctions, $message);
  343. self::assertNotContains('getMockForAbstractClass', $calledFunctions, $message);
  344. self::assertNotContains('getMockFromWsdl', $calledFunctions, $message);
  345. self::assertNotContains('getMockForTrait', $calledFunctions, $message);
  346. self::assertNotContains('getMockClass', $calledFunctions, $message);
  347. self::assertNotContains('createConfiguredMock', $calledFunctions, $message);
  348. self::assertNotContains('getObjectForTrait', $calledFunctions, $message);
  349. }
  350. /**
  351. * @dataProvider provideTestClassCases
  352. *
  353. * @param class-string<TestCase> $testClassName
  354. */
  355. public function testExpectedInputOrder(string $testClassName): void
  356. {
  357. $reflectionClass = new \ReflectionClass($testClassName);
  358. $publicMethods = array_filter(
  359. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  360. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName()
  361. );
  362. if ([] === $publicMethods) {
  363. $this->expectNotToPerformAssertions(); // no methods to test, all good!
  364. return;
  365. }
  366. /** @var \ReflectionMethod $method */
  367. foreach ($publicMethods as $method) {
  368. $parameters = $method->getParameters();
  369. if (\count($parameters) < 2) {
  370. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  371. continue;
  372. }
  373. $expected = [
  374. 'expected' => false,
  375. 'input' => false,
  376. ];
  377. for ($i = \count($parameters) - 1; $i >= 0; --$i) {
  378. $name = $parameters[$i]->getName();
  379. if (isset($expected[$name])) {
  380. $expected[$name] = $i;
  381. }
  382. }
  383. $expected = array_filter($expected, static fn ($item): bool => false !== $item);
  384. if (\count($expected) < 2) {
  385. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  386. continue;
  387. }
  388. self::assertLessThan(
  389. $expected['input'],
  390. $expected['expected'],
  391. \sprintf('Public method "%s::%s" has parameter \'input\' before \'expected\'.', $reflectionClass->getName(), $method->getName())
  392. );
  393. }
  394. }
  395. /**
  396. * @dataProvider provideDataProviderMethodCases
  397. *
  398. * @param class-string<TestCase> $testClassName
  399. */
  400. public function testDataProvidersAreNonPhpVersionConditional(string $testClassName, string $dataProviderName): void
  401. {
  402. $tokens = $this->createTokensForClass($testClassName);
  403. $tokensAnalyzer = new TokensAnalyzer($tokens);
  404. $dataProviderElements = array_filter($tokensAnalyzer->getClassyElements(), static function (array $v, int $k) use ($tokens, $dataProviderName) {
  405. $nextToken = $tokens[$tokens->getNextMeaningfulToken($k)];
  406. // element is data provider method
  407. return 'method' === $v['type'] && $nextToken->equals([T_STRING, $dataProviderName]);
  408. }, ARRAY_FILTER_USE_BOTH);
  409. if (1 !== \count($dataProviderElements)) {
  410. throw new \UnexpectedValueException(\sprintf('Data provider "%s::%s" should be found exactly once, got %d times.', $testClassName, $dataProviderName, \count($dataProviderElements)));
  411. }
  412. $methodIndex = array_key_first($dataProviderElements);
  413. $startIndex = $tokens->getNextTokenOfKind($methodIndex, ['{']);
  414. $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);
  415. $versionTokens = array_filter($tokens->findGivenKind(T_STRING, $startIndex, $endIndex), static function (Token $v): bool {
  416. return $v->equalsAny([
  417. [T_STRING, 'PHP_VERSION_ID'],
  418. [T_STRING, 'PHP_MAJOR_VERSION'],
  419. [T_STRING, 'PHP_MINOR_VERSION'],
  420. [T_STRING, 'PHP_RELEASE_VERSION'],
  421. [T_STRING, 'phpversion'],
  422. ], false);
  423. });
  424. self::assertCount(
  425. 0,
  426. $versionTokens,
  427. \sprintf(
  428. '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".',
  429. $testClassName,
  430. $dataProviderName,
  431. ),
  432. );
  433. }
  434. /**
  435. * @dataProvider provideDataProviderMethodCases
  436. */
  437. public function testDataProvidersDeclaredReturnType(string $testClassName, string $dataProviderName): void
  438. {
  439. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  440. 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));
  441. $doc = new DocBlock(false !== $dataProvider->getDocComment() ? $dataProvider->getDocComment() : '/** */');
  442. $returnDocs = $doc->getAnnotationsOfType('return');
  443. if (\count($returnDocs) > 1) {
  444. throw new \UnexpectedValueException(\sprintf('Multiple "%s::%s@return" annotations.', $testClassName, $dataProviderName));
  445. }
  446. if (1 !== \count($returnDocs)) {
  447. $this->addToAssertionCount(1); // no @return annotation, all good!
  448. return;
  449. }
  450. $returnDoc = $returnDocs[0];
  451. $types = $returnDoc->getTypes();
  452. self::assertCount(1, $types, \sprintf('Data provider "%s::%s@return" must provide single type.', $testClassName, $dataProviderName));
  453. self::assertMatchesRegularExpression('/^iterable\</', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable.', $testClassName, $dataProviderName));
  454. 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));
  455. }
  456. /**
  457. * @dataProvider provideSrcClassCases
  458. * @dataProvider provideTestClassCases
  459. *
  460. * @param class-string $className
  461. */
  462. public function testAllCodeContainSingleClassy(string $className): void
  463. {
  464. $headerTypes = [
  465. T_ABSTRACT,
  466. T_AS,
  467. T_COMMENT,
  468. T_DECLARE,
  469. T_DOC_COMMENT,
  470. T_FINAL,
  471. T_LNUMBER,
  472. T_NAMESPACE,
  473. T_NS_SEPARATOR,
  474. T_OPEN_TAG,
  475. T_STRING,
  476. T_USE,
  477. T_WHITESPACE,
  478. ];
  479. $tokens = $this->createTokensForClass($className);
  480. $classyIndex = null;
  481. self::assertTrue($tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()), \sprintf('File for "%s" should contains a classy.', $className));
  482. $count = \count($tokens);
  483. for ($index = 1; $index < $count; ++$index) {
  484. if ($tokens[$index]->isClassy()) {
  485. $classyIndex = $index;
  486. break;
  487. }
  488. if (\defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(T_ATTRIBUTE)) {
  489. $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
  490. continue;
  491. }
  492. if (!$tokens[$index]->isGivenKind($headerTypes) && !$tokens[$index]->equalsAny([';', '=', '(', ')'])) {
  493. self::fail(\sprintf('File for "%s" should only contains single classy, found "%s" @ %d.', $className, $tokens[$index]->toJson(), $index));
  494. }
  495. }
  496. self::assertNotNull($classyIndex, \sprintf('File for "%s" does not contain a classy.', $className));
  497. $nextTokenOfKind = $tokens->getNextTokenOfKind($classyIndex, ['{']);
  498. if (!\is_int($nextTokenOfKind)) {
  499. throw new \UnexpectedValueException('Classy without {} - braces.');
  500. }
  501. $classyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextTokenOfKind);
  502. self::assertNull($tokens->getNextMeaningfulToken($classyEndIndex), \sprintf('File for "%s" should only contains a single classy.', $className));
  503. }
  504. /**
  505. * @dataProvider provideSrcClassCases
  506. *
  507. * @param class-string $className
  508. */
  509. public function testInheritdocIsNotAbused(string $className): void
  510. {
  511. $rc = new \ReflectionClass($className);
  512. $allowedMethods = array_map(
  513. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  514. $rc->getInterfaces()
  515. );
  516. if (\count($allowedMethods) > 0) {
  517. $allowedMethods = array_merge(...array_values($allowedMethods));
  518. }
  519. $parentClass = $rc;
  520. while (false !== $parentClass = $parentClass->getParentClass()) {
  521. foreach ($parentClass->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  522. $allowedMethods[] = $method->getName();
  523. }
  524. }
  525. $allowedMethods = array_unique($allowedMethods);
  526. $methodsWithInheritdoc = array_filter(
  527. $rc->getMethods(),
  528. static fn (\ReflectionMethod $rm): bool => false !== $rm->getDocComment() && stripos($rm->getDocComment(), '@inheritdoc')
  529. );
  530. $methodsWithInheritdoc = array_map(
  531. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  532. $methodsWithInheritdoc
  533. );
  534. $extraMethods = array_diff($methodsWithInheritdoc, $allowedMethods);
  535. self::assertEmpty(
  536. $extraMethods,
  537. \sprintf(
  538. "Class '%s' should not have methods with '@inheritdoc' in PHPDoc that are not inheriting PHPDoc.\nViolations:\n%s",
  539. $className,
  540. implode("\n", array_map(static fn ($item): string => " * {$item}", $extraMethods))
  541. )
  542. );
  543. }
  544. /**
  545. * @return iterable<string, array{class-string}>
  546. */
  547. public static function provideSrcClassCases(): iterable
  548. {
  549. if (null === self::$srcClassCases) {
  550. $cases = self::getSrcClasses();
  551. self::$srcClassCases = array_combine(
  552. $cases,
  553. array_map(static fn (string $case): array => [$case], $cases),
  554. );
  555. }
  556. yield from self::$srcClassCases;
  557. }
  558. /**
  559. * @return iterable<array{string}>
  560. */
  561. public static function provideThatSrcClassesNotAbuseInterfacesCases(): iterable
  562. {
  563. return array_map(
  564. static fn (string $item): array => [$item],
  565. array_filter(self::getSrcClasses(), static function (string $className): bool {
  566. $rc = new \ReflectionClass($className);
  567. $doc = false !== $rc->getDocComment()
  568. ? new DocBlock($rc->getDocComment())
  569. : null;
  570. if (
  571. $rc->isInterface()
  572. || (null !== $doc && \count($doc->getAnnotationsOfType('internal')) > 0)
  573. || \in_array($className, [
  574. \PhpCsFixer\Finder::class,
  575. AbstractFixerTestCase::class,
  576. AbstractIntegrationTestCase::class,
  577. Tokens::class,
  578. ], true)
  579. ) {
  580. return false;
  581. }
  582. $interfaces = $rc->getInterfaces();
  583. $interfacesCount = \count($interfaces);
  584. if (0 === $interfacesCount) {
  585. return false;
  586. }
  587. if (1 === $interfacesCount) {
  588. $interface = reset($interfaces);
  589. if (\Stringable::class === $interface->getName()) {
  590. return false;
  591. }
  592. }
  593. return true;
  594. })
  595. );
  596. }
  597. /**
  598. * @return iterable<array{string}>
  599. */
  600. public static function provideThatSrcClassHaveTestClassCases(): iterable
  601. {
  602. return array_map(
  603. static fn (string $item): array => [$item],
  604. array_filter(
  605. self::getSrcClasses(),
  606. static function (string $className): bool {
  607. $rc = new \ReflectionClass($className);
  608. return !$rc->isTrait() && !$rc->isAbstract() && !$rc->isInterface() && \count($rc->getMethods(\ReflectionMethod::IS_PUBLIC)) > 0;
  609. }
  610. )
  611. );
  612. }
  613. public function testAllTestsForShortOpenTagAreHandled(): void
  614. {
  615. $testClassesWithShortOpenTag = array_filter(
  616. self::getTestClasses(),
  617. fn (string $className): bool => str_contains($this->getFileContentForClass($className), 'short_open_tag') && self::class !== $className
  618. );
  619. $testFilesWithShortOpenTag = array_map(
  620. fn (string $className): string => './'.$this->getFilePathForClass($className),
  621. $testClassesWithShortOpenTag
  622. );
  623. $phpunitXmlContent = file_get_contents(__DIR__.'/../../phpunit.xml.dist');
  624. $phpunitFiles = (array) simplexml_load_string($phpunitXmlContent)->xpath('testsuites/testsuite[@name="short-open-tag"]')[0]->file;
  625. sort($testFilesWithShortOpenTag);
  626. sort($phpunitFiles);
  627. self::assertSame($testFilesWithShortOpenTag, $phpunitFiles);
  628. }
  629. /**
  630. * @dataProvider provideTestClassCases
  631. *
  632. * @param class-string $className
  633. */
  634. public function testThatTestMethodsAreNotDuplicated(string $className): void
  635. {
  636. $class = new \ReflectionClass($className);
  637. $alreadyFoundMethods = [];
  638. $duplicates = [];
  639. foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  640. if (!str_starts_with($method->getName(), 'test')) {
  641. continue;
  642. }
  643. $startLine = (int) $method->getStartLine();
  644. $length = (int) $method->getEndLine() - $startLine;
  645. if (3 === $length) { // open and closing brace are included - this checks for single line methods
  646. continue;
  647. }
  648. /** @var list<string> $source */
  649. $source = file((string) $method->getFileName());
  650. $candidateContent = implode('', \array_slice($source, $startLine, $length));
  651. if (str_contains($candidateContent, '$this->doTest(')) {
  652. continue;
  653. }
  654. $foundInDuplicates = false;
  655. foreach ($alreadyFoundMethods as $methodKey => $methodContent) {
  656. if ($candidateContent === $methodContent) {
  657. $duplicates[] = \sprintf('%s is duplicate of %s', $methodKey, $method->getName());
  658. $foundInDuplicates = true;
  659. }
  660. }
  661. if (!$foundInDuplicates) {
  662. $alreadyFoundMethods[$method->getName()] = $candidateContent;
  663. }
  664. }
  665. self::assertSame(
  666. [],
  667. $duplicates,
  668. \sprintf(
  669. "Duplicated methods found in %s:\n - %s",
  670. $className,
  671. implode("\n - ", $duplicates)
  672. )
  673. );
  674. }
  675. /**
  676. * @dataProvider provideDataProviderMethodCases
  677. *
  678. * @param class-string<TestCase> $testClassName
  679. */
  680. public function testThatDataFromDataProvidersIsNotDuplicated(string $testClassName, string $dataProviderName): void
  681. {
  682. $exceptions = [ // should only shrink
  683. 'PhpCsFixer\Tests\AutoReview\CommandTest::provideCommandHasNameConstCases',
  684. 'PhpCsFixer\Tests\AutoReview\DocumentationTest::provideFixerDocumentationFileIsUpToDateCases',
  685. 'PhpCsFixer\Tests\AutoReview\FixerFactoryTest::providePriorityIntegrationTestFilesAreListedInPriorityGraphCases',
  686. 'PhpCsFixer\Tests\Console\Command\DescribeCommandTest::provideExecuteOutputCases',
  687. 'PhpCsFixer\Tests\Console\Command\HelpCommandTest::provideGetDisplayableAllowedValuesCases',
  688. 'PhpCsFixer\Tests\Documentation\FixerDocumentGeneratorTest::provideGenerateRuleSetsDocumentationCases',
  689. 'PhpCsFixer\Tests\Fixer\Basic\EncodingFixerTest::provideFixCases',
  690. 'PhpCsFixer\Tests\UtilsTest::provideStableSortCases',
  691. ];
  692. if (\in_array($testClassName.'::'.$dataProviderName, $exceptions, true)) {
  693. $this->addToAssertionCount(1);
  694. return;
  695. }
  696. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  697. $duplicates = [];
  698. $alreadyFoundCases = [];
  699. foreach ($dataProvider->invoke($dataProvider->getDeclaringClass()->newInstanceWithoutConstructor()) as $candidateKey => $candidateData) {
  700. $candidateData = serialize($candidateData);
  701. $foundInDuplicates = false;
  702. foreach ($alreadyFoundCases as $caseKey => $caseData) {
  703. if ($candidateData === $caseData) {
  704. $duplicates[] = \sprintf(
  705. 'Duplicate in %s::%s: %s and %s.'.PHP_EOL,
  706. $testClassName,
  707. $dataProviderName,
  708. \is_int($caseKey) ? '#'.$caseKey : '"'.$caseKey.'"',
  709. \is_int($candidateKey) ? '#'.$candidateKey : '"'.$candidateKey.'"',
  710. );
  711. $foundInDuplicates = true;
  712. }
  713. }
  714. if (!$foundInDuplicates) {
  715. $alreadyFoundCases[$candidateKey] = $candidateData;
  716. }
  717. }
  718. self::assertSame([], $duplicates);
  719. }
  720. /**
  721. * @return iterable<string, array{class-string<TestCase>}>
  722. */
  723. public static function provideTestClassCases(): iterable
  724. {
  725. if (null === self::$testClassCases) {
  726. $cases = self::getTestClasses();
  727. self::$testClassCases = array_combine(
  728. $cases,
  729. array_map(static fn (string $case): array => [$case], $cases),
  730. );
  731. }
  732. yield from self::$testClassCases;
  733. }
  734. /**
  735. * @return iterable<array{string}>
  736. */
  737. public static function provideThereIsNoPregFunctionUsedDirectlyCases(): iterable
  738. {
  739. return array_map(
  740. static fn (string $item): array => [$item],
  741. array_filter(
  742. self::getSrcClasses(),
  743. static fn (string $className): bool => Preg::class !== $className,
  744. ),
  745. );
  746. }
  747. /**
  748. * @dataProvider providePhpUnitFixerExtendsAbstractPhpUnitFixerCases
  749. *
  750. * @param class-string $className
  751. */
  752. public function testPhpUnitFixerExtendsAbstractPhpUnitFixer(string $className): void
  753. {
  754. $reflection = new \ReflectionClass($className);
  755. self::assertTrue($reflection->isSubclassOf(AbstractPhpUnitFixer::class));
  756. }
  757. /**
  758. * @return iterable<array{string}>
  759. */
  760. public static function providePhpUnitFixerExtendsAbstractPhpUnitFixerCases(): iterable
  761. {
  762. $factory = new FixerFactory();
  763. $factory->registerBuiltInFixers();
  764. foreach ($factory->getFixers() as $fixer) {
  765. if (!str_starts_with($fixer->getName(), 'php_unit_')) {
  766. continue;
  767. }
  768. // this one fixes usage of PHPUnit classes
  769. if ($fixer instanceof PhpUnitNamespacedFixer) {
  770. continue;
  771. }
  772. if ($fixer instanceof AbstractProxyFixer) {
  773. continue;
  774. }
  775. yield [\get_class($fixer)];
  776. }
  777. }
  778. /**
  779. * @dataProvider provideSrcClassCases
  780. * @dataProvider provideTestClassCases
  781. *
  782. * @param class-string $className
  783. */
  784. public function testConstantsAreInUpperCase(string $className): void
  785. {
  786. $rc = new \ReflectionClass($className);
  787. $reflectionClassConstants = $rc->getReflectionConstants();
  788. if (\count($reflectionClassConstants) < 1) {
  789. $this->expectNotToPerformAssertions();
  790. return;
  791. }
  792. foreach ($reflectionClassConstants as $constant) {
  793. $constantName = $constant->getName();
  794. self::assertSame(strtoupper($constantName), $constantName, $className);
  795. }
  796. }
  797. /**
  798. * @param class-string $className
  799. *
  800. * @return list<string>
  801. */
  802. private function extractFunctionNamesCalledInClass(string $className): array
  803. {
  804. $tokens = $this->createTokensForClass($className);
  805. $stringTokens = array_filter(
  806. $tokens->toArray(),
  807. static fn (Token $token): bool => $token->isGivenKind(T_STRING)
  808. );
  809. $strings = array_map(
  810. static fn (Token $token): string => $token->getContent(),
  811. $stringTokens
  812. );
  813. return array_unique($strings);
  814. }
  815. /**
  816. * @param class-string $className
  817. */
  818. private function getFilePathForClass(string $className): string
  819. {
  820. $file = $className;
  821. $file = preg_replace('#^PhpCsFixer\\\Tests\\\#', 'tests\\', $file);
  822. $file = preg_replace('#^PhpCsFixer\\\#', 'src\\', $file);
  823. return str_replace('\\', \DIRECTORY_SEPARATOR, $file).'.php';
  824. }
  825. /**
  826. * @param class-string $className
  827. */
  828. private function getFileContentForClass(string $className): string
  829. {
  830. return file_get_contents($this->getFilePathForClass($className));
  831. }
  832. /**
  833. * @param class-string $className
  834. */
  835. private function createTokensForClass(string $className): Tokens
  836. {
  837. if (!isset(self::$tokensCache[$className])) {
  838. self::$tokensCache[$className] = Tokens::fromCode(self::getFileContentForClass($className));
  839. }
  840. return self::$tokensCache[$className];
  841. }
  842. /**
  843. * @param class-string<TestCase> $testClassName
  844. *
  845. * @return iterable<string, string>
  846. */
  847. private function getUsedDataProviderMethodNames(string $testClassName): iterable
  848. {
  849. foreach ($this->getAnnotationsOfTestClass($testClassName, 'dataProvider') as $methodName => $dataProviderAnnotation) {
  850. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  851. yield $methodName => $matches['methodName'];
  852. }
  853. }
  854. }
  855. /**
  856. * @param class-string<TestCase> $testClassName
  857. *
  858. * @return iterable<string, Annotation>
  859. */
  860. private function getAnnotationsOfTestClass(string $testClassName, string $annotation): iterable
  861. {
  862. $tokens = $this->createTokensForClass($testClassName);
  863. foreach ($tokens as $index => $token) {
  864. if (!$token->isGivenKind(T_DOC_COMMENT)) {
  865. continue;
  866. }
  867. $methodName = $tokens[$tokens->getNextTokenOfKind($index, [[T_STRING]])]->getContent();
  868. $docBlock = new DocBlock($token->getContent());
  869. $dataProviderAnnotations = $docBlock->getAnnotationsOfType($annotation);
  870. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  871. yield $methodName => $dataProviderAnnotation;
  872. }
  873. }
  874. }
  875. /**
  876. * @return list<class-string>
  877. */
  878. private static function getSrcClasses(): array
  879. {
  880. static $classes;
  881. if (null !== $classes) {
  882. return $classes;
  883. }
  884. $finder = Finder::create()
  885. ->files()
  886. ->name('*.php')
  887. ->in(__DIR__.'/../../src')
  888. ->exclude([
  889. 'Resources',
  890. ])
  891. ;
  892. /** @var list<class-string> $classes */
  893. $classes = array_map(
  894. static fn (SplFileInfo $file): string => \sprintf(
  895. '%s\%s%s%s',
  896. 'PhpCsFixer',
  897. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  898. '' !== $file->getRelativePath() ? '\\' : '',
  899. $file->getBasename('.'.$file->getExtension())
  900. ),
  901. iterator_to_array($finder, false)
  902. );
  903. sort($classes);
  904. return $classes;
  905. }
  906. /**
  907. * @return list<class-string<TestCase>>
  908. */
  909. private static function getTestClasses(): array
  910. {
  911. static $classes;
  912. if (null !== $classes) {
  913. return $classes;
  914. }
  915. $finder = Finder::create()
  916. ->files()
  917. ->name('*Test.php')
  918. ->in(__DIR__.'/..')
  919. ->exclude([
  920. 'Fixtures',
  921. ])
  922. ;
  923. /** @var list<class-string<TestCase>> $classes */
  924. $classes = array_map(
  925. static fn (SplFileInfo $file): string => \sprintf(
  926. 'PhpCsFixer\Tests\%s%s%s',
  927. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  928. '' !== $file->getRelativePath() ? '\\' : '',
  929. $file->getBasename('.'.$file->getExtension())
  930. ),
  931. iterator_to_array($finder, false)
  932. );
  933. sort($classes);
  934. return $classes;
  935. }
  936. /**
  937. * @param \ReflectionClass<object> $rc
  938. *
  939. * @return list<string>
  940. */
  941. private function getPublicMethodNames(\ReflectionClass $rc): array
  942. {
  943. return array_map(
  944. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  945. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  946. );
  947. }
  948. }