Array.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. public function compile(Twig_Compiler $compiler)
  53. {
  54. $compiler->raw('array(');
  55. $first = true;
  56. foreach ($this->getKeyValuePairs() as $pair) {
  57. if (!$first) {
  58. $compiler->raw(', ');
  59. }
  60. $first = false;
  61. $compiler
  62. ->subcompile($pair['key'])
  63. ->raw(' => ')
  64. ->subcompile($pair['value'])
  65. ;
  66. }
  67. $compiler->raw(')');
  68. }
  69. }