Skip to content

Commit 967356e

Browse files
mhujerondrejmirtes
authored andcommitted
extract PHPUnit method call detection to helper
1 parent 8b8a622 commit 967356e

File tree

2 files changed

+53
-28
lines changed

2 files changed

+53
-28
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\PHPUnit;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\Type\ObjectType;
8+
9+
class AssertRuleHelper
10+
{
11+
12+
/**
13+
* @param \PhpParser\Node\Expr\MethodCall|\PhpParser\Node\Expr\StaticCall $node
14+
* @param \PHPStan\Analyser\Scope $scope
15+
* @return bool
16+
*/
17+
public static function isMethodOrStaticCallOnTestCase(Node $node, Scope $scope): bool
18+
{
19+
$testCaseType = new ObjectType(\PHPUnit\Framework\TestCase::class);
20+
if ($node instanceof Node\Expr\MethodCall) {
21+
$calledOnType = $scope->getType($node->var);
22+
} elseif ($node instanceof Node\Expr\StaticCall) {
23+
if ($node->class instanceof Node\Name) {
24+
$class = (string) $node->class;
25+
if (in_array(
26+
strtolower($class),
27+
[
28+
'self',
29+
'static',
30+
'parent',
31+
],
32+
true
33+
)) {
34+
$calledOnType = new ObjectType($scope->getClassReflection()->getName());
35+
} else {
36+
$calledOnType = new ObjectType($class);
37+
}
38+
} else {
39+
$calledOnType = $scope->getType($node->class);
40+
}
41+
} else {
42+
return false;
43+
}
44+
45+
if (!$testCaseType->isSuperTypeOf($calledOnType)->yes()) {
46+
return false;
47+
}
48+
49+
return true;
50+
}
51+
52+
}

src/Rules/PHPUnit/AssertSameDifferentTypesRule.php

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
use PhpParser\Node;
66
use PHPStan\Analyser\Scope;
7-
use PHPStan\Type\ObjectType;
87

98
class AssertSameDifferentTypesRule implements \PHPStan\Rules\Rule
109
{
@@ -21,33 +20,7 @@ public function getNodeType(): string
2120
*/
2221
public function processNode(Node $node, Scope $scope): array
2322
{
24-
$testCaseType = new ObjectType(\PHPUnit\Framework\TestCase::class);
25-
if ($node instanceof Node\Expr\MethodCall) {
26-
$calledOnType = $scope->getType($node->var);
27-
} elseif ($node instanceof Node\Expr\StaticCall) {
28-
if ($node->class instanceof Node\Name) {
29-
$class = (string) $node->class;
30-
if (in_array(
31-
strtolower($class),
32-
[
33-
'self',
34-
'static',
35-
'parent',
36-
],
37-
true
38-
)) {
39-
$calledOnType = new ObjectType($scope->getClassReflection()->getName());
40-
} else {
41-
$calledOnType = new ObjectType($class);
42-
}
43-
} else {
44-
$calledOnType = $scope->getType($node->class);
45-
}
46-
} else {
47-
return [];
48-
}
49-
50-
if (!$testCaseType->isSuperTypeOf($calledOnType)->yes()) {
23+
if (!AssertRuleHelper::isMethodOrStaticCallOnTestCase($node, $scope)) {
5124
return [];
5225
}
5326

0 commit comments

Comments
 (0)