ParentConnectingVisitor.php 860 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\NodeVisitor;
  3. use PhpParser\Node;
  4. use PhpParser\NodeVisitorAbstract;
  5. use function array_pop;
  6. use function count;
  7. /**
  8. * Visitor that connects a child node to its parent node.
  9. *
  10. * On the child node, the parent node can be accessed through
  11. * <code>$node->getAttribute('parent')</code>.
  12. */
  13. final class ParentConnectingVisitor extends NodeVisitorAbstract {
  14. /**
  15. * @var Node[]
  16. */
  17. private array $stack = [];
  18. public function beforeTraverse(array $nodes) {
  19. $this->stack = [];
  20. }
  21. public function enterNode(Node $node) {
  22. if (!empty($this->stack)) {
  23. $node->setAttribute('parent', $this->stack[count($this->stack) - 1]);
  24. }
  25. $this->stack[] = $node;
  26. }
  27. public function leaveNode(Node $node) {
  28. array_pop($this->stack);
  29. }
  30. }