summaryrefslogtreecommitdiff
path: root/src/ste/VariableNode.php
blob: cdffc3f1829ac35e09f3a9e5600f612ab7f8b6ea (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
<?php

namespace kch42\ste;

class VariableNode extends ASTNode
{
    /** @var string */
    public $name;

    /** @var ASTNode[][] */
    public $arrayfields;

    /**
     * @param string $tpl
     * @param int $off
     * @param string $name
     * @param ASTNode[][] $arrayfields
     */
    public function __construct(string $tpl, int $off, string $name, array $arrayfields)
    {
        parent::__construct($tpl, $off);

        $this->name = $name;
        $this->arrayfields = $arrayfields;
    }

    /**
     * @return string
     */
    public function transcompile(): string
    {
        $varaccess = '@$ste->scope[' . (is_numeric($this->name) ? $this->name : '"' . Misc::escape_text($this->name) . '"'). ']';
        foreach ($this->arrayfields as $af) {
            if (
                count($af) == 1
                && ($af[0] instanceof TextNode)
                && is_numeric($af[0]->text)
            ) {
                $varaccess .= '[' . $af[0]->text . ']';
            } else {
                $varaccess .= '[' . implode(".", array_map(function ($node) {
                    if ($node instanceof TextNode) {
                        return "\"" . Misc::escape_text($node->text) . "\"";
                    } elseif ($node instanceof VariableNode) {
                        return $node->transcompile();
                    }
                }, $af)). ']';
            }
        }
        return $varaccess;
    }
}