-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathAssertMethodAnalyzer.php
More file actions
87 lines (70 loc) · 2.83 KB
/
AssertMethodAnalyzer.php
File metadata and controls
87 lines (70 loc) · 2.83 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
<?php
declare(strict_types=1);
namespace Rector\PHPUnit\CodeQuality\NodeAnalyser;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ExtendedMethodReflection;
use PHPStan\Type\ObjectType;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Rector\PHPUnit\CodeQuality\Enum\NonAssertNonStaticMethods;
use Rector\PHPUnit\Enum\PHPUnitClassName;
use Rector\Reflection\ReflectionResolver;
final readonly class AssertMethodAnalyzer
{
public function __construct(
private NodeNameResolver $nodeNameResolver,
private ReflectionResolver $reflectionResolver,
private NodeTypeResolver $nodeTypeResolver
) {
}
public function detectTestCaseCall(MethodCall|StaticCall $call): bool
{
$objectCaller = $call instanceof MethodCall
? $call->var
: $call->class;
if (! $this->nodeTypeResolver->isObjectType($objectCaller, new ObjectType(PHPUnitClassName::TEST_CASE))) {
return false;
}
$methodName = $this->nodeNameResolver->getName($call->name);
if (! str_starts_with((string) $methodName, 'assert') && ! in_array(
$methodName,
NonAssertNonStaticMethods::ALL,
true
)) {
return false;
}
if ($call instanceof StaticCall && ! $this->nodeNameResolver->isNames($call->class, ['static', 'self'])) {
return false;
}
$extendedMethodReflection = $this->resolveMethodReflection($call);
if (! $extendedMethodReflection instanceof ExtendedMethodReflection) {
return false;
}
// only handle methods in TestCase or Assert class classes
$declaringClassName = $extendedMethodReflection->getDeclaringClass()
->getName();
return in_array($declaringClassName, [PHPUnitClassName::TEST_CASE, PHPUnitClassName::ASSERT], true);
}
public function detectTestCaseCallForStatic(MethodCall $methodCall): bool
{
if (! $this->detectTestCaseCall($methodCall)) {
return false;
}
$extendedMethodReflection = $this->resolveMethodReflection($methodCall);
return $extendedMethodReflection instanceof ExtendedMethodReflection && $extendedMethodReflection->isStatic();
}
private function resolveMethodReflection(MethodCall|StaticCall $call): ?ExtendedMethodReflection
{
$methodName = $this->nodeNameResolver->getName($call->name);
if ($methodName === null) {
return null;
}
$classReflection = $this->reflectionResolver->resolveClassReflection($call);
if (! $classReflection instanceof ClassReflection) {
return null;
}
return $classReflection->getNativeMethod($methodName);
}
}