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