Skip to content

Commit

Permalink
Add findInstancesOfScoped() to BetterNodeFinder, to ease re-use
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Sep 22, 2024
1 parent c5940d2 commit e70613f
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/PhpParser/Node/BetterNodeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,26 +166,47 @@ 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<T>|array<class-string<T>> $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;
}
}

return null;
}
);

return $isFoundNode;
return $foundNodes;
}

/**
Expand Down

0 comments on commit e70613f

Please sign in to comment.