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\Node;
13
14use Twig\Attribute\YieldReady;
15use Twig\Compiler;
16use Twig\Node\Expression\AbstractExpression;
17use Twig\Node\Expression\Variable\AssignTemplateVariable;
18use Twig\Node\Expression\Variable\ContextVariable;
19
20/**
21 * Represents an import node.
22 *
23 * @author Fabien Potencier <fabien@symfony.com>
24 */
25#[YieldReady]
26class ImportNode extends Node implements CoercesChildrenToStringInterface
27{
28    public function __construct(AbstractExpression $expr, AbstractExpression|AssignTemplateVariable $var, int $lineno)
29    {
30        if (\func_num_args() > 3) {
31            trigger_deprecation('twig/twig', '3.15', \sprintf('Passing more than 3 arguments to "%s()" is deprecated.', __METHOD__));
32        }
33
34        if (!$var instanceof AssignTemplateVariable) {
35            trigger_deprecation('twig/twig', '3.15', \sprintf('Passing a "%s" instance as the second argument of "%s" is deprecated, pass a "%s" instead.', $var::class, __CLASS__, AssignTemplateVariable::class));
36
37            $var = new AssignTemplateVariable($var->getAttribute('name'), $lineno);
38        }
39
40        parent::__construct(['expr' => $expr, 'var' => $var], [], $lineno);
41    }
42
43    public function compile(Compiler $compiler): void
44    {
45        $compiler->subcompile($this->getNode('var'));
46
47        if ($this->getNode('expr') instanceof ContextVariable && '_self' === $this->getNode('expr')->getAttribute('name')) {
48            $compiler->raw('$this');
49        } else {
50            $compiler
51                ->raw('$this->load(')
52                ->subcompile($this->getNode('expr'))
53                ->raw(', ')
54                ->repr($this->getTemplateLine())
55                ->raw(')->unwrap()')
56            ;
57        }
58
59        $compiler->raw(";\n");
60    }
61
62    public function getStringCoercedChildNames(): array
63    {
64        // the loader resolves the template-name expression by coercing it to a string
65        return ['expr'];
66    }
67}
68