summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/html/src/TemplateString.php
blob: b1e01c0f5319ce0f09ee10f3a4abeee76cd4caac (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<?php

namespace ipl\Html;

use Exception;

/**
 * Render {{#mustache}}Mustache{{/mustache}}-like string from {@link ValidHtml} element arguments
 *
 * # Example Usage
 * ```
 * $info = TemplateString::create(
 *      'Follow the {{#doc}}HTML documentation{{/doc}} for more information on {{#strong}}HTML elements{{/strong}}',
 *      [
 *          'doc'    => new Link(null, 'doc/html'),
 *          'strong' => Html::tag('strong')
 *      ]
 * );
 * ```
 */
class TemplateString extends FormattedString
{
    /** @var array */
    protected $templateArgs = [];

    /** @var int  */
    protected $pos = 0;

    /** @var string  */
    protected $string;

    /** @var int */
    protected $length;

    public function __construct($format, $args = null)
    {
        $parentArgs = [];
        foreach ($args ?: [] as $val) {
            if (is_array($val) && is_string(key($val))) {
                $this->templateArgs += $val;
            } else {
                $parentArgs[] = $val;
            }
        }

        parent::__construct($format, $parentArgs);
    }

    /**
     * Parse template strings
     *
     * @param  ?string $for template name
     * @return HtmlDocument
     * @throws Exception in case of missing template argument or unbounded open or close templates
     */
    protected function parseTemplates($for = null)
    {
        $buffer = '';

        while (($char = $this->readChar()) !== false) {
            if ($char !== '{') {
                $buffer .= $char;
                continue;
            }

            $nextChar = $this->readChar();
            if ($nextChar !== '{') {
                $buffer .= $char . $nextChar;
                continue;
            }

            $templateHandle = $this->readChar();
            $start = $templateHandle === '#';
            $end = $templateHandle === '/';

            $templateKey = $this->readUntil('}');
            // if the string following '{{#' is read up to the last character or (length - 1)th character
            // then it is not a template
            if ($this->pos >= $this->length - 1) {
                $buffer .= $char . $nextChar . $templateHandle . $templateKey;
                continue;
            }

            $this->pos++;
            $closeChar = $this->readChar();

            if ($closeChar !== '}') {
                $buffer .= $char . $nextChar . $templateHandle . $templateKey . '}' . $closeChar;
                continue;
            }

            if ($start) {
                if (isset($this->templateArgs[$templateKey])) {
                    $wrapper = $this->templateArgs[$templateKey];

                    $buffer .= $this->parseTemplates($templateKey)->prependWrapper($wrapper);
                } else {
                    throw new Exception(sprintf(
                        'Missing template argument: %s ',
                        $templateKey
                    ));
                }
            } elseif ($for === $templateKey && $end) {
                // close the template
                $for = null;
                break;
            } else {
                // throw exception for unbounded closing of templates
                throw new Exception(sprintf(
                    'Unbound closing of template: %s',
                    $templateKey
                ));
            }
        }

        if ($this->pos === $this->length && $for !== null) {
            throw new Exception(sprintf(
                'Unbound opening of template: %s',
                $for
            ));
        }

        return (new HtmlDocument())->addHtml(HtmlString::create($buffer));
    }

    /**
     * Read until any of the given chars appears
     *
     * @param string ...$chars
     *
     * @return string
     */
    protected function readUntil(...$chars)
    {
        $buffer = '';
        while (($c = $this->readChar()) !== false) {
            if (in_array($c, $chars, true)) {
                $this->pos--;
                break;
            }

            $buffer .= $c;
        }

        return $buffer;
    }

    /**
     * Read a single character
     *
     * @return false|string false if there is no character left
     */
    protected function readChar()
    {
        if ($this->length > $this->pos) {
            return $this->string[$this->pos++];
        }

        return false;
    }

    public function render()
    {
        $formattedstring = parent::render();
        if (empty($this->templateArgs)) {
            return $formattedstring;
        }

        $this->string = $formattedstring;

        $this->length = strlen($formattedstring);

        return $this->parseTemplates()->render();
    }
}