vendor/twig/twig/src/Node/Expression/ArrayExpression.php line 59

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Twig\Node\Expression;
  11. use Twig\Compiler;
  12. class ArrayExpression extends AbstractExpression
  13. {
  14. private $index;
  15. public function __construct(array $elements, int $lineno)
  16. {
  17. parent::__construct($elements, [], $lineno);
  18. $this->index = -1;
  19. foreach ($this->getKeyValuePairs() as $pair) {
  20. if ($pair['key'] instanceof ConstantExpression && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) {
  21. $this->index = $pair['key']->getAttribute('value');
  22. }
  23. }
  24. }
  25. public function getKeyValuePairs()
  26. {
  27. $pairs = [];
  28. foreach (array_chunk($this->nodes, 2) as $pair) {
  29. $pairs[] = [
  30. 'key' => $pair[0],
  31. 'value' => $pair[1],
  32. ];
  33. }
  34. return $pairs;
  35. }
  36. public function hasElement(AbstractExpression $key)
  37. {
  38. foreach ($this->getKeyValuePairs() as $pair) {
  39. // we compare the string representation of the keys
  40. // to avoid comparing the line numbers which are not relevant here.
  41. if ((string) $key === (string) $pair['key']) {
  42. return true;
  43. }
  44. }
  45. return false;
  46. }
  47. public function addElement(AbstractExpression $value, AbstractExpression $key = null)
  48. {
  49. if (null === $key) {
  50. $key = new ConstantExpression(++$this->index, $value->getTemplateLine());
  51. }
  52. array_push($this->nodes, $key, $value);
  53. }
  54. public function compile(Compiler $compiler)
  55. {
  56. $compiler->raw('[');
  57. $first = true;
  58. foreach ($this->getKeyValuePairs() as $pair) {
  59. if (!$first) {
  60. $compiler->raw(', ');
  61. }
  62. $first = false;
  63. $compiler
  64. ->subcompile($pair['key'])
  65. ->raw(' => ')
  66. ->subcompile($pair['value'])
  67. ;
  68. }
  69. $compiler->raw(']');
  70. }
  71. }
  72. class_alias('Twig\Node\Expression\ArrayExpression', 'Twig_Node_Expression_Array');