changed context access to use the PHP 7 null coalescing operator when available

This commit is contained in:
Fabien Potencier
2016-11-12 19:26:22 -08:00
parent 4419ff3ae4
commit 6effc9aa34
4 changed files with 28 additions and 5 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.28.0 (2016-XX-XX)
* changed context access to use the PHP 7 null coalescing operator when available
* added the "with" tag
* added support for a custom template on the block() function
* added "is defined" support for block() and constant()
+14 -4
View File
@@ -43,10 +43,20 @@ class Twig_Node_Expression_Name extends Twig_Node_Expression
->raw(']')
;
} else {
// remove the non-PHP 5.4 version when PHP 5.3 support is dropped
// as the non-optimized version is just a workaround for slow ternary operator
// when the context has a lot of variables
if (PHP_VERSION_ID >= 50400) {
if (PHP_VERSION_ID >= 70000) {
// use PHP 7 null coalescing operator
$compiler
->raw('($context[')
->string($name)
->raw('] ?? ')
;
if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) {
$compiler->raw('null)');
} else {
$compiler->raw('$this->getContext($context, ')->string($name)->raw('))');
}
} elseif (PHP_VERSION_ID >= 50400) {
// PHP 5.4 ternary operator performance was optimized
$compiler
->raw('(isset($context[')
+4
View File
@@ -46,6 +46,10 @@ abstract class Twig_Test_NodeTestCase extends PHPUnit_Framework_TestCase
{
$line = $line > 0 ? "// line {$line}\n" : '';
if (PHP_VERSION_ID >= 70000) {
return sprintf('%s($context["%s"] ?? null)', $line, $name, $name);
}
if (PHP_VERSION_ID >= 50400) {
return sprintf('%s(isset($context["%s"]) ? $context["%s"] : null)', $line, $name, $name);
}
+9 -1
View File
@@ -26,8 +26,16 @@ class Twig_Tests_Node_Expression_NameTest extends Twig_Test_NodeTestCase
$env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true));
$env1 = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => false));
if (PHP_VERSION_ID >= 70000) {
$output = '($context["foo"] ?? $this->getContext($context, "foo"))';
} elseif (PHP_VERSION_ID >= 50400) {
$output = '(isset($context["foo"]) ? $context["foo"] : $this->getContext($context, "foo"))';
} else {
$output = '$this->getContext($context, "foo")';
}
return array(
array($node, "// line 1\n".(PHP_VERSION_ID >= 50400 ? '(isset($context["foo"]) ? $context["foo"] : $this->getContext($context, "foo"))' : '$this->getContext($context, "foo")'), $env),
array($node, "// line 1\n".$output, $env),
array($node, $this->getVariableGetter('foo', 1), $env1),
array($context, "// line 1\n\$context"),
);