vendor/twig/twig/src/Node/IfNode.php line 58

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  * (c) Armin Ronacher
  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 Twig\Node;
  12. use Twig\Attribute\YieldReady;
  13. use Twig\Compiler;
  14. /**
  15.  * Represents an if node.
  16.  *
  17.  * @author Fabien Potencier <fabien@symfony.com>
  18.  */
  19. #[YieldReady]
  20. class IfNode extends Node
  21. {
  22.     public function __construct(Node $tests, ?Node $elseint $lineno, ?string $tag null)
  23.     {
  24.         $nodes = ['tests' => $tests];
  25.         if (null !== $else) {
  26.             $nodes['else'] = $else;
  27.         }
  28.         parent::__construct($nodes, [], $lineno$tag);
  29.     }
  30.     public function compile(Compiler $compiler): void
  31.     {
  32.         $compiler->addDebugInfo($this);
  33.         for ($i 0$count \count($this->getNode('tests')); $i $count$i += 2) {
  34.             if ($i 0) {
  35.                 $compiler
  36.                     ->outdent()
  37.                     ->write('} elseif (')
  38.                 ;
  39.             } else {
  40.                 $compiler
  41.                     ->write('if (')
  42.                 ;
  43.             }
  44.             $compiler
  45.                 ->subcompile($this->getNode('tests')->getNode((string) $i))
  46.                 ->raw(") {\n")
  47.                 ->indent()
  48.             ;
  49.             // The node might not exists if the content is empty
  50.             if ($this->getNode('tests')->hasNode((string) ($i 1))) {
  51.                 $compiler->subcompile($this->getNode('tests')->getNode((string) ($i 1)));
  52.             }
  53.         }
  54.         if ($this->hasNode('else')) {
  55.             $compiler
  56.                 ->outdent()
  57.                 ->write("} else {\n")
  58.                 ->indent()
  59.                 ->subcompile($this->getNode('else'))
  60.             ;
  61.         }
  62.         $compiler
  63.             ->outdent()
  64.             ->write("}\n");
  65.     }
  66. }