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\Expression;
13
14use Twig\Compiler;
15use Twig\Error\SyntaxError;
16use Twig\Node\Expression\Variable\AssignContextVariable;
17use Twig\Node\Expression\Variable\ContextVariable;
18use Twig\Node\Node;
19
20/**
21 * Represents an arrow function.
22 *
23 * @author Fabien Potencier <fabien@symfony.com>
24 */
25class ArrowFunctionExpression extends AbstractExpression
26{
27    public function __construct(AbstractExpression $expr, Node $names, $lineno)
28    {
29        if ($names instanceof ContextVariable) {
30            $names = new ListExpression([new AssignContextVariable($names->getAttribute('name'), $names->getTemplateLine())], $lineno);
31        }
32
33        if (!$names instanceof ListExpression) {
34            throw new SyntaxError('The arrow function argument must be a list of variables or a single variable.', $names->getTemplateLine(), $names->getSourceContext());
35        }
36
37        parent::__construct(['expr' => $expr, 'names' => $names], [], $lineno);
38    }
39
40    public function compile(Compiler $compiler): void
41    {
42        $compiler
43            ->addDebugInfo($this)
44            ->raw('function (')
45            ->subcompile($this->getNode('names'))
46            ->raw(') use ($context, $macros) { ')
47        ;
48        foreach ($this->getNode('names') as $name) {
49            $compiler
50                ->raw('$context["')
51                ->raw($name->getAttribute('name'))
52                ->raw('"] = $__')
53                ->raw($name->getAttribute('name'))
54                ->raw('__; ')
55            ;
56        }
57        $compiler
58            ->raw('return ')
59            ->subcompile($this->getNode('expr'))
60            ->raw('; }')
61        ;
62    }
63}
64