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) public function __construct(\Twig_NodeInterface $left, \Twig_NodeInterface $right, $lineno)
{ {
$test = new AndBinary( $test = new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine());
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
new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), if (!$left instanceof BlockReferenceExpression) {
$left->getTemplateLine() $test = new AndBinary(
); $test,
new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()),
$left->getTemplateLine()
);
}
parent::__construct($test, $left, $right, $lineno); 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