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;
15
16class ArrayExpression extends AbstractExpression
17{
18    private $index;
19
20    public function __construct(array $elements, int $lineno)
21    {
22        parent::__construct($elements, [], $lineno);
23
24        $this->index = -1;
25        foreach ($this->getKeyValuePairs() as $pair) {
26            if ($pair['key'] instanceof ConstantExpression && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) {
27                $this->index = $pair['key']->getAttribute('value');
28            }
29        }
30    }
31
32    public function getKeyValuePairs()
33    {
34        $pairs = [];
35
36        foreach (array_chunk($this->nodes, 2) as $pair) {
37            $pairs[] = [
38                'key' => $pair[0],
39                'value' => $pair[1],
40            ];
41        }
42
43        return $pairs;
44    }
45
46    public function hasElement(AbstractExpression $key)
47    {
48        foreach ($this->getKeyValuePairs() as $pair) {
49            // we compare the string representation of the keys
50            // to avoid comparing the line numbers which are not relevant here.
51            if ((string) $key === (string) $pair['key']) {
52                return true;
53            }
54        }
55
56        return false;
57    }
58
59    public function addElement(AbstractExpression $value, AbstractExpression $key = null)
60    {
61        if (null === $key) {
62            $key = new ConstantExpression(++$this->index, $value->getTemplateLine());
63        }
64
65        array_push($this->nodes, $key, $value);
66    }
67
68    public function compile(Compiler $compiler)
69    {
70        $compiler->raw('[');
71        $first = true;
72        foreach ($this->getKeyValuePairs() as $pair) {
73            if (!$first) {
74                $compiler->raw(', ');
75            }
76            $first = false;
77
78            $compiler
79                ->subcompile($pair['key'])
80                ->raw(' => ')
81                ->subcompile($pair['value'])
82            ;
83        }
84        $compiler->raw(']');
85    }
86}
87
88class_alias('Twig\Node\Expression\ArrayExpression', 'Twig_Node_Expression_Array');
89