Skip to content

Commit

Permalink
Fix covers rule for functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
mad-briller authored and ondrejmirtes committed Oct 28, 2022
1 parent e431a6c commit c86e460
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
14 changes: 11 additions & 3 deletions src/Rules/PHPUnit/CoversHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPStan\Rules\PHPUnit;

use PhpParser\Node;
use PhpParser\Node\Name;
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\Reflection\ReflectionProvider;
Expand Down Expand Up @@ -70,8 +71,9 @@ public function processCovers(
{
$errors = [];
$covers = (string) $phpDocTag->value;
$isMethod = strpos($covers, '::') !== false;

if (strpos($covers, '::') !== false) {
if ($isMethod) {
[$className, $method] = explode('::', $covers);
} else {
$className = $covers;
Expand All @@ -83,16 +85,22 @@ public function processCovers(

if ($this->reflectionProvider->hasClass($className)) {
$class = $this->reflectionProvider->getClass($className);

if (isset($method) && $method !== '' && !$class->hasMethod($method)) {
$errors[] = RuleErrorBuilder::message(sprintf(
'@covers value %s references an invalid method.',
$covers
))->build();
}
} else {
if (!isset($method) && $this->reflectionProvider->hasFunction(new Name($covers, []), null)) {
return $errors;
}

$errors[] = RuleErrorBuilder::message(sprintf(
'@covers value %s references an invalid class.',
$covers
'@covers value %s references an invalid %s.',
$covers,
$isMethod ? 'method' : 'class or function'
))->build();
}
return $errors;
Expand Down
4 changes: 2 additions & 2 deletions tests/Rules/PHPUnit/ClassMethodCoversExistsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ public function testRule(): void
{
$this->analyse([__DIR__ . '/data/method-coverage.php'], [
[
'@covers value ::ignoreThis references an invalid class.',
'@covers value ::ignoreThis references an invalid method.',
14,
],
[
'@covers value \PHPUnit\Framework\TestCase::assertNotReal references an invalid method.',
28,
],
[
'@covers value \Not\A\Class::foo references an invalid class.',
'@covers value \Not\A\Class::foo references an invalid method.',
35,
],
[
Expand Down
12 changes: 12 additions & 0 deletions tests/Rules/PHPUnit/data/class-coverage.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,15 @@ class CoversShouldExistTestCase2 extends \PHPUnit\Framework\TestCase
class MultipleCoversDefaultClass extends \PHPUnit\Framework\TestCase
{
}

/**
* @covers \ClassCoverage\testable
*/
class CoversFunction extends \PHPUnit\Framework\TestCase
{
}

function testable(): void
{

}

0 comments on commit c86e460

Please sign in to comment.