Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor getLinesToBeIgnored() so it can work with branch/path data #757

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 9 additions & 99 deletions src/CodeCoverage.php
Original file line number Diff line number Diff line change
Expand Up @@ -496,27 +496,22 @@ private function applyIgnoredLinesFilter(RawCodeCoverageData $data): void
*/
private function addUncoveredFilesFromWhitelist(): void
{
$data = [];
$uncoveredFiles = \array_diff(
$this->filter->getWhitelist(),
\array_keys($this->data->getLineCoverage())
);

foreach ($uncoveredFiles as $uncoveredFile) {
if (!\file_exists($uncoveredFile)) {
continue;
}

$data[$uncoveredFile] = [];

$lines = \count(\file($uncoveredFile));
if (\file_exists($uncoveredFile)) {
if ($this->cacheTokens) {
$tokens = \PHP_Token_Stream_CachingFactory::get($uncoveredFile);
} else {
$tokens = new \PHP_Token_Stream($uncoveredFile);
}

for ($i = 1; $i <= $lines; $i++) {
$data[$uncoveredFile][$i] = Driver::LINE_NOT_EXECUTED;
$this->append(RawCodeCoverageData::fromUncoveredFile($uncoveredFile, $tokens), self::UNCOVERED_FILES_FROM_WHITELIST);
}
}

$this->append(RawCodeCoverageData::fromXdebugWithoutPathCoverage($data), self::UNCOVERED_FILES_FROM_WHITELIST);
}

private function getLinesToBeIgnored(string $fileName): array
Expand All @@ -540,60 +535,12 @@ private function getLinesToBeIgnoredInner(string $fileName): array

$lines = \file($fileName);

foreach ($lines as $index => $line) {
if (!\trim($line)) {
$this->ignoredLines[$fileName][] = $index + 1;
}
}

if ($this->cacheTokens) {
$tokens = \PHP_Token_Stream_CachingFactory::get($fileName);
} else {
$tokens = new \PHP_Token_Stream($fileName);
}

foreach ($tokens->getInterfaces() as $interface) {
$interfaceStartLine = $interface['startLine'];
$interfaceEndLine = $interface['endLine'];

foreach (\range($interfaceStartLine, $interfaceEndLine) as $line) {
$this->ignoredLines[$fileName][] = $line;
}
}

foreach (\array_merge($tokens->getClasses(), $tokens->getTraits()) as $classOrTrait) {
$classOrTraitStartLine = $classOrTrait['startLine'];
$classOrTraitEndLine = $classOrTrait['endLine'];

if (empty($classOrTrait['methods'])) {
foreach (\range($classOrTraitStartLine, $classOrTraitEndLine) as $line) {
$this->ignoredLines[$fileName][] = $line;
}

continue;
}

$firstMethod = \array_shift($classOrTrait['methods']);
$firstMethodStartLine = $firstMethod['startLine'];
$lastMethodEndLine = $firstMethod['endLine'];

do {
$lastMethod = \array_pop($classOrTrait['methods']);
} while ($lastMethod !== null && 0 === \strpos($lastMethod['signature'], 'anonymousFunction'));

if ($lastMethod !== null) {
$lastMethodEndLine = $lastMethod['endLine'];
}

foreach (\range($classOrTraitStartLine, $firstMethodStartLine) as $line) {
$this->ignoredLines[$fileName][] = $line;
}

foreach (\range($lastMethodEndLine + 1, $classOrTraitEndLine) as $line) {
$this->ignoredLines[$fileName][] = $line;
}
}

if ($this->disableIgnoredLines) {
$this->ignoredLines[$fileName] = \array_unique($this->ignoredLines[$fileName]);
\sort($this->ignoredLines[$fileName]);
Expand Down Expand Up @@ -623,29 +570,10 @@ private function getLinesToBeIgnoredInner(string $fileName): array
$stop = true;
}

if (!$ignore) {
$start = $token->getLine();
$end = $start + \substr_count((string) $token, "\n");

// Do not ignore the first line when there is a token
// before the comment
if (0 !== \strpos($_token, $_line)) {
$start++;
}

for ($i = $start; $i < $end; $i++) {
$this->ignoredLines[$fileName][] = $i;
}

// A DOC_COMMENT token or a COMMENT token starting with "/*"
// does not contain the final \n character in its text
if (isset($lines[$i - 1]) && 0 === \strpos($_token, '/*') && '*/' === \substr(\trim($lines[$i - 1]), -2)) {
$this->ignoredLines[$fileName][] = $i;
}
}

break;

// Intentional fallthrough

case \PHP_Token_INTERFACE::class:
case \PHP_Token_TRAIT::class:
case \PHP_Token_CLASS::class:
Expand All @@ -654,8 +582,6 @@ private function getLinesToBeIgnoredInner(string $fileName): array

$docblock = (string) $token->getDocblock();

$this->ignoredLines[$fileName][] = $token->getLine();

if (\strpos($docblock, '@codeCoverageIgnore') || ($this->ignoreDeprecatedCode && \strpos($docblock, '@deprecated'))) {
$endLine = $token->getEndLine();

Expand All @@ -664,20 +590,6 @@ private function getLinesToBeIgnoredInner(string $fileName): array
}
}

break;

/* @noinspection PhpMissingBreakStatementInspection */
case \PHP_Token_NAMESPACE::class:
$this->ignoredLines[$fileName][] = $token->getEndLine();

// Intentional fallthrough
case \PHP_Token_DECLARE::class:
case \PHP_Token_OPEN_TAG::class:
case \PHP_Token_CLOSE_TAG::class:
case \PHP_Token_USE::class:
case \PHP_Token_USE_FUNCTION::class:
$this->ignoredLines[$fileName][] = $token->getLine();

break;
}

Expand All @@ -691,8 +603,6 @@ private function getLinesToBeIgnoredInner(string $fileName): array
}
}

$this->ignoredLines[$fileName][] = \count($lines) + 1;

$this->ignoredLines[$fileName] = \array_unique(
$this->ignoredLines[$fileName]
);
Expand Down
120 changes: 120 additions & 0 deletions src/RawCodeCoverageData.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
*/
namespace SebastianBergmann\CodeCoverage;

use PHP_Token_Stream;
use SebastianBergmann\CodeCoverage\Driver\Driver;

/**
* @internal This class is not covered by the backward compatibility promise for phpunit/php-code-coverage
*/
Expand Down Expand Up @@ -54,6 +57,123 @@ public static function fromXdebugWithPathCoverage(array $rawCoverage): self
return new self($lineCoverage, $functionCoverage);
}

public static function fromUncoveredFile(string $filename, PHP_Token_Stream $tokens): self
{
$lineCoverage = [];

$lines = \file($filename);
$lineCount = \count($lines);

for ($i = 1; $i <= $lineCount; $i++) {
$lineCoverage[$i] = Driver::LINE_NOT_EXECUTED;
}

//remove empty lines
foreach ($lines as $index => $line) {
if (!\trim($line)) {
unset($lineCoverage[$index + 1]);
}
}

//not all lines are actually executable though, remove these
try {
foreach ($tokens->getInterfaces() as $interface) {
$interfaceStartLine = $interface['startLine'];
$interfaceEndLine = $interface['endLine'];

foreach (\range($interfaceStartLine, $interfaceEndLine) as $line) {
unset($lineCoverage[$line]);
}
}

foreach (\array_merge($tokens->getClasses(), $tokens->getTraits()) as $classOrTrait) {
$classOrTraitStartLine = $classOrTrait['startLine'];
$classOrTraitEndLine = $classOrTrait['endLine'];

if (empty($classOrTrait['methods'])) {
foreach (\range($classOrTraitStartLine, $classOrTraitEndLine) as $line) {
unset($lineCoverage[$line]);
}

continue;
}

$firstMethod = \array_shift($classOrTrait['methods']);
$firstMethodStartLine = $firstMethod['startLine'];
$lastMethodEndLine = $firstMethod['endLine'];

do {
$lastMethod = \array_pop($classOrTrait['methods']);
} while ($lastMethod !== null && 0 === \strpos($lastMethod['signature'], 'anonymousFunction'));

if ($lastMethod !== null) {
$lastMethodEndLine = $lastMethod['endLine'];
}

foreach (\range($classOrTraitStartLine, $firstMethodStartLine) as $line) {
unset($lineCoverage[$line]);
}

foreach (\range($lastMethodEndLine + 1, $classOrTraitEndLine) as $line) {
unset($lineCoverage[$line]);
}
}

foreach ($tokens->tokens() as $token) {
switch (\get_class($token)) {
case \PHP_Token_COMMENT::class:
case \PHP_Token_DOC_COMMENT::class:
$_token = \trim((string) $token);
$_line = \trim($lines[$token->getLine() - 1]);

$start = $token->getLine();
$end = $start + \substr_count((string) $token, "\n");

// Do not ignore the first line when there is a token
// before the comment
if (0 !== \strpos($_token, $_line)) {
$start++;
}

for ($i = $start; $i < $end; $i++) {
unset($lineCoverage[$i]);
}

// A DOC_COMMENT token or a COMMENT token starting with "/*"
// does not contain the final \n character in its text
if (isset($lines[$i - 1]) && 0 === \strpos($_token, '/*') && '*/' === \substr(\trim($lines[$i - 1]), -2)) {
unset($lineCoverage[$i]);
}

break;

/* @noinspection PhpMissingBreakStatementInspection */
case \PHP_Token_NAMESPACE::class:
unset($lineCoverage[$token->getEndLine()]);

// Intentional fallthrough

case \PHP_Token_INTERFACE::class:
case \PHP_Token_TRAIT::class:
case \PHP_Token_CLASS::class:
case \PHP_Token_FUNCTION::class:
case \PHP_Token_DECLARE::class:
case \PHP_Token_OPEN_TAG::class:
case \PHP_Token_CLOSE_TAG::class:
case \PHP_Token_USE::class:
case \PHP_Token_USE_FUNCTION::class:
unset($lineCoverage[$token->getLine()]);

break;
}
}
} catch (\Exception $e) { // This can happen with PHP_Token_Stream if the file is syntactically invalid
// do nothing
}

return new self([$filename => $lineCoverage], []);
}

private function __construct(array $lineCoverage, array $functionCoverage)
{
$this->lineCoverage = $lineCoverage;
Expand Down
1 change: 0 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -1530,7 +1530,6 @@ protected function setUpXdebugStubForFileWithIgnoredLines(): Driver
2 => 1,
4 => -1,
6 => -1,
7 => 1,
],
]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ <h3>Insufficient Coverage</h3>
</tr>
</thead>
<tbody>
<tr><td><a href="source_with_class_and_anonymous_function.php.html#3">CoveredClassWithAnonymousFunctionInStaticMethod</a></td><td class="text-right">87%</td></tr>
<tr><td><a href="source_with_class_and_anonymous_function.php.html#3">CoveredClassWithAnonymousFunctionInStaticMethod</a></td><td class="text-right">88%</td></tr>

</tbody>
</table>
Expand Down Expand Up @@ -111,7 +111,7 @@ <h3>Insufficient Coverage</h3>
</tr>
</thead>
<tbody>
<tr><td><a href="source_with_class_and_anonymous_function.php.html#5"><abbr title="CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous">runAnonymous</abbr></a></td><td class="text-right">87%</td></tr>
<tr><td><a href="source_with_class_and_anonymous_function.php.html#5"><abbr title="CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous">runAnonymous</abbr></a></td><td class="text-right">88%</td></tr>

</tbody>
</table>
Expand Down Expand Up @@ -224,7 +224,7 @@ <h3>Project Risks</h3>
chart.yAxis.axisLabel('Cyclomatic Complexity');

d3.select('#classComplexity svg')
.datum(getComplexityData([[87.5,1,"<a href=\"source_with_class_and_anonymous_function.php.html#3\">CoveredClassWithAnonymousFunctionInStaticMethod<\/a>"]], 'Class Complexity'))
.datum(getComplexityData([[88.888888888889,1,"<a href=\"source_with_class_and_anonymous_function.php.html#3\">CoveredClassWithAnonymousFunctionInStaticMethod<\/a>"]], 'Class Complexity'))
.transition()
.duration(500)
.call(chart);
Expand All @@ -248,7 +248,7 @@ <h3>Project Risks</h3>
chart.yAxis.axisLabel('Method Complexity');

d3.select('#methodComplexity svg')
.datum(getComplexityData([[87.5,1,"<a href=\"source_with_class_and_anonymous_function.php.html#5\">CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous<\/a>"]], 'Method Complexity'))
.datum(getComplexityData([[88.888888888889,1,"<a href=\"source_with_class_and_anonymous_function.php.html#5\">CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous<\/a>"]], 'Method Complexity'))
.transition()
.duration(500)
.call(chart);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@
<tr>
<td class="warning">Total</td>
<td class="warning big"> <div class="progress">
<div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
<span class="sr-only">87.50% covered (warning)</span>
<div class="progress-bar bg-warning" role="progressbar" aria-valuenow="88.89" aria-valuemin="0" aria-valuemax="100" style="width: 88.89%">
<span class="sr-only">88.89% covered (warning)</span>
</div>
</div>
</td>
<td class="warning small"><div align="right">87.50%</div></td>
<td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
<td class="warning small"><div align="right">88.89%</div></td>
<td class="warning small"><div align="right">8&nbsp;/&nbsp;9</div></td>
<td class="danger big"> <div class="progress">
<div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
<span class="sr-only">0.00% covered (danger)</span>
Expand All @@ -72,13 +72,13 @@
<tr>
<td class="warning"><img src="_icons/file-code.svg" class="octicon" /><a href="source_with_class_and_anonymous_function.php.html">source_with_class_and_anonymous_function.php</a></td>
<td class="warning big"> <div class="progress">
<div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
<span class="sr-only">87.50% covered (warning)</span>
<div class="progress-bar bg-warning" role="progressbar" aria-valuenow="88.89" aria-valuemin="0" aria-valuemax="100" style="width: 88.89%">
<span class="sr-only">88.89% covered (warning)</span>
</div>
</div>
</td>
<td class="warning small"><div align="right">87.50%</div></td>
<td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
<td class="warning small"><div align="right">88.89%</div></td>
<td class="warning small"><div align="right">8&nbsp;/&nbsp;9</div></td>
<td class="danger big"> <div class="progress">
<div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
<span class="sr-only">0.00% covered (danger)</span>
Expand Down
Loading