ProjectCodeTest.php 34 KB

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