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\ConstantExpression;
16use Twig\Node\Node;
17use Twig\Token;
18
19/**
20 * Imports blocks defined in another template into the current template.
21 *
22 *    {% extends "base.html" %}
23 *
24 *    {% use "blocks.html" %}
25 *
26 *    {% block title %}{% endblock %}
27 *    {% block content %}{% endblock %}
28 *
29 * @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for details.
30 *
31 * @final
32 */
33class UseTokenParser extends AbstractTokenParser
34{
35    public function parse(Token $token)
36    {
37        $template = $this->parser->getExpressionParser()->parseExpression();
38        $stream = $this->parser->getStream();
39
40        if (!$template instanceof ConstantExpression) {
41            throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
42        }
43
44        $targets = [];
45        if ($stream->nextIf('with')) {
46            do {
47                $name = $stream->expect(Token::NAME_TYPE)->getValue();
48
49                $alias = $name;
50                if ($stream->nextIf('as')) {
51                    $alias = $stream->expect(Token::NAME_TYPE)->getValue();
52                }
53
54                $targets[$name] = new ConstantExpression($alias, -1);
55
56                if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) {
57                    break;
58                }
59            } while (true);
60        }
61
62        $stream->expect(Token::BLOCK_END_TYPE);
63
64        $this->parser->addTrait(new Node(['template' => $template, 'targets' => new Node($targets)]));
65
66        return new Node();
67    }
68
69    public function getTag()
70    {
71        return 'use';
72    }
73}
74
75class_alias('Twig\TokenParser\UseTokenParser', 'Twig_TokenParser_Use');
76