CodeCoverage.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-code-coverage.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\CodeCoverage;
  11. use function array_diff;
  12. use function array_diff_key;
  13. use function array_flip;
  14. use function array_keys;
  15. use function array_merge;
  16. use function array_unique;
  17. use function array_values;
  18. use function count;
  19. use function explode;
  20. use function get_class;
  21. use function is_array;
  22. use function is_file;
  23. use function sort;
  24. use PHPUnit\Framework\TestCase;
  25. use PHPUnit\Runner\PhptTestCase;
  26. use PHPUnit\Util\Test;
  27. use ReflectionClass;
  28. use SebastianBergmann\CodeCoverage\Driver\Driver;
  29. use SebastianBergmann\CodeCoverage\Node\Builder;
  30. use SebastianBergmann\CodeCoverage\Node\Directory;
  31. use SebastianBergmann\CodeCoverage\StaticAnalysis\CachingCoveredFileAnalyser;
  32. use SebastianBergmann\CodeCoverage\StaticAnalysis\CachingUncoveredFileAnalyser;
  33. use SebastianBergmann\CodeCoverage\StaticAnalysis\CoveredFileAnalyser;
  34. use SebastianBergmann\CodeCoverage\StaticAnalysis\ParsingCoveredFileAnalyser;
  35. use SebastianBergmann\CodeCoverage\StaticAnalysis\ParsingUncoveredFileAnalyser;
  36. use SebastianBergmann\CodeCoverage\StaticAnalysis\UncoveredFileAnalyser;
  37. use SebastianBergmann\CodeUnitReverseLookup\Wizard;
  38. /**
  39. * Provides collection functionality for PHP code coverage information.
  40. */
  41. final class CodeCoverage
  42. {
  43. private const UNCOVERED_FILES = 'UNCOVERED_FILES';
  44. /**
  45. * @var Driver
  46. */
  47. private $driver;
  48. /**
  49. * @var Filter
  50. */
  51. private $filter;
  52. /**
  53. * @var Wizard
  54. */
  55. private $wizard;
  56. /**
  57. * @var bool
  58. */
  59. private $checkForUnintentionallyCoveredCode = false;
  60. /**
  61. * @var bool
  62. */
  63. private $includeUncoveredFiles = true;
  64. /**
  65. * @var bool
  66. */
  67. private $processUncoveredFiles = false;
  68. /**
  69. * @var bool
  70. */
  71. private $ignoreDeprecatedCode = false;
  72. /**
  73. * @var PhptTestCase|string|TestCase
  74. */
  75. private $currentId;
  76. /**
  77. * Code coverage data.
  78. *
  79. * @var ProcessedCodeCoverageData
  80. */
  81. private $data;
  82. /**
  83. * @var bool
  84. */
  85. private $useAnnotationsForIgnoringCode = true;
  86. /**
  87. * Test data.
  88. *
  89. * @var array
  90. */
  91. private $tests = [];
  92. /**
  93. * @psalm-var list<class-string>
  94. */
  95. private $parentClassesExcludedFromUnintentionallyCoveredCodeCheck = [];
  96. /**
  97. * @var ?CoveredFileAnalyser
  98. */
  99. private $coveredFileAnalyser;
  100. /**
  101. * @var ?UncoveredFileAnalyser
  102. */
  103. private $uncoveredFileAnalyser;
  104. /**
  105. * @var ?string
  106. */
  107. private $cacheDirectory;
  108. public function __construct(Driver $driver, Filter $filter)
  109. {
  110. $this->driver = $driver;
  111. $this->filter = $filter;
  112. $this->data = new ProcessedCodeCoverageData;
  113. $this->wizard = new Wizard;
  114. }
  115. /**
  116. * Returns the code coverage information as a graph of node objects.
  117. */
  118. public function getReport(): Directory
  119. {
  120. return (new Builder($this->coveredFileAnalyser()))->build($this);
  121. }
  122. /**
  123. * Clears collected code coverage data.
  124. */
  125. public function clear(): void
  126. {
  127. $this->currentId = null;
  128. $this->data = new ProcessedCodeCoverageData;
  129. $this->tests = [];
  130. }
  131. /**
  132. * Returns the filter object used.
  133. */
  134. public function filter(): Filter
  135. {
  136. return $this->filter;
  137. }
  138. /**
  139. * Returns the collected code coverage data.
  140. */
  141. public function getData(bool $raw = false): ProcessedCodeCoverageData
  142. {
  143. if (!$raw) {
  144. if ($this->processUncoveredFiles) {
  145. $this->processUncoveredFilesFromFilter();
  146. } elseif ($this->includeUncoveredFiles) {
  147. $this->addUncoveredFilesFromFilter();
  148. } else {
  149. $this->data->removeFilesWithNoCoverage();
  150. }
  151. }
  152. return $this->data;
  153. }
  154. /**
  155. * Sets the coverage data.
  156. */
  157. public function setData(ProcessedCodeCoverageData $data): void
  158. {
  159. $this->data = $data;
  160. }
  161. /**
  162. * Returns the test data.
  163. */
  164. public function getTests(): array
  165. {
  166. return $this->tests;
  167. }
  168. /**
  169. * Sets the test data.
  170. */
  171. public function setTests(array $tests): void
  172. {
  173. $this->tests = $tests;
  174. }
  175. /**
  176. * Start collection of code coverage information.
  177. *
  178. * @param PhptTestCase|string|TestCase $id
  179. */
  180. public function start($id, bool $clear = false): void
  181. {
  182. if ($clear) {
  183. $this->clear();
  184. }
  185. $this->currentId = $id;
  186. $this->driver->start();
  187. }
  188. /**
  189. * Stop collection of code coverage information.
  190. *
  191. * @param array|false $linesToBeCovered
  192. */
  193. public function stop(bool $append = true, $linesToBeCovered = [], array $linesToBeUsed = []): RawCodeCoverageData
  194. {
  195. if (!is_array($linesToBeCovered) && $linesToBeCovered !== false) {
  196. throw new InvalidArgumentException(
  197. '$linesToBeCovered must be an array or false'
  198. );
  199. }
  200. $data = $this->driver->stop();
  201. $this->append($data, null, $append, $linesToBeCovered, $linesToBeUsed);
  202. $this->currentId = null;
  203. return $data;
  204. }
  205. /**
  206. * Appends code coverage data.
  207. *
  208. * @param PhptTestCase|string|TestCase $id
  209. * @param array|false $linesToBeCovered
  210. *
  211. * @throws ReflectionException
  212. * @throws TestIdMissingException
  213. * @throws UnintentionallyCoveredCodeException
  214. */
  215. public function append(RawCodeCoverageData $rawData, $id = null, bool $append = true, $linesToBeCovered = [], array $linesToBeUsed = []): void
  216. {
  217. if ($id === null) {
  218. $id = $this->currentId;
  219. }
  220. if ($id === null) {
  221. throw new TestIdMissingException;
  222. }
  223. $this->applyFilter($rawData);
  224. if ($this->useAnnotationsForIgnoringCode) {
  225. $this->applyIgnoredLinesFilter($rawData);
  226. }
  227. $this->data->initializeUnseenData($rawData);
  228. if (!$append) {
  229. return;
  230. }
  231. if ($id !== self::UNCOVERED_FILES) {
  232. $this->applyCoversAnnotationFilter(
  233. $rawData,
  234. $linesToBeCovered,
  235. $linesToBeUsed
  236. );
  237. if (empty($rawData->lineCoverage())) {
  238. return;
  239. }
  240. $size = 'unknown';
  241. $status = -1;
  242. $fromTestcase = false;
  243. if ($id instanceof TestCase) {
  244. $fromTestcase = true;
  245. $_size = $id->getSize();
  246. if ($_size === Test::SMALL) {
  247. $size = 'small';
  248. } elseif ($_size === Test::MEDIUM) {
  249. $size = 'medium';
  250. } elseif ($_size === Test::LARGE) {
  251. $size = 'large';
  252. }
  253. $status = $id->getStatus();
  254. $id = get_class($id) . '::' . $id->getName();
  255. } elseif ($id instanceof PhptTestCase) {
  256. $fromTestcase = true;
  257. $size = 'large';
  258. $id = $id->getName();
  259. }
  260. $this->tests[$id] = ['size' => $size, 'status' => $status, 'fromTestcase' => $fromTestcase];
  261. $this->data->markCodeAsExecutedByTestCase($id, $rawData);
  262. }
  263. }
  264. /**
  265. * Merges the data from another instance.
  266. */
  267. public function merge(self $that): void
  268. {
  269. $this->filter->includeFiles(
  270. $that->filter()->files()
  271. );
  272. $this->data->merge($that->data);
  273. $this->tests = array_merge($this->tests, $that->getTests());
  274. }
  275. public function enableCheckForUnintentionallyCoveredCode(): void
  276. {
  277. $this->checkForUnintentionallyCoveredCode = true;
  278. }
  279. public function disableCheckForUnintentionallyCoveredCode(): void
  280. {
  281. $this->checkForUnintentionallyCoveredCode = false;
  282. }
  283. public function includeUncoveredFiles(): void
  284. {
  285. $this->includeUncoveredFiles = true;
  286. }
  287. public function excludeUncoveredFiles(): void
  288. {
  289. $this->includeUncoveredFiles = false;
  290. }
  291. public function processUncoveredFiles(): void
  292. {
  293. $this->processUncoveredFiles = true;
  294. }
  295. public function doNotProcessUncoveredFiles(): void
  296. {
  297. $this->processUncoveredFiles = false;
  298. }
  299. public function enableAnnotationsForIgnoringCode(): void
  300. {
  301. $this->useAnnotationsForIgnoringCode = true;
  302. }
  303. public function disableAnnotationsForIgnoringCode(): void
  304. {
  305. $this->useAnnotationsForIgnoringCode = false;
  306. }
  307. public function ignoreDeprecatedCode(): void
  308. {
  309. $this->ignoreDeprecatedCode = true;
  310. }
  311. public function doNotIgnoreDeprecatedCode(): void
  312. {
  313. $this->ignoreDeprecatedCode = false;
  314. }
  315. /**
  316. * @psalm-assert-if-true !null $this->cacheDirectory
  317. */
  318. public function cachesStaticAnalysis(): bool
  319. {
  320. return $this->cacheDirectory !== null;
  321. }
  322. public function cacheStaticAnalysis(string $directory): void
  323. {
  324. $this->cacheDirectory = $directory;
  325. }
  326. public function doNotCacheStaticAnalysis(): void
  327. {
  328. $this->cacheDirectory = null;
  329. }
  330. /**
  331. * @throws StaticAnalysisCacheNotConfiguredException
  332. */
  333. public function cacheDirectory(): string
  334. {
  335. if (!$this->cachesStaticAnalysis()) {
  336. throw new StaticAnalysisCacheNotConfiguredException(
  337. 'The static analysis cache is not configured'
  338. );
  339. }
  340. return $this->cacheDirectory;
  341. }
  342. /**
  343. * @psalm-param class-string $className
  344. */
  345. public function excludeSubclassesOfThisClassFromUnintentionallyCoveredCodeCheck(string $className): void
  346. {
  347. $this->parentClassesExcludedFromUnintentionallyCoveredCodeCheck[] = $className;
  348. }
  349. public function enableBranchAndPathCoverage(): void
  350. {
  351. $this->driver->enableBranchAndPathCoverage();
  352. }
  353. public function disableBranchAndPathCoverage(): void
  354. {
  355. $this->driver->disableBranchAndPathCoverage();
  356. }
  357. public function collectsBranchAndPathCoverage(): bool
  358. {
  359. return $this->driver->collectsBranchAndPathCoverage();
  360. }
  361. public function detectsDeadCode(): bool
  362. {
  363. return $this->driver->detectsDeadCode();
  364. }
  365. /**
  366. * Applies the @covers annotation filtering.
  367. *
  368. * @param array|false $linesToBeCovered
  369. *
  370. * @throws ReflectionException
  371. * @throws UnintentionallyCoveredCodeException
  372. */
  373. private function applyCoversAnnotationFilter(RawCodeCoverageData $rawData, $linesToBeCovered, array $linesToBeUsed): void
  374. {
  375. if ($linesToBeCovered === false) {
  376. $rawData->clear();
  377. return;
  378. }
  379. if (empty($linesToBeCovered)) {
  380. return;
  381. }
  382. if ($this->checkForUnintentionallyCoveredCode &&
  383. (!$this->currentId instanceof TestCase ||
  384. (!$this->currentId->isMedium() && !$this->currentId->isLarge()))) {
  385. $this->performUnintentionallyCoveredCodeCheck($rawData, $linesToBeCovered, $linesToBeUsed);
  386. }
  387. $rawLineData = $rawData->lineCoverage();
  388. $filesWithNoCoverage = array_diff_key($rawLineData, $linesToBeCovered);
  389. foreach (array_keys($filesWithNoCoverage) as $fileWithNoCoverage) {
  390. $rawData->removeCoverageDataForFile($fileWithNoCoverage);
  391. }
  392. if (is_array($linesToBeCovered)) {
  393. foreach ($linesToBeCovered as $fileToBeCovered => $includedLines) {
  394. $rawData->keepCoverageDataOnlyForLines($fileToBeCovered, $includedLines);
  395. }
  396. }
  397. }
  398. private function applyFilter(RawCodeCoverageData $data): void
  399. {
  400. if ($this->filter->isEmpty()) {
  401. return;
  402. }
  403. foreach (array_keys($data->lineCoverage()) as $filename) {
  404. if ($this->filter->isExcluded($filename)) {
  405. $data->removeCoverageDataForFile($filename);
  406. }
  407. }
  408. }
  409. private function applyIgnoredLinesFilter(RawCodeCoverageData $data): void
  410. {
  411. foreach (array_keys($data->lineCoverage()) as $filename) {
  412. if (!$this->filter->isFile($filename)) {
  413. continue;
  414. }
  415. $data->removeCoverageDataForLines(
  416. $filename,
  417. $this->coveredFileAnalyser()->ignoredLinesFor($filename)
  418. );
  419. }
  420. }
  421. /**
  422. * @throws UnintentionallyCoveredCodeException
  423. */
  424. private function addUncoveredFilesFromFilter(): void
  425. {
  426. $uncoveredFiles = array_diff(
  427. $this->filter->files(),
  428. $this->data->coveredFiles()
  429. );
  430. foreach ($uncoveredFiles as $uncoveredFile) {
  431. if (is_file($uncoveredFile)) {
  432. $this->append(
  433. RawCodeCoverageData::fromUncoveredFile(
  434. $uncoveredFile,
  435. $this->uncoveredFileAnalyser()
  436. ),
  437. self::UNCOVERED_FILES
  438. );
  439. }
  440. }
  441. }
  442. /**
  443. * @throws UnintentionallyCoveredCodeException
  444. */
  445. private function processUncoveredFilesFromFilter(): void
  446. {
  447. $uncoveredFiles = array_diff(
  448. $this->filter->files(),
  449. $this->data->coveredFiles()
  450. );
  451. $this->driver->start();
  452. foreach ($uncoveredFiles as $uncoveredFile) {
  453. if (is_file($uncoveredFile)) {
  454. include_once $uncoveredFile;
  455. }
  456. }
  457. $this->append($this->driver->stop(), self::UNCOVERED_FILES);
  458. }
  459. /**
  460. * @throws ReflectionException
  461. * @throws UnintentionallyCoveredCodeException
  462. */
  463. private function performUnintentionallyCoveredCodeCheck(RawCodeCoverageData $data, array $linesToBeCovered, array $linesToBeUsed): void
  464. {
  465. $allowedLines = $this->getAllowedLines(
  466. $linesToBeCovered,
  467. $linesToBeUsed
  468. );
  469. $unintentionallyCoveredUnits = [];
  470. foreach ($data->lineCoverage() as $file => $_data) {
  471. foreach ($_data as $line => $flag) {
  472. if ($flag === 1 && !isset($allowedLines[$file][$line])) {
  473. $unintentionallyCoveredUnits[] = $this->wizard->lookup($file, $line);
  474. }
  475. }
  476. }
  477. $unintentionallyCoveredUnits = $this->processUnintentionallyCoveredUnits($unintentionallyCoveredUnits);
  478. if (!empty($unintentionallyCoveredUnits)) {
  479. throw new UnintentionallyCoveredCodeException(
  480. $unintentionallyCoveredUnits
  481. );
  482. }
  483. }
  484. private function getAllowedLines(array $linesToBeCovered, array $linesToBeUsed): array
  485. {
  486. $allowedLines = [];
  487. foreach (array_keys($linesToBeCovered) as $file) {
  488. if (!isset($allowedLines[$file])) {
  489. $allowedLines[$file] = [];
  490. }
  491. $allowedLines[$file] = array_merge(
  492. $allowedLines[$file],
  493. $linesToBeCovered[$file]
  494. );
  495. }
  496. foreach (array_keys($linesToBeUsed) as $file) {
  497. if (!isset($allowedLines[$file])) {
  498. $allowedLines[$file] = [];
  499. }
  500. $allowedLines[$file] = array_merge(
  501. $allowedLines[$file],
  502. $linesToBeUsed[$file]
  503. );
  504. }
  505. foreach (array_keys($allowedLines) as $file) {
  506. $allowedLines[$file] = array_flip(
  507. array_unique($allowedLines[$file])
  508. );
  509. }
  510. return $allowedLines;
  511. }
  512. /**
  513. * @throws ReflectionException
  514. */
  515. private function processUnintentionallyCoveredUnits(array $unintentionallyCoveredUnits): array
  516. {
  517. $unintentionallyCoveredUnits = array_unique($unintentionallyCoveredUnits);
  518. sort($unintentionallyCoveredUnits);
  519. foreach (array_keys($unintentionallyCoveredUnits) as $k => $v) {
  520. $unit = explode('::', $unintentionallyCoveredUnits[$k]);
  521. if (count($unit) !== 2) {
  522. continue;
  523. }
  524. try {
  525. $class = new ReflectionClass($unit[0]);
  526. foreach ($this->parentClassesExcludedFromUnintentionallyCoveredCodeCheck as $parentClass) {
  527. if ($class->isSubclassOf($parentClass)) {
  528. unset($unintentionallyCoveredUnits[$k]);
  529. break;
  530. }
  531. }
  532. } catch (\ReflectionException $e) {
  533. throw new ReflectionException(
  534. $e->getMessage(),
  535. (int) $e->getCode(),
  536. $e
  537. );
  538. }
  539. }
  540. return array_values($unintentionallyCoveredUnits);
  541. }
  542. private function coveredFileAnalyser(): CoveredFileAnalyser
  543. {
  544. if ($this->coveredFileAnalyser !== null) {
  545. return $this->coveredFileAnalyser;
  546. }
  547. $this->coveredFileAnalyser = new ParsingCoveredFileAnalyser(
  548. $this->useAnnotationsForIgnoringCode,
  549. $this->ignoreDeprecatedCode
  550. );
  551. if ($this->cachesStaticAnalysis()) {
  552. $this->coveredFileAnalyser = new CachingCoveredFileAnalyser(
  553. $this->cacheDirectory,
  554. $this->coveredFileAnalyser
  555. );
  556. }
  557. return $this->coveredFileAnalyser;
  558. }
  559. private function uncoveredFileAnalyser(): UncoveredFileAnalyser
  560. {
  561. if ($this->uncoveredFileAnalyser !== null) {
  562. return $this->uncoveredFileAnalyser;
  563. }
  564. $this->uncoveredFileAnalyser = new ParsingUncoveredFileAnalyser;
  565. if ($this->cachesStaticAnalysis()) {
  566. $this->uncoveredFileAnalyser = new CachingUncoveredFileAnalyser(
  567. $this->cacheDirectory,
  568. $this->uncoveredFileAnalyser
  569. );
  570. }
  571. return $this->uncoveredFileAnalyser;
  572. }
  573. }