If.php 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * Tests a condition.
  13. *
  14. * <pre>
  15. * {% if users %}
  16. * <ul>
  17. * {% for user in users %}
  18. * <li>{{ user.username|e }}</li>
  19. * {% endfor %}
  20. * </ul>
  21. * {% endif %}
  22. * </pre>
  23. */
  24. class Twig_TokenParser_If extends Twig_TokenParser
  25. {
  26. /**
  27. * Parses a token and returns a node.
  28. *
  29. * @param Twig_Token $token A Twig_Token instance
  30. *
  31. * @return Twig_NodeInterface A Twig_NodeInterface instance
  32. */
  33. public function parse(Twig_Token $token)
  34. {
  35. $lineno = $token->getLine();
  36. $expr = $this->parser->getExpressionParser()->parseExpression();
  37. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  38. $body = $this->parser->subparse(array($this, 'decideIfFork'));
  39. $tests = array($expr, $body);
  40. $else = null;
  41. $end = false;
  42. while (!$end) {
  43. switch ($this->parser->getStream()->next()->getValue()) {
  44. case 'else':
  45. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  46. $else = $this->parser->subparse(array($this, 'decideIfEnd'));
  47. break;
  48. case 'elseif':
  49. $expr = $this->parser->getExpressionParser()->parseExpression();
  50. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  51. $body = $this->parser->subparse(array($this, 'decideIfFork'));
  52. $tests[] = $expr;
  53. $tests[] = $body;
  54. break;
  55. case 'endif':
  56. $end = true;
  57. break;
  58. default:
  59. throw new Twig_Error_Syntax(sprintf('Unexpected end of template. Twig was looking for the following tags "else", "elseif", or "endif" to close the "if" block started at line %d)', $lineno), -1);
  60. }
  61. }
  62. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  63. return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag());
  64. }
  65. public function decideIfFork(Twig_Token $token)
  66. {
  67. return $token->test(array('elseif', 'else', 'endif'));
  68. }
  69. public function decideIfEnd(Twig_Token $token)
  70. {
  71. return $token->test(array('endif'));
  72. }
  73. /**
  74. * Gets the tag name associated with this token parser.
  75. *
  76. * @param string The tag name
  77. */
  78. public function getTag()
  79. {
  80. return 'if';
  81. }
  82. }