blob: 0e25fe46ad83802dd1a611338a601d1d4080326a [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?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(): array
33 {
34 $pairs = [];
35 foreach (array_chunk($this->nodes, 2) as $pair) {
36 $pairs[] = [
37 'key' => $pair[0],
38 'value' => $pair[1],
39 ];
40 }
41
42 return $pairs;
43 }
44
45 public function hasElement(AbstractExpression $key): bool
46 {
47 foreach ($this->getKeyValuePairs() as $pair) {
48 // we compare the string representation of the keys
49 // to avoid comparing the line numbers which are not relevant here.
50 if ((string) $key === (string) $pair['key']) {
51 return true;
52 }
53 }
54
55 return false;
56 }
57
58 public function addElement(AbstractExpression $value, AbstractExpression $key = null): void
59 {
60 if (null === $key) {
61 $key = new ConstantExpression(++$this->index, $value->getTemplateLine());
62 }
63
64 array_push($this->nodes, $key, $value);
65 }
66
67 public function compile(Compiler $compiler): void
68 {
69 $compiler->raw('[');
70 $first = true;
71 foreach ($this->getKeyValuePairs() as $pair) {
72 if (!$first) {
73 $compiler->raw(', ');
74 }
75 $first = false;
76
77 $compiler
78 ->subcompile($pair['key'])
79 ->raw(' => ')
80 ->subcompile($pair['value'])
81 ;
82 }
83 $compiler->raw(']');
84 }
85}