vendor/twig/twig/src/TokenParser/BlockTokenParser.php line 34

  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\BlockNode;
  14. use Twig\Node\BlockReferenceNode;
  15. use Twig\Node\Node;
  16. use Twig\Node\PrintNode;
  17. use Twig\Token;
  18. /**
  19.  * Marks a section of a template as being reusable.
  20.  *
  21.  *  {% block head %}
  22.  *    <link rel="stylesheet" href="style.css" />
  23.  *    <title>{% block title %}{% endblock %} - My Webpage</title>
  24.  *  {% endblock %}
  25.  *
  26.  * @internal
  27.  */
  28. final class BlockTokenParser extends AbstractTokenParser
  29. {
  30.     public function parse(Token $token): Node
  31.     {
  32.         $lineno $token->getLine();
  33.         $stream $this->parser->getStream();
  34.         $name $stream->expect(Token::NAME_TYPE)->getValue();
  35.         $this->parser->setBlock($name$block = new BlockNode($name, new Node([]), $lineno));
  36.         $this->parser->pushLocalScope();
  37.         $this->parser->pushBlockStack($name);
  38.         if ($stream->nextIf(Token::BLOCK_END_TYPE)) {
  39.             $body $this->parser->subparse([$this'decideBlockEnd'], true);
  40.             if ($token $stream->nextIf(Token::NAME_TYPE)) {
  41.                 $value $token->getValue();
  42.                 if ($value != $name) {
  43.                     throw new SyntaxError(\sprintf('Expected endblock for block "%s" (but "%s" given).'$name$value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
  44.                 }
  45.             }
  46.         } else {
  47.             $body = new Node([
  48.                 new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno),
  49.             ]);
  50.         }
  51.         $stream->expect(Token::BLOCK_END_TYPE);
  52.         $block->setNode('body'$body);
  53.         $this->parser->popBlockStack();
  54.         $this->parser->popLocalScope();
  55.         return new BlockReferenceNode($name$lineno);
  56.     }
  57.     public function decideBlockEnd(Token $token): bool
  58.     {
  59.         return $token->test('endblock');
  60.     }
  61.     public function getTag(): string
  62.     {
  63.         return 'block';
  64.     }
  65. }