blob: 35098c267b162f8c9c48864aa2932351e9006c7b [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?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\Node\Expression\AssignNameExpression;
15use Twig\Node\ImportNode;
16use Twig\Node\Node;
17use Twig\Token;
18
19/**
20 * Imports macros.
21 *
22 * {% from 'forms.html' import forms %}
23 *
24 * @internal
25 */
26final class FromTokenParser extends AbstractTokenParser
27{
28 public function parse(Token $token): Node
29 {
30 $macro = $this->parser->getExpressionParser()->parseExpression();
31 $stream = $this->parser->getStream();
32 $stream->expect(/* Token::NAME_TYPE */ 5, 'import');
33
34 $targets = [];
35 do {
36 $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
37
38 $alias = $name;
39 if ($stream->nextIf('as')) {
40 $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
41 }
42
43 $targets[$name] = $alias;
44
45 if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
46 break;
47 }
48 } while (true);
49
50 $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
51
52 $var = new AssignNameExpression($this->parser->getVarName(), $token->getLine());
53 $node = new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope());
54
55 foreach ($targets as $name => $alias) {
56 $this->parser->addImportedSymbol('function', $alias, 'macro_'.$name, $var);
57 }
58
59 return $node;
60 }
61
62 public function getTag(): string
63 {
64 return 'from';
65 }
66}