Optimize block('foo') ?? 'bar'

This commit is contained in:
Fabien Potencier
2019-09-20 08:33:24 +02:00
parent 144c557bb1
commit 7a99a4e7e5
2 changed files with 18 additions and 5 deletions
@@ -22,11 +22,15 @@ class NullCoalesceExpression extends ConditionalExpression
{
public function __construct(\Twig_NodeInterface $left, \Twig_NodeInterface $right, $lineno)
{
$test = new AndBinary(
new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()),
new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()),
$left->getTemplateLine()
);
$test = new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine());
// for "block()", we don't need the null test as the return value is always a string
if (!$left instanceof BlockReferenceExpression) {
$test = new AndBinary(
$test,
new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()),
$left->getTemplateLine()
);
}
parent::__construct($test, $left, $right, $lineno);
}
@@ -0,0 +1,9 @@
--TEST--
Twig supports the ?? operator with blocks
--TEMPLATE--
{% block foo %}OK{% endblock %}
{{ block('foo') ?? 'KO' }}
--DATA--
return []
--EXPECT--
OKOK