vendor/twig/twig/src/NodeTraverser.php line 53

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Twig;
  11. use Twig\Node\Node;
  12. use Twig\NodeVisitor\NodeVisitorInterface;
  13. /**
  14. * A node traverser.
  15. *
  16. * It visits all nodes and their children and calls the given visitor for each.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. final class NodeTraverser
  21. {
  22. private $env;
  23. private $visitors = [];
  24. /**
  25. * @param NodeVisitorInterface[] $visitors
  26. */
  27. public function __construct(Environment $env, array $visitors = [])
  28. {
  29. $this->env = $env;
  30. foreach ($visitors as $visitor) {
  31. $this->addVisitor($visitor);
  32. }
  33. }
  34. public function addVisitor(NodeVisitorInterface $visitor): void
  35. {
  36. $this->visitors[$visitor->getPriority()][] = $visitor;
  37. }
  38. /**
  39. * Traverses a node and calls the registered visitors.
  40. */
  41. public function traverse(Node $node): Node
  42. {
  43. ksort($this->visitors);
  44. foreach ($this->visitors as $visitors) {
  45. foreach ($visitors as $visitor) {
  46. $node = $this->traverseForVisitor($visitor, $node);
  47. }
  48. }
  49. return $node;
  50. }
  51. private function traverseForVisitor(NodeVisitorInterface $visitor, Node $node): ?Node
  52. {
  53. $node = $visitor->enterNode($node, $this->env);
  54. foreach ($node as $k => $n) {
  55. if (null !== $m = $this->traverseForVisitor($visitor, $n)) {
  56. if ($m !== $n) {
  57. $node->setNode($k, $m);
  58. }
  59. } else {
  60. $node->removeNode($k);
  61. }
  62. }
  63. return $visitor->leaveNode($node, $this->env);
  64. }
  65. }