ArrayNode.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\ExpressionLanguage\Node;
  11. use Symfony\Component\ExpressionLanguage\Compiler;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. *
  15. * @internal
  16. */
  17. class ArrayNode extends Node
  18. {
  19. protected $index;
  20. public function __construct()
  21. {
  22. $this->index = -1;
  23. }
  24. public function addElement(Node $value, Node $key = null)
  25. {
  26. if (null === $key) {
  27. $key = new ConstantNode(++$this->index);
  28. }
  29. array_push($this->nodes, $key, $value);
  30. }
  31. /**
  32. * Compiles the node to PHP.
  33. */
  34. public function compile(Compiler $compiler)
  35. {
  36. $compiler->raw('[');
  37. $this->compileArguments($compiler);
  38. $compiler->raw(']');
  39. }
  40. public function evaluate(array $functions, array $values)
  41. {
  42. $result = [];
  43. foreach ($this->getKeyValuePairs() as $pair) {
  44. $result[$pair['key']->evaluate($functions, $values)] = $pair['value']->evaluate($functions, $values);
  45. }
  46. return $result;
  47. }
  48. public function toArray()
  49. {
  50. $value = [];
  51. foreach ($this->getKeyValuePairs() as $pair) {
  52. $value[$pair['key']->attributes['value']] = $pair['value'];
  53. }
  54. $array = [];
  55. if ($this->isHash($value)) {
  56. foreach ($value as $k => $v) {
  57. $array[] = ', ';
  58. $array[] = new ConstantNode($k);
  59. $array[] = ': ';
  60. $array[] = $v;
  61. }
  62. $array[0] = '{';
  63. $array[] = '}';
  64. } else {
  65. foreach ($value as $v) {
  66. $array[] = ', ';
  67. $array[] = $v;
  68. }
  69. $array[0] = '[';
  70. $array[] = ']';
  71. }
  72. return $array;
  73. }
  74. protected function getKeyValuePairs()
  75. {
  76. $pairs = [];
  77. foreach (array_chunk($this->nodes, 2) as $pair) {
  78. $pairs[] = ['key' => $pair[0], 'value' => $pair[1]];
  79. }
  80. return $pairs;
  81. }
  82. protected function compileArguments(Compiler $compiler, $withKeys = true)
  83. {
  84. $first = true;
  85. foreach ($this->getKeyValuePairs() as $pair) {
  86. if (!$first) {
  87. $compiler->raw(', ');
  88. }
  89. $first = false;
  90. if ($withKeys) {
  91. $compiler
  92. ->compile($pair['key'])
  93. ->raw(' => ')
  94. ;
  95. }
  96. $compiler->compile($pair['value']);
  97. }
  98. }
  99. }