-
Notifications
You must be signed in to change notification settings - Fork 505
/
Copy pathImpossibleCheckTypeFunctionCallRule.php
92 lines (76 loc) · 2.56 KB
/
ImpossibleCheckTypeFunctionCallRule.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Comparison;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Parser\LastConditionVisitor;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function sprintf;
/**
* @implements Rule<Node\Expr\FuncCall>
*/
final class ImpossibleCheckTypeFunctionCallRule implements Rule
{
public function __construct(
private ImpossibleCheckTypeHelper $impossibleCheckTypeHelper,
private bool $checkAlwaysTrueCheckTypeFunctionCall,
private bool $treatPhpDocTypesAsCertain,
private bool $reportAlwaysTrueInLastCondition,
private bool $treatPhpDocTypesAsCertainTip,
)
{
}
public function getNodeType(): string
{
return Node\Expr\FuncCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Node\Name) {
return [];
}
$functionName = (string) $node->name;
$isAlways = $this->impossibleCheckTypeHelper->findSpecifiedType($scope, $node);
if ($isAlways === null) {
return [];
}
$addTip = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $node): RuleErrorBuilder {
if (!$this->treatPhpDocTypesAsCertain) {
return $ruleErrorBuilder;
}
$isAlways = $this->impossibleCheckTypeHelper->doNotTreatPhpDocTypesAsCertain()->findSpecifiedType($scope, $node);
if ($isAlways !== null) {
return $ruleErrorBuilder;
}
if (!$this->treatPhpDocTypesAsCertainTip) {
return $ruleErrorBuilder;
}
return $ruleErrorBuilder->treatPhpDocTypesAsCertainTip();
};
if (!$isAlways) {
return [
$addTip(RuleErrorBuilder::message(sprintf(
'Call to function %s()%s will always evaluate to false.',
$functionName,
$this->impossibleCheckTypeHelper->getArgumentsDescription($scope, $node->getArgs()),
)))->identifier('function.impossibleType')->build(),
];
} elseif ($this->checkAlwaysTrueCheckTypeFunctionCall) {
$isLast = $node->getAttribute(LastConditionVisitor::ATTRIBUTE_NAME);
if ($isLast === true && !$this->reportAlwaysTrueInLastCondition) {
return [];
}
$errorBuilder = $addTip(RuleErrorBuilder::message(sprintf(
'Call to function %s()%s will always evaluate to true.',
$functionName,
$this->impossibleCheckTypeHelper->getArgumentsDescription($scope, $node->getArgs()),
)));
if ($isLast === false && !$this->reportAlwaysTrueInLastCondition) {
$errorBuilder->tip('Remove remaining cases below this one and this error will disappear too.');
}
$errorBuilder->identifier('function.alreadyNarrowedType');
return [$errorBuilder->build()];
}
return [];
}
}