{
$stream = $this->parser->getStream();
$stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
- $elements = array();
- $index = 0;
+
+ $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
+ $first = true;
while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
- if (!empty($elements)) {
+ if (!$first) {
$stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
// trailing ,?
break;
}
}
+ $first = false;
- $value = $this->parseExpression();
- $key = new Twig_Node_Expression_Constant($index, $value->getLine());
-
- array_push($elements, $key, $value);
-
- $index += 1;
+ $node->addElement($this->parseExpression());
}
$stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
- return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
+ return $node;
}
public function parseHashExpression()
{
$stream = $this->parser->getStream();
$stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
- $elements = array();
+
+ $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
+ $first = true;
while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
- if (!empty($elements)) {
+ if (!$first) {
$stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
// trailing ,?
break;
}
}
+ $first = false;
$key = $this->parseExpression();
$stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
$value = $this->parseExpression();
- array_push($elements, $key, $value);
+ $node->addElement($value, $key);
}
$stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
- return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
+ return $node;
}
public function parsePostfixExpression($node)
*/
class Twig_Node_Expression_Array extends Twig_Node_Expression
{
+ protected $index;
+
public function __construct(array $elements, $lineno)
{
parent::__construct($elements, array(), $lineno);
+
+ $this->index = -1;
+ foreach ($this->getKeyValuePairs() as $pair) {
+ if ($pair['key'] instanceof Twig_Node_Expression_Constant && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) {
+ $this->index = $pair['key']->getAttribute('value');
+ }
+ }
}
public function getKeyValuePairs()
return $pairs;
}
+ public function hasElement(Twig_Node_Expression $key)
+ {
+ foreach ($this->getKeyValuePairs() as $pair) {
+ if ($key == $pair['key']) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public function addElement(Twig_Node_Expression $value, Twig_Node_Expression $key = null)
+ {
+ if (null === $key) {
+ $key = new Twig_Node_Expression_Constant(++$this->index, $value->getLine());
+ }
+
+ array_push($this->nodes, $key, $value);
+ }
+
/**
* Compiles the node to PHP.
*