Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | /* |
| 4 | * This file is part of Twig. |
| 5 | * |
| 6 | * (c) Fabien Potencier |
| 7 | * (c) Armin Ronacher |
| 8 | * |
| 9 | * For the full copyright and license information, please view the LICENSE |
| 10 | * file that was distributed with this source code. |
| 11 | */ |
| 12 | |
| 13 | namespace Twig\Node; |
| 14 | |
| 15 | use Twig\Compiler; |
| 16 | |
| 17 | /** |
| 18 | * Represents an if node. |
| 19 | * |
| 20 | * @author Fabien Potencier <fabien@symfony.com> |
| 21 | */ |
| 22 | class IfNode extends Node |
| 23 | { |
| 24 | public function __construct(Node $tests, ?Node $else, int $lineno, string $tag = null) |
| 25 | { |
| 26 | $nodes = ['tests' => $tests]; |
| 27 | if (null !== $else) { |
| 28 | $nodes['else'] = $else; |
| 29 | } |
| 30 | |
| 31 | parent::__construct($nodes, [], $lineno, $tag); |
| 32 | } |
| 33 | |
| 34 | public function compile(Compiler $compiler): void |
| 35 | { |
| 36 | $compiler->addDebugInfo($this); |
| 37 | for ($i = 0, $count = \count($this->getNode('tests')); $i < $count; $i += 2) { |
| 38 | if ($i > 0) { |
| 39 | $compiler |
| 40 | ->outdent() |
| 41 | ->write('} elseif (') |
| 42 | ; |
| 43 | } else { |
| 44 | $compiler |
| 45 | ->write('if (') |
| 46 | ; |
| 47 | } |
| 48 | |
| 49 | $compiler |
| 50 | ->subcompile($this->getNode('tests')->getNode($i)) |
| 51 | ->raw(") {\n") |
| 52 | ->indent() |
| 53 | ->subcompile($this->getNode('tests')->getNode($i + 1)) |
| 54 | ; |
| 55 | } |
| 56 | |
| 57 | if ($this->hasNode('else')) { |
| 58 | $compiler |
| 59 | ->outdent() |
| 60 | ->write("} else {\n") |
| 61 | ->indent() |
| 62 | ->subcompile($this->getNode('else')) |
| 63 | ; |
| 64 | } |
| 65 | |
| 66 | $compiler |
| 67 | ->outdent() |
| 68 | ->write("}\n"); |
| 69 | } |
| 70 | } |