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\Node\EmbedNode;
|
|
|
|
use Twig\Node\Expression\ConstantExpression;
|
|
|
|
use Twig\Node\Expression\NameExpression;
|
|
|
|
use Twig\Node\Node;
|
|
|
|
use Twig\Token;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Embeds a template.
|
|
|
|
*
|
|
|
|
* @internal
|
|
|
|
*/
|
|
|
|
final class EmbedTokenParser extends IncludeTokenParser
|
|
|
|
{
|
|
|
|
public function parse(Token $token): Node
|
|
|
|
{
|
|
|
|
$stream = $this->parser->getStream();
|
|
|
|
|
|
|
|
$parent = $this->parser->getExpressionParser()->parseExpression();
|
|
|
|
|
|
|
|
[$variables, $only, $ignoreMissing] = $this->parseArguments();
|
|
|
|
|
2025-01-13 09:56:01 +00:00
|
|
|
$parentToken = $fakeParentToken = new Token(Token::STRING_TYPE, '__parent__', $token->getLine());
|
2024-06-20 14:10:42 +00:00
|
|
|
if ($parent instanceof ConstantExpression) {
|
2025-01-13 09:56:01 +00:00
|
|
|
$parentToken = new Token(Token::STRING_TYPE, $parent->getAttribute('value'), $token->getLine());
|
2024-06-20 14:10:42 +00:00
|
|
|
} elseif ($parent instanceof NameExpression) {
|
2025-01-13 09:56:01 +00:00
|
|
|
$parentToken = new Token(Token::NAME_TYPE, $parent->getAttribute('name'), $token->getLine());
|
2024-06-20 14:10:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// inject a fake parent to make the parent() function work
|
|
|
|
$stream->injectTokens([
|
2025-01-13 09:56:01 +00:00
|
|
|
new Token(Token::BLOCK_START_TYPE, '', $token->getLine()),
|
|
|
|
new Token(Token::NAME_TYPE, 'extends', $token->getLine()),
|
2024-06-20 14:10:42 +00:00
|
|
|
$parentToken,
|
2025-01-13 09:56:01 +00:00
|
|
|
new Token(Token::BLOCK_END_TYPE, '', $token->getLine()),
|
2024-06-20 14:10:42 +00:00
|
|
|
]);
|
|
|
|
|
|
|
|
$module = $this->parser->parse($stream, [$this, 'decideBlockEnd'], true);
|
|
|
|
|
|
|
|
// override the parent with the correct one
|
|
|
|
if ($fakeParentToken === $parentToken) {
|
|
|
|
$module->setNode('parent', $parent);
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->parser->embedTemplate($module);
|
|
|
|
|
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
|
|
|
return new EmbedNode($module->getTemplateName(), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine());
|
2024-06-20 14:10:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function decideBlockEnd(Token $token): bool
|
|
|
|
{
|
|
|
|
return $token->test('endembed');
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getTag(): string
|
|
|
|
{
|
|
|
|
return 'embed';
|
|
|
|
}
|
|
|
|
}
|