src/NodeTraverser.php
5420a5e3
 <?php
 
037ee672
 /*
  * This file is part of Twig.
  *
  * (c) Fabien Potencier
  *
  * For the full copyright and license information, please view the LICENSE
  * file that was distributed with this source code.
  */
 
5420a5e3
 namespace Twig;
 
037ee672
 use Twig\Node\Node;
 use Twig\NodeVisitor\NodeVisitorInterface;
 
 /**
4eb0c9da
  * A node traverser.
037ee672
  *
  * It visits all nodes and their children and calls the given visitor for each.
  *
  * @author Fabien Potencier <fabien@symfony.com>
  */
 final class NodeTraverser
 {
     private $env;
     private $visitors = [];
 
     /**
      * @param NodeVisitorInterface[] $visitors
      */
     public function __construct(Environment $env, array $visitors = [])
     {
         $this->env = $env;
         foreach ($visitors as $visitor) {
             $this->addVisitor($visitor);
         }
     }
 
54cec4e3
     public function addVisitor(NodeVisitorInterface $visitor): void
037ee672
     {
         $this->visitors[$visitor->getPriority()][] = $visitor;
     }
 
     /**
      * Traverses a node and calls the registered visitors.
      */
6c91803a
     public function traverse(Node $node): Node
037ee672
     {
         ksort($this->visitors);
         foreach ($this->visitors as $visitors) {
             foreach ($visitors as $visitor) {
                 $node = $this->traverseForVisitor($visitor, $node);
             }
         }
 
         return $node;
     }
5420a5e3
 
54cec4e3
     private function traverseForVisitor(NodeVisitorInterface $visitor, Node $node): ?Node
5420a5e3
     {
037ee672
         $node = $visitor->enterNode($node, $this->env);
 
         foreach ($node as $k => $n) {
3ada8194
             if (null !== $m = $this->traverseForVisitor($visitor, $n)) {
037ee672
                 if ($m !== $n) {
                     $node->setNode($k, $m);
                 }
             } else {
                 $node->removeNode($k);
             }
         }
 
         return $visitor->leaveNode($node, $this->env);
5420a5e3
     }
 }