From e70613fa010739a12f0b7829c309b93eb5c82971 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Sun, 22 Sep 2024 11:37:35 +0200 Subject: [PATCH] Add findInstancesOfScoped() to BetterNodeFinder, to ease re-use --- src/PhpParser/Node/BetterNodeFinder.php | 33 ++++++++++++++++++++----- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/PhpParser/Node/BetterNodeFinder.php b/src/PhpParser/Node/BetterNodeFinder.php index 36bb846ff10..7cccba9f133 100644 --- a/src/PhpParser/Node/BetterNodeFinder.php +++ b/src/PhpParser/Node/BetterNodeFinder.php @@ -166,18 +166,39 @@ public function hasInstancesOfInFunctionLikeScoped( $types = [$types]; } - $isFoundNode = false; + return $this->findInstancesOfScoped((array) $functionLike->stmts, $types) !== []; + } + + /** + * @api to be used + * + * @template T of Node + * @param Node[] $nodes + * @param class-string|array> $type + * @return T[] + */ + public function findInstancesOfScoped(array $nodes, string|array $type): array + { + /** @var T[] $foundNodes */ + $foundNodes = []; + + if (! is_array($type)) { + $types = [$type]; + } else { + $types = $type; + } + $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $functionLike->stmts, - static function (Node $subNode) use ($types, &$isFoundNode): ?int { + $nodes, + static function (Node $subNode) use ($types, &$foundNodes): ?int { if ($subNode instanceof Class_ || $subNode instanceof Function_ || $subNode instanceof Closure) { return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } foreach ($types as $type) { if ($subNode instanceof $type) { - $isFoundNode = true; - return NodeTraverser::STOP_TRAVERSAL; + $foundNodes[] = $subNode; + return null; } } @@ -185,7 +206,7 @@ static function (Node $subNode) use ($types, &$isFoundNode): ?int { } ); - return $isFoundNode; + return $foundNodes; } /**