You are here

protected function Twig_NodeVisitor_Optimizer::enterOptimizeFor in Translation template extractor 7.3

Same name and namespace in other branches
  1. 6.3 vendor/Twig/NodeVisitor/Optimizer.php \Twig_NodeVisitor_Optimizer::enterOptimizeFor()

Optimizes "for" tag by removing the "loop" variable creation whenever possible.

Parameters

Twig_NodeInterface $node A Node:

Twig_Environment $env The current Twig environment:

1 call to Twig_NodeVisitor_Optimizer::enterOptimizeFor()
Twig_NodeVisitor_Optimizer::doEnterNode in vendor/Twig/NodeVisitor/Optimizer.php
Called before child nodes are visited.

File

vendor/Twig/NodeVisitor/Optimizer.php, line 176

Class

Twig_NodeVisitor_Optimizer
Twig_NodeVisitor_Optimizer tries to optimizes the AST.

Code

protected function enterOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env) {
  if ($node instanceof Twig_Node_For) {

    // disable the loop variable by default
    $node
      ->setAttribute('with_loop', false);
    array_unshift($this->loops, $node);
    array_unshift($this->loopsTargets, $node
      ->getNode('value_target')
      ->getAttribute('name'));
    array_unshift($this->loopsTargets, $node
      ->getNode('key_target')
      ->getAttribute('name'));
  }
  elseif (!$this->loops) {

    // we are outside a loop
    return;
  }
  elseif ($node instanceof Twig_Node_Expression_Name && 'loop' === $node
    ->getAttribute('name')) {
    $node
      ->setAttribute('always_defined', true);
    $this
      ->addLoopToCurrent();
  }
  elseif ($node instanceof Twig_Node_Expression_Name && in_array($node
    ->getAttribute('name'), $this->loopsTargets)) {
    $node
      ->setAttribute('always_defined', true);
  }
  elseif ($node instanceof Twig_Node_BlockReference || $node instanceof Twig_Node_Expression_BlockReference) {
    $this
      ->addLoopToCurrent();
  }
  elseif ($node instanceof Twig_Node_Include && !$node
    ->getAttribute('only')) {
    $this
      ->addLoopToAll();
  }
  elseif ($node instanceof Twig_Node_Expression_Function && 'include' === $node
    ->getAttribute('name') && (!$node
    ->getNode('arguments')
    ->hasNode('with_context') || false !== $node
    ->getNode('arguments')
    ->getNode('with_context')
    ->getAttribute('value'))) {
    $this
      ->addLoopToAll();
  }
  elseif ($node instanceof Twig_Node_Expression_GetAttr && (!$node
    ->getNode('attribute') instanceof Twig_Node_Expression_Constant || 'parent' === $node
    ->getNode('attribute')
    ->getAttribute('value')) && (true === $this->loops[0]
    ->getAttribute('with_loop') || $node
    ->getNode('node') instanceof Twig_Node_Expression_Name && 'loop' === $node
    ->getNode('node')
    ->getAttribute('name'))) {
    $this
      ->addLoopToAll();
  }
}