If.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. public function parse(Twig_Token $token)
  27. {
  28. $lineno = $token->getLine();
  29. $expr = $this->parser->getExpressionParser()->parseExpression();
  30. $stream = $this->parser->getStream();
  31. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  32. $body = $this->parser->subparse(array($this, 'decideIfFork'));
  33. $tests = array($expr, $body);
  34. $else = null;
  35. $end = false;
  36. while (!$end) {
  37. switch ($stream->next()->getValue()) {
  38. case 'else':
  39. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  40. $else = $this->parser->subparse(array($this, 'decideIfEnd'));
  41. break;
  42. case 'elseif':
  43. $expr = $this->parser->getExpressionParser()->parseExpression();
  44. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  45. $body = $this->parser->subparse(array($this, 'decideIfFork'));
  46. $tests[] = $expr;
  47. $tests[] = $body;
  48. break;
  49. case 'endif':
  50. $end = true;
  51. break;
  52. default:
  53. 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), $stream->getCurrent()->getLine(), $stream->getFilename());
  54. }
  55. }
  56. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  57. return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag());
  58. }
  59. public function decideIfFork(Twig_Token $token)
  60. {
  61. return $token->test(array('elseif', 'else', 'endif'));
  62. }
  63. public function decideIfEnd(Twig_Token $token)
  64. {
  65. return $token->test(array('endif'));
  66. }
  67. public function getTag()
  68. {
  69. return 'if';
  70. }
  71. }