FirstFindingVisitor.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\NodeVisitor;
  3. use PhpParser\Node;
  4. use PhpParser\NodeTraverser;
  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. {
  12. /** @var callable Filter callback */
  13. protected $filterCallback;
  14. /** @var null|Node Found node */
  15. protected $foundNode;
  16. public function __construct(callable $filterCallback) {
  17. $this->filterCallback = $filterCallback;
  18. }
  19. /**
  20. * Get found node satisfying the filter callback.
  21. *
  22. * Returns null if no node satisfies the filter callback.
  23. *
  24. * @return null|Node Found node (or null if not found)
  25. */
  26. public function getFoundNode() {
  27. return $this->foundNode;
  28. }
  29. public function beforeTraverse(array $nodes) {
  30. $this->foundNode = null;
  31. return null;
  32. }
  33. public function enterNode(Node $node) {
  34. $filterCallback = $this->filterCallback;
  35. if ($filterCallback($node)) {
  36. $this->foundNode = $node;
  37. return NodeTraverser::STOP_TRAVERSAL;
  38. }
  39. return null;
  40. }
  41. }