|
3 | 3 | namespace PHPStan\Parser;
|
4 | 4 |
|
5 | 5 | use PhpParser\Node;
|
| 6 | +use PhpParser\NodeFinder; |
6 | 7 | use PhpParser\NodeVisitorAbstract;
|
| 8 | +use PHPStan\Reflection\ParametersAcceptor; |
7 | 9 |
|
8 | 10 | class CleaningVisitor extends NodeVisitorAbstract
|
9 | 11 | {
|
10 | 12 |
|
| 13 | + private NodeFinder $nodeFinder; |
| 14 | + |
| 15 | + public function __construct() |
| 16 | + { |
| 17 | + $this->nodeFinder = new NodeFinder(); |
| 18 | + } |
| 19 | + |
11 | 20 | public function enterNode(Node $node): ?Node
|
12 | 21 | {
|
13 | 22 | if ($node instanceof Node\Stmt\Function_) {
|
14 |
| - $node->stmts = []; |
| 23 | + $node->stmts = $this->keepVariadicsAndYields($node->stmts); |
15 | 24 | return $node;
|
16 | 25 | }
|
17 | 26 |
|
18 | 27 | if ($node instanceof Node\Stmt\ClassMethod && $node->stmts !== null) {
|
19 |
| - $node->stmts = []; |
| 28 | + $node->stmts = $this->keepVariadicsAndYields($node->stmts); |
20 | 29 | return $node;
|
21 | 30 | }
|
22 | 31 |
|
23 | 32 | if ($node instanceof Node\Expr\Closure) {
|
24 |
| - $node->stmts = []; |
| 33 | + $node->stmts = $this->keepVariadicsAndYields($node->stmts); |
25 | 34 | return $node;
|
26 | 35 | }
|
27 | 36 |
|
28 | 37 | return null;
|
29 | 38 | }
|
30 | 39 |
|
| 40 | + /** |
| 41 | + * @param Node\Stmt[] $stmts |
| 42 | + * @return Node\Stmt[] |
| 43 | + */ |
| 44 | + private function keepVariadicsAndYields(array $stmts): array |
| 45 | + { |
| 46 | + $results = $this->nodeFinder->find($stmts, static function (Node $node): bool { |
| 47 | + if ($node instanceof Node\Expr\YieldFrom || $node instanceof Node\Expr\Yield_) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + if ($node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name) { |
| 51 | + return in_array($node->name->toLowerString(), ParametersAcceptor::VARIADIC_FUNCTIONS, true); |
| 52 | + } |
| 53 | + |
| 54 | + return false; |
| 55 | + }); |
| 56 | + $newStmts = []; |
| 57 | + foreach ($results as $result) { |
| 58 | + if ($result instanceof Node\Expr\Yield_ || $result instanceof Node\Expr\YieldFrom) { |
| 59 | + $newStmts[] = new Node\Stmt\Expression($result); |
| 60 | + continue; |
| 61 | + } |
| 62 | + if (!$result instanceof Node\Expr\FuncCall) { |
| 63 | + continue; |
| 64 | + } |
| 65 | + |
| 66 | + $newStmts[] = new Node\Stmt\Expression(new Node\Expr\FuncCall(new Node\Name\FullyQualified('func_get_args'))); |
| 67 | + } |
| 68 | + |
| 69 | + return $newStmts; |
| 70 | + } |
| 71 | + |
31 | 72 | }
|
0 commit comments