forked from phpstan/phpstan-phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestMethodsHelper.php
More file actions
94 lines (75 loc) · 2.07 KB
/
TestMethodsHelper.php
File metadata and controls
94 lines (75 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PHPStan\Analyser\Scope;
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\FileTypeMapper;
use ReflectionMethod;
use function str_starts_with;
use function strtolower;
final class TestMethodsHelper
{
private FileTypeMapper $fileTypeMapper;
private bool $phpunit10OrNewer;
public function __construct(
FileTypeMapper $fileTypeMapper,
bool $phpunit10OrNewer
)
{
$this->fileTypeMapper = $fileTypeMapper;
$this->phpunit10OrNewer = $phpunit10OrNewer;
}
/**
* @return array<ReflectionMethod>
*/
public function getTestMethods(ClassReflection $classReflection, Scope $scope): array
{
$testMethods = [];
foreach ($classReflection->getNativeReflection()->getMethods() as $reflectionMethod) {
if (!$reflectionMethod->isPublic()) {
continue;
}
if (str_starts_with(strtolower($reflectionMethod->getName()), 'test')) {
$testMethods[] = $reflectionMethod;
continue;
}
$docComment = $reflectionMethod->getDocComment();
if ($docComment !== false) {
$methodPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
$scope->getFile(),
$classReflection->getName(),
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
$reflectionMethod->getName(),
$docComment,
);
if ($this->hasTestAnnotation($methodPhpDoc)) {
$testMethods[] = $reflectionMethod;
continue;
}
}
if (!$this->phpunit10OrNewer) {
continue;
}
$testAttributes = $reflectionMethod->getAttributes('PHPUnit\Framework\Attributes\Test'); // @phpstan-ignore argument.type
if ($testAttributes === []) {
continue;
}
$testMethods[] = $reflectionMethod;
}
return $testMethods;
}
private function hasTestAnnotation(?ResolvedPhpDocBlock $phpDoc): bool
{
if ($phpDoc === null) {
return false;
}
$phpDocNodes = $phpDoc->getPhpDocNodes();
foreach ($phpDocNodes as $docNode) {
$tags = $docNode->getTagsByName('@test');
if ($tags !== []) {
return true;
}
}
return false;
}
}