From 3b1f269e25c0783ccd1bff009086a3b5b696fe89 Mon Sep 17 00:00:00 2001 From: Arnaud Le Blanc Date: Sat, 12 Nov 2011 11:56:00 +0100 Subject: [PATCH] support any expression as hash key --- lib/Twig/ExpressionParser.php | 19 +++++++++++-------- lib/Twig/Node/Expression/Array.php | 6 +++--- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/lib/Twig/ExpressionParser.php b/lib/Twig/ExpressionParser.php index 33cc0dc..2fb19e4 100644 --- a/lib/Twig/ExpressionParser.php +++ b/lib/Twig/ExpressionParser.php @@ -166,6 +166,7 @@ class Twig_ExpressionParser $stream = $this->parser->getStream(); $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected'); $elements = array(); + $index = 0; while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { if (!empty($elements)) { $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma'); @@ -176,7 +177,12 @@ class Twig_ExpressionParser } } - $elements[] = $this->parseExpression(); + $value = $this->parseExpression(); + $key = new Twig_Node_Expression_Constant($index, $value->getLine()); + + array_push($elements, $key, $value); + + $index += 1; } $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed'); @@ -198,14 +204,11 @@ class Twig_ExpressionParser } } - if (!$stream->test(Twig_Token::STRING_TYPE) && !$stream->test(Twig_Token::NUMBER_TYPE)) { - $current = $stream->getCurrent(); - throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string or a number (unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($current->getType(), $current->getLine()), $current->getValue()), $current->getLine()); - } - - $key = $stream->next()->getValue(); + $key = $this->parseExpression(); $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)'); - $elements[$key] = $this->parseExpression(); + $value = $this->parseExpression(); + + array_push($elements, $key, $value); } $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed'); diff --git a/lib/Twig/Node/Expression/Array.php b/lib/Twig/Node/Expression/Array.php index 2d86082..2de67d4 100644 --- a/lib/Twig/Node/Expression/Array.php +++ b/lib/Twig/Node/Expression/Array.php @@ -24,16 +24,16 @@ class Twig_Node_Expression_Array extends Twig_Node_Expression { $compiler->raw('array('); $first = true; - foreach ($this->nodes as $name => $node) { + foreach (array_chunk($this->nodes, 2) as $entry) { if (!$first) { $compiler->raw(', '); } $first = false; $compiler - ->repr($name) + ->subcompile($entry[0]) ->raw(' => ') - ->subcompile($node) + ->subcompile($entry[1]) ; } $compiler->raw(')'); -- 1.7.2.5