If.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  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. * Represents an if node.
  13. *
  14. * @package twig
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Twig_Node_If extends Twig_Node
  18. {
  19. public function __construct(Twig_NodeInterface $tests, Twig_NodeInterface $else = null, $lineno, $tag = null)
  20. {
  21. parent::__construct(array('tests' => $tests, 'else' => $else), array(), $lineno, $tag);
  22. }
  23. /**
  24. * Compiles the node to PHP.
  25. *
  26. * @param Twig_Compiler A Twig_Compiler instance
  27. */
  28. public function compile(Twig_Compiler $compiler)
  29. {
  30. $compiler->addDebugInfo($this);
  31. for ($i = 0; $i < count($this->getNode('tests')); $i += 2) {
  32. if ($i > 0) {
  33. $compiler
  34. ->outdent()
  35. ->write("} elseif (")
  36. ;
  37. } else {
  38. $compiler
  39. ->write('if (')
  40. ;
  41. }
  42. $compiler
  43. ->subcompile($this->getNode('tests')->getNode($i))
  44. ->raw(") {\n")
  45. ->indent()
  46. ->subcompile($this->getNode('tests')->getNode($i + 1))
  47. ;
  48. }
  49. if ($this->hasNode('else') && null !== $this->getNode('else')) {
  50. $compiler
  51. ->outdent()
  52. ->write("} else {\n")
  53. ->indent()
  54. ->subcompile($this->getNode('else'))
  55. ;
  56. }
  57. $compiler
  58. ->outdent()
  59. ->write("}\n");
  60. }
  61. }