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

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\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 */ 5)->getValue();
  35.         if ($this->parser->hasBlock($name)) {
  36.             throw new SyntaxError(sprintf("The block '%s' has already been defined line %d."$name$this->parser->getBlock($name)->getTemplateLine()), $stream->getCurrent()->getLine(), $stream->getSourceContext());
  37.         }
  38.         $this->parser->setBlock($name$block = new BlockNode($name, new Node([]), $lineno));
  39.         $this->parser->pushLocalScope();
  40.         $this->parser->pushBlockStack($name);
  41.         if ($stream->nextIf(/* Token::BLOCK_END_TYPE */ 3)) {
  42.             $body $this->parser->subparse([$this'decideBlockEnd'], true);
  43.             if ($token $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
  44.                 $value $token->getValue();
  45.                 if ($value != $name) {
  46.                     throw new SyntaxError(sprintf('Expected endblock for block "%s" (but "%s" given).'$name$value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
  47.                 }
  48.             }
  49.         } else {
  50.             $body = new Node([
  51.                 new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno),
  52.             ]);
  53.         }
  54.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  55.         $block->setNode('body'$body);
  56.         $this->parser->popBlockStack();
  57.         $this->parser->popLocalScope();
  58.         return new BlockReferenceNode($name$lineno$this->getTag());
  59.     }
  60.     public function decideBlockEnd(Token $token): bool
  61.     {
  62.         return $token->test('endblock');
  63.     }
  64.     public function getTag(): string
  65.     {
  66.         return 'block';
  67.     }
  68. }