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

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