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

70 lines
1.9 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;
2025-01-13 09:56:01 +00:00
use Twig\Node\Expression\Variable\AssignContextVariable;
use Twig\Node\Expression\Variable\AssignTemplateVariable;
use Twig\Node\Expression\Variable\TemplateVariable;
2024-06-20 14:10:42 +00:00
use Twig\Node\ImportNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Imports macros.
*
2025-01-13 09:56:01 +00:00
* {% from 'forms.html.twig' import forms %}
2024-06-20 14:10:42 +00:00
*
* @internal
*/
final class FromTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$macro = $this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
2025-01-13 09:56:01 +00:00
$stream->expect(Token::NAME_TYPE, 'import');
2024-06-20 14:10:42 +00:00
$targets = [];
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
if ($stream->nextIf('as')) {
2025-01-13 09:56:01 +00:00
$alias = new AssignContextVariable($stream->expect(Token::NAME_TYPE)->getValue(), $token->getLine());
} else {
$alias = new AssignContextVariable($name, $token->getLine());
2024-06-20 14:10:42 +00:00
}
$targets[$name] = $alias;
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
$internalRef = new AssignTemplateVariable(new TemplateVariable(null, $token->getLine()), $this->parser->isMainScope());
$node = new ImportNode($macro, $internalRef, $token->getLine());
2024-06-20 14:10:42 +00:00
foreach ($targets as $name => $alias) {
2025-01-13 09:56:01 +00:00
$this->parser->addImportedSymbol('function', $alias->getAttribute('name'), 'macro_'.$name, $internalRef);
2024-06-20 14:10:42 +00:00
}
return $node;
}
public function getTag(): string
{
return 'from';
}
}