FindingVisitor.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. {
  11. /** @var callable Filter callback */
  12. protected $filterCallback;
  13. /** @var Node[] Found nodes */
  14. protected $foundNodes;
  15. public function __construct(callable $filterCallback) {
  16. $this->filterCallback = $filterCallback;
  17. }
  18. /**
  19. * Get found nodes satisfying the filter callback.
  20. *
  21. * Nodes are returned in pre-order.
  22. *
  23. * @return Node[] Found nodes
  24. */
  25. public function getFoundNodes() : array {
  26. return $this->foundNodes;
  27. }
  28. public function beforeTraverse(array $nodes) {
  29. $this->foundNodes = [];
  30. return null;
  31. }
  32. public function enterNode(Node $node) {
  33. $filterCallback = $this->filterCallback;
  34. if ($filterCallback($node)) {
  35. $this->foundNodes[] = $node;
  36. }
  37. return null;
  38. }
  39. }