No Description

ParentConnectingVisitor.php 865B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\NodeVisitor;
  3. use function array_pop;
  4. use function count;
  5. use PhpParser\Node;
  6. use PhpParser\NodeVisitorAbstract;
  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. /**
  16. * @var Node[]
  17. */
  18. private $stack = [];
  19. public function beforeTraverse(array $nodes)
  20. {
  21. $this->stack = [];
  22. }
  23. public function enterNode(Node $node)
  24. {
  25. if (!empty($this->stack)) {
  26. $node->setAttribute('parent', $this->stack[count($this->stack) - 1]);
  27. }
  28. $this->stack[] = $node;
  29. }
  30. public function leaveNode(Node $node)
  31. {
  32. array_pop($this->stack);
  33. }
  34. }