forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefinedVariableRule.php
92 lines (79 loc) · 2.2 KB
/
DefinedVariableRule.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\Variables;
use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Constant\ConstantStringType;
use function array_map;
use function array_merge;
use function in_array;
use function is_string;
use function sprintf;
/**
* @implements Rule<Node\Expr\Variable>
*/
final class DefinedVariableRule implements Rule
{
public function __construct(
private bool $cliArgumentsVariablesRegistered,
private bool $checkMaybeUndefinedVariables,
)
{
}
public function getNodeType(): string
{
return Variable::class;
}
public function processNode(Node $node, Scope $scope): array
{
$errors = [];
if (is_string($node->name)) {
$variableNames = [$node->name];
} else {
$fetchType = $scope->getType($node->name);
$variableNames = array_map(static fn (ConstantStringType $type): string => $type->getValue(), $fetchType->getConstantStrings());
}
foreach ($variableNames as $name) {
$errors = array_merge($errors, $this->processSingleVariable($scope, $node, $name));
}
return $errors;
}
/**
* @return list<IdentifierRuleError>
*/
private function processSingleVariable(Scope $scope, Variable $node, string $variableName): array
{
if ($this->cliArgumentsVariablesRegistered && in_array($variableName, [
'argc',
'argv',
], true)) {
$isInMain = !$scope->isInClass() && !$scope->isInAnonymousFunction() && $scope->getFunction() === null;
if ($isInMain) {
return [];
}
}
if ($scope->isInExpressionAssign($node) || $scope->isUndefinedExpressionAllowed($node)) {
return [];
}
if ($scope->hasVariableType($variableName)->no()) {
return [
RuleErrorBuilder::message(sprintf('Undefined variable: $%s', $variableName))
->identifier('variable.undefined')
->build(),
];
} elseif (
$this->checkMaybeUndefinedVariables
&& !$scope->hasVariableType($variableName)->yes()
) {
return [
RuleErrorBuilder::message(sprintf('Variable $%s might not be defined.', $variableName))
->identifier('variable.undefined')
->build(),
];
}
return [];
}
}