ArrayNode.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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('array(');
  37. $this->compileArguments($compiler);
  38. $compiler->raw(')');
  39. }
  40. public function evaluate($functions, $values)
  41. {
  42. $result = array();
  43. foreach ($this->getKeyValuePairs() as $pair) {
  44. $result[$pair['key']->evaluate($functions, $values)] = $pair['value']->evaluate($functions, $values);
  45. }
  46. return $result;
  47. }
  48. protected function getKeyValuePairs()
  49. {
  50. $pairs = array();
  51. foreach (array_chunk($this->nodes, 2) as $pair) {
  52. $pairs[] = array('key' => $pair[0], 'value' => $pair[1]);
  53. }
  54. return $pairs;
  55. }
  56. protected function compileArguments(Compiler $compiler, $withKeys = true)
  57. {
  58. $first = true;
  59. foreach ($this->getKeyValuePairs() as $pair) {
  60. if (!$first) {
  61. $compiler->raw(', ');
  62. }
  63. $first = false;
  64. if ($withKeys) {
  65. $compiler
  66. ->compile($pair['key'])
  67. ->raw(' => ')
  68. ;
  69. }
  70. $compiler->compile($pair['value']);
  71. }
  72. }
  73. }