| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of Twig. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
namespace ElementorDeps\Twig\Node\Expression; |
| 12 |
|
| 13 |
use ElementorDeps\Twig\Compiler; |
| 14 |
use ElementorDeps\Twig\Node\Expression\Binary\AndBinary; |
| 15 |
use ElementorDeps\Twig\Node\Expression\Test\DefinedTest; |
| 16 |
use ElementorDeps\Twig\Node\Expression\Test\NullTest; |
| 17 |
use ElementorDeps\Twig\Node\Expression\Unary\NotUnary; |
| 18 |
use ElementorDeps\Twig\Node\Node; |
| 19 |
class NullCoalesceExpression extends ConditionalExpression |
| 20 |
{ |
| 21 |
public function __construct(Node $left, Node $right, int $lineno) |
| 22 |
{ |
| 23 |
$test = new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()); |
| 24 |
// for "block()", we don't need the null test as the return value is always a string |
| 25 |
if (!$left instanceof BlockReferenceExpression) { |
| 26 |
$test = new AndBinary($test, new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), $left->getTemplateLine()); |
| 27 |
} |
| 28 |
parent::__construct($test, $left, $right, $lineno); |
| 29 |
} |
| 30 |
public function compile(Compiler $compiler) : void |
| 31 |
{ |
| 32 |
/* |
| 33 |
* This optimizes only one case. PHP 7 also supports more complex expressions |
| 34 |
* that can return null. So, for instance, if log is defined, log("foo") ?? "..." works, |
| 35 |
* but log($a["foo"]) ?? "..." does not if $a["foo"] is not defined. More advanced |
| 36 |
* cases might be implemented as an optimizer node visitor, but has not been done |
| 37 |
* as benefits are probably not worth the added complexity. |
| 38 |
*/ |
| 39 |
if ($this->getNode('expr2') instanceof NameExpression) { |
| 40 |
$this->getNode('expr2')->setAttribute('always_defined', \true); |
| 41 |
$compiler->raw('((')->subcompile($this->getNode('expr2'))->raw(') ?? (')->subcompile($this->getNode('expr3'))->raw('))'); |
| 42 |
} else { |
| 43 |
parent::compile($compiler); |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
|