-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathCleaningVisitor.php
82 lines (67 loc) · 1.98 KB
/
CleaningVisitor.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
<?php declare(strict_types = 1);
namespace PHPStan\Parser;
use PhpParser\Node;
use PhpParser\NodeFinder;
use PhpParser\NodeVisitorAbstract;
use PHPStan\Reflection\ParametersAcceptor;
use function in_array;
class CleaningVisitor extends NodeVisitorAbstract
{
private NodeFinder $nodeFinder;
public function __construct()
{
$this->nodeFinder = new NodeFinder();
}
public function enterNode(Node $node): ?Node
{
if ($node instanceof Node\Stmt\Function_) {
$node->stmts = $this->keepVariadicsAndYields($node->stmts);
return $node;
}
if ($node instanceof Node\Stmt\ClassMethod && $node->stmts !== null) {
$node->stmts = $this->keepVariadicsAndYields($node->stmts);
return $node;
}
if ($node instanceof Node\Expr\Closure) {
$node->stmts = $this->keepVariadicsAndYields($node->stmts);
return $node;
}
return null;
}
/**
* @param Node\Stmt[] $stmts
* @return Node\Stmt[]
*/
private function keepVariadicsAndYields(array $stmts): array
{
$results = $this->nodeFinder->find($stmts, static function (Node $node): bool {
if ($node instanceof Node\Expr\YieldFrom || $node instanceof Node\Expr\Yield_) {
return true;
}
if ($node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name) {
return in_array($node->name->toLowerString(), ParametersAcceptor::VARIADIC_FUNCTIONS, true);
}
if ($node instanceof Node\Expr\Closure || $node instanceof Node\Expr\ArrowFunction) {
return true;
}
return false;
});
$newStmts = [];
foreach ($results as $result) {
if (
$result instanceof Node\Expr\Yield_
|| $result instanceof Node\Expr\YieldFrom
|| $result instanceof Node\Expr\Closure
|| $result instanceof Node\Expr\ArrowFunction
) {
$newStmts[] = new Node\Stmt\Expression($result);
continue;
}
if (!$result instanceof Node\Expr\FuncCall) {
continue;
}
$newStmts[] = new Node\Stmt\Expression(new Node\Expr\FuncCall(new Node\Name\FullyQualified('func_get_args')));
}
return $newStmts;
}
}