vendor/twig/twig/src/TokenParser/IfTokenParser.php line 39

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  * (c) 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. namespace Twig\TokenParser;
  12. use Twig\Error\SyntaxError;
  13. use Twig\Node\IfNode;
  14. use Twig\Node\Node;
  15. use Twig\Token;
  16. /**
  17.  * Tests a condition.
  18.  *
  19.  *   {% if users %}
  20.  *    <ul>
  21.  *      {% for user in users %}
  22.  *        <li>{{ user.username|e }}</li>
  23.  *      {% endfor %}
  24.  *    </ul>
  25.  *   {% endif %}
  26.  */
  27. final class IfTokenParser extends AbstractTokenParser
  28. {
  29.     public function parse(Token $token)
  30.     {
  31.         $lineno $token->getLine();
  32.         $expr $this->parser->getExpressionParser()->parseExpression();
  33.         $stream $this->parser->getStream();
  34.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  35.         $body $this->parser->subparse([$this'decideIfFork']);
  36.         $tests = [$expr$body];
  37.         $else null;
  38.         $end false;
  39.         while (!$end) {
  40.             switch ($stream->next()->getValue()) {
  41.                 case 'else':
  42.                     $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  43.                     $else $this->parser->subparse([$this'decideIfEnd']);
  44.                     break;
  45.                 case 'elseif':
  46.                     $expr $this->parser->getExpressionParser()->parseExpression();
  47.                     $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  48.                     $body $this->parser->subparse([$this'decideIfFork']);
  49.                     $tests[] = $expr;
  50.                     $tests[] = $body;
  51.                     break;
  52.                 case 'endif':
  53.                     $end true;
  54.                     break;
  55.                 default:
  56.                     throw new SyntaxError(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->getSourceContext());
  57.             }
  58.         }
  59.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  60.         return new IfNode(new Node($tests), $else$lineno$this->getTag());
  61.     }
  62.     public function decideIfFork(Token $token)
  63.     {
  64.         return $token->test(['elseif''else''endif']);
  65.     }
  66.     public function decideIfEnd(Token $token)
  67.     {
  68.         return $token->test(['endif']);
  69.     }
  70.     public function getTag()
  71.     {
  72.         return 'if';
  73.     }
  74. }
  75. class_alias('Twig\TokenParser\IfTokenParser''Twig_TokenParser_If');