-
Notifications
You must be signed in to change notification settings - Fork 576
Expand file tree
/
Copy pathInfiniteFunctionRecursionRule.php
More file actions
81 lines (69 loc) · 1.95 KB
/
Copy pathInfiniteFunctionRecursionRule.php
File metadata and controls
81 lines (69 loc) · 1.95 KB
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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Functions;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Node\FunctionReturnStatementsNode;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\InfiniteRecursionFinder;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function sprintf;
use function strtolower;
/**
* @implements Rule<FunctionReturnStatementsNode>
*/
#[RegisteredRule(level: 4)]
final class InfiniteFunctionRecursionRule implements Rule
{
public function __construct(
private InfiniteRecursionFinder $finder,
private ReflectionProvider $reflectionProvider,
)
{
}
public function getNodeType(): string
{
return FunctionReturnStatementsNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->isGenerator()) {
return [];
}
$function = $node->getFunctionReflection();
$functionName = strtolower($function->getName());
$reflectionProvider = $this->reflectionProvider;
$isSelfCall = static function (Expr $expr) use ($functionName, $reflectionProvider, $scope): bool {
if (!$expr instanceof FuncCall) {
return false;
}
if ($expr->isFirstClassCallable()) {
return false;
}
if (!$expr->name instanceof Name) {
return false;
}
if (!$reflectionProvider->hasFunction($expr->name, $scope)) {
return false;
}
return strtolower($reflectionProvider->getFunction($expr->name, $scope)->getName()) === $functionName;
};
$call = $this->finder->find($node->getStatements(), $isSelfCall);
if ($call === null) {
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'Function %s() calls itself on every code path, leading to infinite recursion.',
$function->getName(),
))
->identifier('function.infiniteRecursion')
->line($call->getStartLine())
->build(),
];
}
}