FirstFindingVisitor.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\NodeVisitor;
  3. use PhpParser\Node;
  4. use PhpParser\NodeVisitor;
  5. use PhpParser\NodeVisitorAbstract;
  6. /**
  7. * This visitor can be used to find the first node satisfying some criterion determined by
  8. * a filter callback.
  9. */
  10. class FirstFindingVisitor extends NodeVisitorAbstract {
  11. /** @var callable Filter callback */
  12. protected $filterCallback;
  13. /** @var null|Node Found node */
  14. protected ?Node $foundNode;
  15. public function __construct(callable $filterCallback) {
  16. $this->filterCallback = $filterCallback;
  17. }
  18. /**
  19. * Get found node satisfying the filter callback.
  20. *
  21. * Returns null if no node satisfies the filter callback.
  22. *
  23. * @return null|Node Found node (or null if not found)
  24. */
  25. public function getFoundNode(): ?Node {
  26. return $this->foundNode;
  27. }
  28. public function beforeTraverse(array $nodes): ?array {
  29. $this->foundNode = null;
  30. return null;
  31. }
  32. public function enterNode(Node $node) {
  33. $filterCallback = $this->filterCallback;
  34. if ($filterCallback($node)) {
  35. $this->foundNode = $node;
  36. return NodeVisitor::STOP_TRAVERSAL;
  37. }
  38. return null;
  39. }
  40. }