Array.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 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. class Twig_Node_Expression_Array extends Twig_Node_Expression
  11. {
  12. protected $index;
  13. public function __construct(array $elements, $lineno)
  14. {
  15. parent::__construct($elements, array(), $lineno);
  16. $this->index = -1;
  17. foreach ($this->getKeyValuePairs() as $pair) {
  18. if ($pair['key'] instanceof Twig_Node_Expression_Constant && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) {
  19. $this->index = $pair['key']->getAttribute('value');
  20. }
  21. }
  22. }
  23. public function getKeyValuePairs()
  24. {
  25. $pairs = array();
  26. foreach (array_chunk($this->nodes, 2) as $pair) {
  27. $pairs[] = array(
  28. 'key' => $pair[0],
  29. 'value' => $pair[1],
  30. );
  31. }
  32. return $pairs;
  33. }
  34. public function hasElement(Twig_Node_Expression $key)
  35. {
  36. foreach ($this->getKeyValuePairs() as $pair) {
  37. // we compare the string representation of the keys
  38. // to avoid comparing the line numbers which are not relevant here.
  39. if ((string) $key == (string) $pair['key']) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. public function addElement(Twig_Node_Expression $value, Twig_Node_Expression $key = null)
  46. {
  47. if (null === $key) {
  48. $key = new Twig_Node_Expression_Constant(++$this->index, $value->getLine());
  49. }
  50. array_push($this->nodes, $key, $value);
  51. }
  52. /**
  53. * Compiles the node to PHP.
  54. *
  55. * @param Twig_Compiler A Twig_Compiler instance
  56. */
  57. public function compile(Twig_Compiler $compiler)
  58. {
  59. $compiler->raw('array(');
  60. $first = true;
  61. foreach ($this->getKeyValuePairs() as $pair) {
  62. if (!$first) {
  63. $compiler->raw(', ');
  64. }
  65. $first = false;
  66. $compiler
  67. ->subcompile($pair['key'])
  68. ->raw(' => ')
  69. ->subcompile($pair['value'])
  70. ;
  71. }
  72. $compiler->raw(')');
  73. }
  74. }