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

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