From d8951853ba5a5c33e859abffca8e986aae35f21b Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 14 Jan 2012 09:27:35 +0100 Subject: [PATCH] added support for optional length in the slice [] notation --- lib/Twig/ExpressionParser.php | 8 +++++++- test/Twig/Tests/Fixtures/filters/slice.test | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/Twig/ExpressionParser.php b/lib/Twig/ExpressionParser.php index bbe5d97..ddbdc8f 100644 --- a/lib/Twig/ExpressionParser.php +++ b/lib/Twig/ExpressionParser.php @@ -354,8 +354,14 @@ class Twig_ExpressionParser if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) { $stream->next(); + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { + $length = new Twig_Node_Expression_Constant(null, $token->getLine()); + } else { + $length = $this->parseExpression(); + } + $class = $this->getFilterNodeClass('slice'); - $arguments = new Twig_Node(array($arg, $this->parseExpression())); + $arguments = new Twig_Node(array($arg, $length)); $filter = new $class($node, new Twig_Node_Expression_Constant('slice', $token->getLine()), $arguments, $token->getLine()); $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']'); diff --git a/test/Twig/Tests/Fixtures/filters/slice.test b/test/Twig/Tests/Fixtures/filters/slice.test index da9861f..ae64b26 100644 --- a/test/Twig/Tests/Fixtures/filters/slice.test +++ b/test/Twig/Tests/Fixtures/filters/slice.test @@ -1,7 +1,7 @@ --TEST-- "slice" filter --TEMPLATE-- -{{ [1, 2, 3, 4][1:2]|join('')}} +{{ [1, 2, 3, 4][1:2]|join('') }} {{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }} {{ [1, 2, 3, 4][start:length]|join('') }} {{ [1, 2, 3, 4]|slice(1, 2)|join('') }} @@ -10,6 +10,9 @@ {{ '1234'[1:2] }} {{ arr|slice(1, 2)|join('') }} {{ arr[1:2]|join('') }} + +{{ [1, 2, 3, 4]|slice(1)|join('') }} +{{ [1, 2, 3, 4][1:]|join('') }} --DATA-- return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3, 4))) --EXPECT-- @@ -22,3 +25,6 @@ return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3 23 23 23 + +234 +234 -- 1.7.2.5