aboutsummaryrefslogtreecommitdiff
path: root/lib/exTpl/IteratorNode.php
blob: 58dd593599a84e9907f3129f452591f5219229d0 (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
<?php

namespace exTpl;

/**
 * IteratorNode represents a single iterator tag:
 * "{foreach ARRAY [as [KEY =>] VALUE]}...{endforeach}".
 */
class IteratorNode extends ArrayNode
{
    protected Expression $expr;
    protected string $key_name;
    protected string $val_name;

    /**
     * Initializes a new Node instance with the given expression.
     *
     * @param Expression $expr expression object
     * @param string $key_name name of variable on each iteration
     * @param string $val_name name of variable on each iteration
     */
    public function __construct(Expression $expr, string $key_name, string $val_name)
    {
        $this->expr     = $expr;
        $this->key_name = $key_name;
        $this->val_name = $val_name;
    }

    /**
     * Returns a string representation of this node. The IteratorNode
     * renders the node sequence for each value in the expression list.
     *
     * @param Context $context symbol table
     */
    public function render(Context $context): string
    {
        $values = $this->expr->value($context);
        $result = '';

        if (is_array($values) && is_int(key($values))) {
            $bindings = [$this->key_name => &$key, $this->val_name => &$value];
            $context  = new Context($bindings, $context);

            foreach ($values as $key => $value) {
                $result .= parent::render(new Context($value, $context));
            }
        } else if (is_array($values) && count($values)) {
            return parent::render(new Context($values, $context));
        } else if ($values) {
            return parent::render($context);
        }

        return $result;
    }
}