Fixed 'starts with' operator for empty needle

This commit is contained in:
Martin Hasoň
2014-07-11 10:37:09 +02:00
parent 5fd428ed76
commit 790305af93
3 changed files with 18 additions and 4 deletions
+5
View File
@@ -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));
}
}
@@ -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))
;
}
@@ -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