Skip to content

Commit

Permalink
optimized compilation for arrays when using a['b'] notation under cer…
Browse files Browse the repository at this point in the history
…tain conditions
  • Loading branch information
fabpot committed Jan 30, 2018
1 parent 734d2d8 commit d501e0e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
21 changes: 21 additions & 0 deletions lib/Twig/Node/Expression/GetAttr.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,27 @@ public function __construct(Twig_Node_Expression $node, Twig_Node_Expression $at

public function compile(Twig_Compiler $compiler)
{
// optimize array calls
if (
(!$compiler->getEnvironment()->isStrictVariables() || $this->getAttribute('ignore_strict_check'))
&& !$this->getAttribute('is_defined_test')
&& Twig_Template::ARRAY_CALL === $this->getAttribute('type')
) {
$compiler
->raw('(is_array(')
->subcompile($this->getNode('node'))
->raw(') || ')
->subcompile($this->getNode('node'))
->raw(' instanceof ArrayAccess ? (')
->subcompile($this->getNode('node'))
->raw('[')
->subcompile($this->getNode('attribute'))
->raw('] ?? null) : null)')
;

return;
}

$compiler->raw('twig_get_attribute($this->env, $this->source, ');

if ($this->getAttribute('ignore_strict_check')) {
Expand Down
2 changes: 1 addition & 1 deletion test/Twig/Tests/Node/Expression/GetAttrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function getTests()
$tests[] = array($node, sprintf('%s%s, "bar", array())', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1)));

$node = new Twig_Node_Expression_GetAttr($expr, $attr, $args, Twig_Template::ARRAY_CALL, 1);
$tests[] = array($node, sprintf('%s%s, "bar", array(), "array")', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1)));
$tests[] = array($node, sprintf('(is_array(%s) || ($context["foo"] ?? null) instanceof ArrayAccess ? (($context["foo"] ?? null)["bar"] ?? null) : null)', $this->getVariableGetter('foo', 1), $this->getVariableGetter('foo', 1)));

$args = new Twig_Node_Expression_Array(array(), 1);
$args->addElement(new Twig_Node_Expression_Name('foo', 1));
Expand Down

0 comments on commit d501e0e

Please sign in to comment.