bug #1468 Fixed "starts with" a "ends with" operators for non-string arguments (hason)

This PR was merged into the 1.16-dev branch.

Discussion
----------

Fixed "starts with" a "ends with" operators for non-string arguments

Commits
-------

4c26981 Fixed "starts with" a "ends with" operators for non-string arguments
This commit is contained in:
Fabien Potencier
2014-08-03 10:10:53 +02:00
4 changed files with 27 additions and 10 deletions
+5 -5
View File
@@ -12,14 +12,14 @@ class Twig_Node_Expression_Binary_EndsWith extends Twig_Node_Expression_Binary
{
public function compile(Twig_Compiler $compiler)
{
$left = $compiler->getVarName();
$right = $compiler->getVarName();
$compiler
->raw('(0 === substr_compare(')
->raw(sprintf('(is_string($%s = ', $left))
->subcompile($this->getNode('left'))
->raw(', ')
->raw(sprintf(') && is_string($%s = ', $right))
->subcompile($this->getNode('right'))
->raw(', -strlen(')
->subcompile($this->getNode('right'))
->raw(')))')
->raw(sprintf(') && (\'\' === $%2$s || $%2$s === substr($%1$s, -strlen($%2$s))))', $left, $right))
;
}
@@ -12,13 +12,14 @@ class Twig_Node_Expression_Binary_StartsWith extends Twig_Node_Expression_Binary
{
public function compile(Twig_Compiler $compiler)
{
$varName = $compiler->getVarName();
$left = $compiler->getVarName();
$right = $compiler->getVarName();
$compiler
->raw(sprintf("(('' === (\$%s = ", $varName))
->subcompile($this->getNode('right'))
->raw(')) ? true : 0 === strpos(')
->raw(sprintf('(is_string($%s = ', $left))
->subcompile($this->getNode('left'))
->raw(sprintf(', $%s))', $varName))
->raw(sprintf(') && is_string($%s = ', $right))
->subcompile($this->getNode('right'))
->raw(sprintf(') && (\'\' === $%2$s || 0 === strpos($%1$s, $%2$s)))', $left, $right))
;
}
@@ -4,9 +4,23 @@ Twig supports the "ends with" operator
{{ 'foo' ends with 'o' ? 'OK' : 'KO' }}
{{ not ('foo' ends with 'f') ? 'OK' : 'KO' }}
{{ not ('foo' ends with 'foowaytoolong') ? 'OK' : 'KO' }}
{{ 'foo' ends with '' ? 'OK' : 'KO' }}
{{ '1' ends with true ? 'OK' : 'KO' }}
{{ 1 ends with true ? 'OK' : 'KO' }}
{{ 0 ends with false ? 'OK' : 'KO' }}
{{ '' ends with false ? 'OK' : 'KO' }}
{{ false ends with false ? 'OK' : 'KO' }}
{{ false ends with '' ? 'OK' : 'KO' }}
--DATA--
return array()
--EXPECT--
OK
OK
OK
OK
KO
KO
KO
KO
KO
KO
@@ -11,6 +11,7 @@ with 'f' ? 'OK' : 'KO' }}
{{ '1' starts with true ? 'OK' : 'KO' }}
{{ '' starts with false ? 'OK' : 'KO' }}
{{ 'a' starts with false ? 'OK' : 'KO' }}
{{ false starts with '' ? 'OK' : 'KO' }}
--DATA--
return array()
--EXPECT--
@@ -23,3 +24,4 @@ OK
KO
KO
KO
KO