From: Martin HasoĊˆ Date: Fri, 11 Jul 2014 08:37:09 +0000 (+0200) Subject: Fixed 'starts with' operator for empty needle X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=790305af935b6e18d08d74338185fca9dedc0cbb;p=web%2Fkonrad%2Ftwig.git Fixed 'starts with' operator for empty needle --- diff --git a/lib/Twig/Compiler.php b/lib/Twig/Compiler.php index ee00519..8ea3c93 100644 --- a/lib/Twig/Compiler.php +++ b/lib/Twig/Compiler.php @@ -267,4 +267,9 @@ class Twig_Compiler implements Twig_CompilerInterface return $this; } + + public function getVarName() + { + return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false)); + } } diff --git a/lib/Twig/Node/Expression/Binary/StartsWith.php b/lib/Twig/Node/Expression/Binary/StartsWith.php index eb8c107..b7c30b3 100644 --- a/lib/Twig/Node/Expression/Binary/StartsWith.php +++ b/lib/Twig/Node/Expression/Binary/StartsWith.php @@ -12,12 +12,13 @@ class Twig_Node_Expression_Binary_StartsWith extends Twig_Node_Expression_Binary { public function compile(Twig_Compiler $compiler) { + $varName = $compiler->getVarName(); $compiler - ->raw('(0 === strpos(') - ->subcompile($this->getNode('left')) - ->raw(', ') + ->raw(sprintf("(('' === (\$%s = ", $varName)) ->subcompile($this->getNode('right')) - ->raw('))') + ->raw(')) ? true : 0 === strpos(') + ->subcompile($this->getNode('left')) + ->raw(sprintf(', $%s))', $varName)) ; } diff --git a/test/Twig/Tests/Fixtures/expressions/starts_with.test b/test/Twig/Tests/Fixtures/expressions/starts_with.test index 1ae4f86..b960c8b 100644 --- a/test/Twig/Tests/Fixtures/expressions/starts_with.test +++ b/test/Twig/Tests/Fixtures/expressions/starts_with.test @@ -7,6 +7,10 @@ Twig supports the "starts with" operator {{ 'foo' starts with 'f' ? 'OK' : 'KO' }} {{ 'foo' starts with 'f' ? 'OK' : 'KO' }} +{{ 'foo' starts with '' ? 'OK' : 'KO' }} +{{ '1' starts with true ? 'OK' : 'KO' }} +{{ '' starts with false ? 'OK' : 'KO' }} +{{ 'a' starts with false ? 'OK' : 'KO' }} --DATA-- return array() --EXPECT-- @@ -15,3 +19,7 @@ OK OK OK OK +OK +KO +KO +KO