1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Twig\TokenParser;
13
14use Twig\Error\SyntaxError;
15use Twig\Node\Expression\AssignNameExpression;
16use Twig\Node\ImportNode;
17use Twig\Token;
18
19/**
20 * Imports macros.
21 *
22 *   {% from 'forms.html' import forms %}
23 *
24 * @final
25 */
26class FromTokenParser extends AbstractTokenParser
27{
28    public function parse(Token $token)
29    {
30        $macro = $this->parser->getExpressionParser()->parseExpression();
31        $stream = $this->parser->getStream();
32        $stream->expect('import');
33
34        $targets = [];
35        do {
36            $name = $stream->expect(Token::NAME_TYPE)->getValue();
37
38            $alias = $name;
39            if ($stream->nextIf('as')) {
40                $alias = $stream->expect(Token::NAME_TYPE)->getValue();
41            }
42
43            $targets[$name] = $alias;
44
45            if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) {
46                break;
47            }
48        } while (true);
49
50        $stream->expect(Token::BLOCK_END_TYPE);
51
52        $node = new ImportNode($macro, new AssignNameExpression($this->parser->getVarName(), $token->getLine()), $token->getLine(), $this->getTag());
53
54        foreach ($targets as $name => $alias) {
55            if ($this->parser->isReservedMacroName($name)) {
56                throw new SyntaxError(sprintf('"%s" cannot be an imported macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getSourceContext());
57            }
58
59            $this->parser->addImportedSymbol('function', $alias, 'get'.$name, $node->getNode('var'));
60        }
61
62        return $node;
63    }
64
65    public function getTag()
66    {
67        return 'from';
68    }
69}
70
71class_alias('Twig\TokenParser\FromTokenParser', 'Twig_TokenParser_From');
72