aboutsummaryrefslogtreecommitdiffhomepage
path: root/inc/Twig/NodeTraverser.php
diff options
context:
space:
mode:
Diffstat (limited to 'inc/Twig/NodeTraverser.php')
-rw-r--r--inc/Twig/NodeTraverser.php88
1 files changed, 88 insertions, 0 deletions
diff --git a/inc/Twig/NodeTraverser.php b/inc/Twig/NodeTraverser.php
new file mode 100644
index 00000000..28cba1ad
--- /dev/null
+++ b/inc/Twig/NodeTraverser.php
@@ -0,0 +1,88 @@
1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) 2009 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
12/**
13 * Twig_NodeTraverser is a node traverser.
14 *
15 * It visits all nodes and their children and call the given visitor for each.
16 *
17 * @author Fabien Potencier <fabien@symfony.com>
18 */
19class Twig_NodeTraverser
20{
21 protected $env;
22 protected $visitors;
23
24 /**
25 * Constructor.
26 *
27 * @param Twig_Environment $env A Twig_Environment instance
28 * @param array $visitors An array of Twig_NodeVisitorInterface instances
29 */
30 public function __construct(Twig_Environment $env, array $visitors = array())
31 {
32 $this->env = $env;
33 $this->visitors = array();
34 foreach ($visitors as $visitor) {
35 $this->addVisitor($visitor);
36 }
37 }
38
39 /**
40 * Adds a visitor.
41 *
42 * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
43 */
44 public function addVisitor(Twig_NodeVisitorInterface $visitor)
45 {
46 if (!isset($this->visitors[$visitor->getPriority()])) {
47 $this->visitors[$visitor->getPriority()] = array();
48 }
49
50 $this->visitors[$visitor->getPriority()][] = $visitor;
51 }
52
53 /**
54 * Traverses a node and calls the registered visitors.
55 *
56 * @param Twig_NodeInterface $node A Twig_NodeInterface instance
57 */
58 public function traverse(Twig_NodeInterface $node)
59 {
60 ksort($this->visitors);
61 foreach ($this->visitors as $visitors) {
62 foreach ($visitors as $visitor) {
63 $node = $this->traverseForVisitor($visitor, $node);
64 }
65 }
66
67 return $node;
68 }
69
70 protected function traverseForVisitor(Twig_NodeVisitorInterface $visitor, Twig_NodeInterface $node = null)
71 {
72 if (null === $node) {
73 return null;
74 }
75
76 $node = $visitor->enterNode($node, $this->env);
77
78 foreach ($node as $k => $n) {
79 if (false !== $n = $this->traverseForVisitor($visitor, $n)) {
80 $node->setNode($k, $n);
81 } else {
82 $node->removeNode($k);
83 }
84 }
85
86 return $visitor->leaveNode($node, $this->env);
87 }
88}