leilukin-tumbleblog/includes/lib/Twig/TokenParser/BlockTokenParser.php

78 lines
2.2 KiB
PHP
Raw Normal View History

2024-06-20 14:10:42 +00:00
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
2025-01-13 09:56:01 +00:00
use Twig\Node\EmptyNode;
2024-06-20 14:10:42 +00:00
use Twig\Node\Node;
2025-01-13 09:56:01 +00:00
use Twig\Node\Nodes;
2024-06-20 14:10:42 +00:00
use Twig\Node\PrintNode;
use Twig\Token;
/**
* Marks a section of a template as being reusable.
*
* {% block head %}
* <link rel="stylesheet" href="style.css" />
* <title>{% block title %}{% endblock %} - My Webpage</title>
* {% endblock %}
*
* @internal
*/
final class BlockTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
2025-01-13 09:56:01 +00:00
$name = $stream->expect(Token::NAME_TYPE)->getValue();
$this->parser->setBlock($name, $block = new BlockNode($name, new EmptyNode(), $lineno));
2024-06-20 14:10:42 +00:00
$this->parser->pushLocalScope();
$this->parser->pushBlockStack($name);
2025-01-13 09:56:01 +00:00
if ($stream->nextIf(Token::BLOCK_END_TYPE)) {
2024-06-20 14:10:42 +00:00
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
2025-01-13 09:56:01 +00:00
if ($token = $stream->nextIf(Token::NAME_TYPE)) {
2024-06-20 14:10:42 +00:00
$value = $token->getValue();
if ($value != $name) {
2024-09-05 17:51:48 +00:00
throw new SyntaxError(\sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
2024-06-20 14:10:42 +00:00
}
}
} else {
2025-01-13 09:56:01 +00:00
$body = new Nodes([
2024-06-20 14:10:42 +00:00
new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno),
]);
}
2025-01-13 09:56:01 +00:00
$stream->expect(Token::BLOCK_END_TYPE);
2024-06-20 14:10:42 +00:00
$block->setNode('body', $body);
$this->parser->popBlockStack();
$this->parser->popLocalScope();
2025-01-13 09:56:01 +00:00
return new BlockReferenceNode($name, $lineno);
2024-06-20 14:10:42 +00:00
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endblock');
}
public function getTag(): string
{
return 'block';
}
}