Permalink
Browse files

support any expression as hash key

  • Loading branch information...
1 parent 65f09ac commit 3b1f269e25c0783ccd1bff009086a3b5b696fe89 @arnaud-lb arnaud-lb committed Nov 12, 2011
Showing with 14 additions and 11 deletions.
  1. +11 −8 lib/Twig/ExpressionParser.php
  2. +3 −3 lib/Twig/Node/Expression/Array.php
@@ -166,6 +166,7 @@ public function parseArrayExpression()
$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 @@ public function parseArrayExpression()
}
}
- $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 @@ public function parseHashExpression()
}
}
- 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');
@@ -24,16 +24,16 @@ public function compile(Twig_Compiler $compiler)
{
$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(')');

0 comments on commit 3b1f269

Please sign in to comment.