FindingVisitor.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\NodeVisitor;
  3. use PhpParser\Node;
  4. use PhpParser\NodeVisitorAbstract;
  5. /**
  6. * This visitor can be used to find and collect all nodes satisfying some criterion determined by
  7. * a filter callback.
  8. */
  9. class FindingVisitor extends NodeVisitorAbstract {
  10. /** @var callable Filter callback */
  11. protected $filterCallback;
  12. /** @var Node[] Found nodes */
  13. protected array $foundNodes;
  14. public function __construct(callable $filterCallback) {
  15. $this->filterCallback = $filterCallback;
  16. }
  17. /**
  18. * Get found nodes satisfying the filter callback.
  19. *
  20. * Nodes are returned in pre-order.
  21. *
  22. * @return Node[] Found nodes
  23. */
  24. public function getFoundNodes(): array {
  25. return $this->foundNodes;
  26. }
  27. public function beforeTraverse(array $nodes): ?array {
  28. $this->foundNodes = [];
  29. return null;
  30. }
  31. public function enterNode(Node $node) {
  32. $filterCallback = $this->filterCallback;
  33. if ($filterCallback($node)) {
  34. $this->foundNodes[] = $node;
  35. }
  36. return null;
  37. }
  38. }