ProjectCodeTest.php 33 KB

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