Skip to content

Commit

Permalink
Fixed 'starts with' operator for empty needle
Browse files Browse the repository at this point in the history
  • Loading branch information
hason committed Aug 1, 2014
1 parent 5fd428e commit 790305a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
5 changes: 5 additions & 0 deletions lib/Twig/Compiler.php
Expand Up @@ -267,4 +267,9 @@ public function outdent($step = 1)

return $this;
}

public function getVarName()
{
return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false));
}
}
9 changes: 5 additions & 4 deletions lib/Twig/Node/Expression/Binary/StartsWith.php
Expand Up @@ -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))
;
}

Expand Down
8 changes: 8 additions & 0 deletions test/Twig/Tests/Fixtures/expressions/starts_with.test
Expand Up @@ -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--
Expand All @@ -15,3 +19,7 @@ OK
OK
OK
OK
OK
KO
KO
KO

0 comments on commit 790305a

Please sign in to comment.