forked from phpstan/phpstan-phpunit
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssertEqualsIsDiscouragedRule.php
76 lines (64 loc) · 2 KB
/
AssertEqualsIsDiscouragedRule.php
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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PhpParser\Node;
use PhpParser\Node\Expr\CallLike;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\TypeCombinator;
use function count;
use function in_array;
use function strtolower;
/**
* @implements Rule<CallLike>
*/
class AssertEqualsIsDiscouragedRule implements Rule
{
public function getNodeType(): string
{
return CallLike::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!AssertRuleHelper::isMethodOrStaticCallOnAssert($node, $scope)) {
return [];
}
if (count($node->getArgs()) < 2) {
return [];
}
if (
!$node->name instanceof Node\Identifier
|| !in_array(strtolower($node->name->name), ['assertequals', 'assertnotequals'], true)
) {
return [];
}
$leftType = TypeCombinator::removeNull($scope->getType($node->getArgs()[0]->value));
$rightType = TypeCombinator::removeNull($scope->getType($node->getArgs()[1]->value));
if ($leftType->isConstantScalarValue()->yes()) {
$leftType = $leftType->generalize(GeneralizePrecision::lessSpecific());
}
if ($rightType->isConstantScalarValue()->yes()) {
$rightType = $rightType->generalize(GeneralizePrecision::lessSpecific());
}
if (
($leftType->isScalar()->yes() && $rightType->isScalar()->yes())
&& ($leftType->isSuperTypeOf($rightType)->yes())
&& ($rightType->isSuperTypeOf($leftType)->yes())
) {
if (strtolower($node->name->name) === 'assertnotequals') {
return [
RuleErrorBuilder::message(
'You should use assertNotSame() instead of assertNotEquals(), because both values are scalars of the same type',
)->identifier('phpunit.assertEquals')->build(),
];
}
return [
RuleErrorBuilder::message(
'You should use assertSame() instead of assertEquals(), because both values are scalars of the same type',
)->identifier('phpunit.assertEquals')->build(),
];
}
return [];
}
}