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