NodeTraverser.php 2.3KB

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 call the given visitor for each.
  14. *
  15. * @package twig
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Twig_NodeTraverser
  19. {
  20. protected $env;
  21. protected $visitors;
  22. /**
  23. * Constructor.
  24. *
  25. * @param Twig_Environment $env A Twig_Environment instance
  26. * @param array $visitors An array of Twig_NodeVisitorInterface instances
  27. */
  28. public function __construct(Twig_Environment $env, array $visitors = array())
  29. {
  30. $this->env = $env;
  31. $this->visitors = array();
  32. foreach ($visitors as $visitor) {
  33. $this->addVisitor($visitor);
  34. }
  35. }
  36. /**
  37. * Adds a visitor.
  38. *
  39. * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
  40. */
  41. public function addVisitor(Twig_NodeVisitorInterface $visitor)
  42. {
  43. if (!isset($this->visitors[$visitor->getPriority()])) {
  44. $this->visitors[$visitor->getPriority()] = array();
  45. }
  46. $this->visitors[$visitor->getPriority()][] = $visitor;
  47. }
  48. /**
  49. * Traverses a node and calls the registered visitors.
  50. *
  51. * @param Twig_NodeInterface $node A Twig_NodeInterface instance
  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 null;
  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. }