NodeTraverser.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 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. /**
  11. * Twig_NodeTraverser is a node traverser.
  12. *
  13. * It visits all nodes and their children and calls the given visitor for each.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Twig_NodeTraverser
  18. {
  19. protected $env;
  20. protected $visitors = array();
  21. /**
  22. * Constructor.
  23. *
  24. * @param Twig_Environment $env A Twig_Environment instance
  25. * @param Twig_NodeVisitorInterface[] $visitors An array of Twig_NodeVisitorInterface instances
  26. */
  27. public function __construct(Twig_Environment $env, array $visitors = array())
  28. {
  29. $this->env = $env;
  30. foreach ($visitors as $visitor) {
  31. $this->addVisitor($visitor);
  32. }
  33. }
  34. /**
  35. * Adds a visitor.
  36. *
  37. * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
  38. */
  39. public function addVisitor(Twig_NodeVisitorInterface $visitor)
  40. {
  41. if (!isset($this->visitors[$visitor->getPriority()])) {
  42. $this->visitors[$visitor->getPriority()] = array();
  43. }
  44. $this->visitors[$visitor->getPriority()][] = $visitor;
  45. }
  46. /**
  47. * Traverses a node and calls the registered visitors.
  48. *
  49. * @param Twig_NodeInterface $node A Twig_NodeInterface instance
  50. *
  51. * @return Twig_NodeInterface
  52. */
  53. public function traverse(Twig_NodeInterface $node)
  54. {
  55. ksort($this->visitors);
  56. foreach ($this->visitors as $visitors) {
  57. foreach ($visitors as $visitor) {
  58. $node = $this->traverseForVisitor($visitor, $node);
  59. }
  60. }
  61. return $node;
  62. }
  63. protected function traverseForVisitor(Twig_NodeVisitorInterface $visitor, Twig_NodeInterface $node = null)
  64. {
  65. if (null === $node) {
  66. return;
  67. }
  68. $node = $visitor->enterNode($node, $this->env);
  69. foreach ($node as $k => $n) {
  70. if (false !== $n = $this->traverseForVisitor($visitor, $n)) {
  71. $node->setNode($k, $n);
  72. } else {
  73. $node->removeNode($k);
  74. }
  75. }
  76. return $visitor->leaveNode($node, $this->env);
  77. }
  78. }