aboutsummaryrefslogtreecommitdiff
path: root/lib/exTpl/ConditionNode.php
blob: bab212141f8b73f2872847a127c8dbb5b19f55d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

namespace exTpl;

/**
 * ConditionNode represents a single condition tag:
 * "{if CONDITION}...{else}...{endif}".
 */
class ConditionNode extends ArrayNode
{
    protected Expression $condition;
    protected ArrayNode|null $else_node = null;

    /**
     * Initializes a new Node instance with the given expression.
     *
     * @param Expression $condition expression object
     */
    public function __construct(Expression $condition)
    {
        $this->condition = $condition;
    }

    /**
     * Adds an else block to this condition node.
     */
    public function addElse(): void
    {
        $this->else_node = new ArrayNode();
    }

    /**
     * Adds a child node to this condition node.
     *
     * @param Node $node child node to add
     */
    public function addChild(Node $node): void
    {
        if ($this->else_node) {
            $this->else_node->addChild($node);
        } else {
            parent::addChild($node);
        }
    }

    /**
     * Returns a string representation of this node.
     *
     * @param Context $context symbol table
     */
    public function render(Context $context): string
    {
        if ($this->condition->value($context)) {
            return parent::render($context);
        }

        return $this->else_node ? $this->else_node->render($context) : '';
    }
}