Avoid creating unnecessary Twig_Markup instances, allows testing for falsiness of empty output

This commit is contained in:
Jordi Boggiano
2012-02-17 15:56:34 +01:00
parent 4b1a8e2798
commit e4590d0cd8
4 changed files with 15 additions and 6 deletions
+3 -3
View File
@@ -67,7 +67,7 @@ class Twig_Node_Set extends Twig_Node
$compiler->subcompile($this->getNode('names'), false);
if ($this->getAttribute('capture')) {
$compiler->raw(" = new Twig_Markup(ob_get_clean(), \$this->env->getCharset())");
$compiler->raw(" = ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset())");
}
}
@@ -87,9 +87,9 @@ class Twig_Node_Set extends Twig_Node
} else {
if ($this->getAttribute('safe')) {
$compiler
->raw("new Twig_Markup(")
->raw("('' === \$tmp = ")
->subcompile($this->getNode('values'))
->raw(", \$this->env->getCharset())")
->raw(") ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset())")
;
} else {
$compiler->subcompile($this->getNode('values'));
+1 -1
View File
@@ -429,7 +429,7 @@ abstract class Twig_Template implements Twig_TemplateInterface
// hack to be removed when macro calls are refactored
if ($object instanceof Twig_TemplateInterface) {
return new Twig_Markup($ret, $this->env->getCharset());
return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset());
}
return $ret;
@@ -0,0 +1,9 @@
--TEST--
"set" tag block empty capture
--TEMPLATE--
{% set foo %}{% endset %}
{% if foo %}FAIL{% endif %}
--DATA--
return array()
--EXPECT--
+2 -2
View File
@@ -51,14 +51,14 @@ class Twig_Tests_Node_SetTest extends Twig_Tests_Node_TestCase
$tests[] = array($node, <<<EOF
ob_start();
echo "foo";
\$context["foo"] = new Twig_Markup(ob_get_clean(), \$this->env->getCharset());
\$context["foo"] = ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset());
EOF
);
$names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 0)), array(), 0);
$values = new Twig_Node_Text('foo', 0);
$node = new Twig_Node_Set(true, $names, $values, 0);
$tests[] = array($node, '$context["foo"] = new Twig_Markup("foo", $this->env->getCharset());');
$tests[] = array($node, '$context["foo"] = (\'\' === $tmp = "foo") ? \'\' : new Twig_Markup($tmp, $this->env->getCharset());');
$names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 0), new Twig_Node_Expression_AssignName('bar', 0)), array(), 0);
$values = new Twig_Node(array(new Twig_Node_Expression_Constant('foo', 0), new Twig_Node_Expression_Name('bar', 0)), array(), 0);