Sin descripción

FindingVisitor.php 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. }