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

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.  * @internal
  28.  */
  29. final class IfTokenParser extends AbstractTokenParser
  30. {
  31.     public function parse(Token $token): Node
  32.     {
  33.         $lineno $token->getLine();
  34.         $expr $this->parser->getExpressionParser()->parseExpression();
  35.         $stream $this->parser->getStream();
  36.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  37.         $body $this->parser->subparse([$this'decideIfFork']);
  38.         $tests = [$expr$body];
  39.         $else null;
  40.         $end false;
  41.         while (!$end) {
  42.             switch ($stream->next()->getValue()) {
  43.                 case 'else':
  44.                     $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  45.                     $else $this->parser->subparse([$this'decideIfEnd']);
  46.                     break;
  47.                 case 'elseif':
  48.                     $expr $this->parser->getExpressionParser()->parseExpression();
  49.                     $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  50.                     $body $this->parser->subparse([$this'decideIfFork']);
  51.                     $tests[] = $expr;
  52.                     $tests[] = $body;
  53.                     break;
  54.                 case 'endif':
  55.                     $end true;
  56.                     break;
  57.                 default:
  58.                     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());
  59.             }
  60.         }
  61.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  62.         return new IfNode(new Node($tests), $else$lineno$this->getTag());
  63.     }
  64.     public function decideIfFork(Token $token): bool
  65.     {
  66.         return $token->test(['elseif''else''endif']);
  67.     }
  68.     public function decideIfEnd(Token $token): bool
  69.     {
  70.         return $token->test(['endif']);
  71.     }
  72.     public function getTag(): string
  73.     {
  74.         return 'if';
  75.     }
  76. }