/
ConstantLooseComparisonRule.php
62 lines (52 loc) · 1.63 KB
/
ConstantLooseComparisonRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Comparison;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<Node\Expr\BinaryOp>
*/
class ConstantLooseComparisonRule implements Rule
{
public function __construct(private bool $checkAlwaysTrueLooseComparison)
{
}
public function getNodeType(): string
{
return Node\Expr\BinaryOp::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node instanceof Node\Expr\BinaryOp\Equal && !$node instanceof Node\Expr\BinaryOp\NotEqual) {
return [];
}
$nodeType = $scope->getType($node);
if (!$nodeType instanceof ConstantBooleanType) {
return [];
}
if (!$nodeType->getValue()) {
return [
RuleErrorBuilder::message(sprintf(
'Loose comparison using %s between %s and %s will always evaluate to false.',
$node instanceof Node\Expr\BinaryOp\Equal ? '==' : '!=',
$scope->getType($node->left)->describe(VerbosityLevel::value()),
$scope->getType($node->right)->describe(VerbosityLevel::value()),
))->build(),
];
} elseif ($this->checkAlwaysTrueLooseComparison) {
return [
RuleErrorBuilder::message(sprintf(
'Loose comparison using %s between %s and %s will always evaluate to true.',
$node instanceof Node\Expr\BinaryOp\Equal ? '==' : '!=',
$scope->getType($node->left)->describe(VerbosityLevel::value()),
$scope->getType($node->right)->describe(VerbosityLevel::value()),
))->build(),
];
}
return [];
}
}