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

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