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

76 lines
2.0 KiB
PHP
Raw Normal View History

2024-06-20 14:10:42 +00:00
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* 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;
2025-01-13 09:56:01 +00:00
use Twig\Node\EmptyNode;
2024-06-20 14:10:42 +00:00
use Twig\Node\Expression\ConstantExpression;
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\Token;
/**
* Imports blocks defined in another template into the current template.
*
* {% extends "base.html" %}
*
* {% use "blocks.html" %}
*
* {% block title %}{% endblock %}
* {% block content %}{% endblock %}
*
* @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for details.
*
* @internal
*/
final class UseTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$template = $this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
if (!$template instanceof ConstantExpression) {
throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$targets = [];
if ($stream->nextIf('with')) {
while (true) {
2025-01-13 09:56:01 +00:00
$name = $stream->expect(Token::NAME_TYPE)->getValue();
2024-06-20 14:10:42 +00:00
$alias = $name;
if ($stream->nextIf('as')) {
2025-01-13 09:56:01 +00:00
$alias = $stream->expect(Token::NAME_TYPE)->getValue();
2024-06-20 14:10:42 +00:00
}
$targets[$name] = new ConstantExpression($alias, -1);
2025-01-13 09:56:01 +00:00
if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) {
2024-06-20 14:10:42 +00:00
break;
}
}
}
2025-01-13 09:56:01 +00:00
$stream->expect(Token::BLOCK_END_TYPE);
2024-06-20 14:10:42 +00:00
2025-01-13 09:56:01 +00:00
$this->parser->addTrait(new Nodes(['template' => $template, 'targets' => new Nodes($targets)]));
2024-06-20 14:10:42 +00:00
2025-01-13 09:56:01 +00:00
return new EmptyNode($token->getLine());
2024-06-20 14:10:42 +00:00
}
public function getTag(): string
{
return 'use';
}
}