1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 * (c) Armin Ronacher
8 *
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
11 */
12
13namespace Twig\Node;
14
15use Twig\Compiler;
16use Twig\Node\Expression\AbstractExpression;
17
18/**
19 * Represents an include node.
20 *
21 * @author Fabien Potencier <fabien@symfony.com>
22 */
23class IncludeNode extends Node implements NodeOutputInterface
24{
25    public function __construct(AbstractExpression $expr, AbstractExpression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null)
26    {
27        $nodes = ['expr' => $expr];
28        if (null !== $variables) {
29            $nodes['variables'] = $variables;
30        }
31
32        parent::__construct($nodes, ['only' => (bool) $only, 'ignore_missing' => (bool) $ignoreMissing], $lineno, $tag);
33    }
34
35    public function compile(Compiler $compiler)
36    {
37        $compiler->addDebugInfo($this);
38
39        if ($this->getAttribute('ignore_missing')) {
40            $compiler
41                ->write("try {\n")
42                ->indent()
43            ;
44        }
45
46        $this->addGetTemplate($compiler);
47
48        $compiler->raw('->display(');
49
50        $this->addTemplateArguments($compiler);
51
52        $compiler->raw(");\n");
53
54        if ($this->getAttribute('ignore_missing')) {
55            $compiler
56                ->outdent()
57                ->write("} catch (LoaderError \$e) {\n")
58                ->indent()
59                ->write("// ignore missing template\n")
60                ->outdent()
61                ->write("}\n\n")
62            ;
63        }
64    }
65
66    protected function addGetTemplate(Compiler $compiler)
67    {
68        $compiler
69             ->write('$this->loadTemplate(')
70             ->subcompile($this->getNode('expr'))
71             ->raw(', ')
72             ->repr($this->getTemplateName())
73             ->raw(', ')
74             ->repr($this->getTemplateLine())
75             ->raw(')')
76         ;
77    }
78
79    protected function addTemplateArguments(Compiler $compiler)
80    {
81        if (!$this->hasNode('variables')) {
82            $compiler->raw(false === $this->getAttribute('only') ? '$context' : '[]');
83        } elseif (false === $this->getAttribute('only')) {
84            $compiler
85                ->raw('twig_array_merge($context, ')
86                ->subcompile($this->getNode('variables'))
87                ->raw(')')
88            ;
89        } else {
90            $compiler->raw('twig_to_array(');
91            $compiler->subcompile($this->getNode('variables'));
92            $compiler->raw(')');
93        }
94    }
95}
96
97class_alias('Twig\Node\IncludeNode', 'Twig_Node_Include');
98