summaryrefslogtreecommitdiffstats
path: root/library/Graphite/Util/MacroTemplate.php
blob: 23a171ae1f8707bb1b4dd0afb79c317acad9ca2a (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
<?php

namespace Icinga\Module\Graphite\Util;

use InvalidArgumentException;

/**
 * A macro-based template for strings
 */
class MacroTemplate
{
    /**
     * Macros' start and end character
     *
     * @var string
     */
    protected $macroCharacter;

    /**
     * The parsed template
     *
     * @var string[]
     */
    protected $template;

    /**
     * Regex for reverse resolving patterns
     *
     * @var string
     */
    protected $reverseResolvePattern;

    /**
     * Wildcards
     *
     * @var string[]
     */
    protected $wildCards;

    /**
     * The original raw template
     *
     * @var string
     */
    protected $orgTemplate;

    /**
     * Constructor
     *
     * @param   string  $template           The raw template
     * @param   string  $macroCharacter     Macros' start and end character
     */
    public function __construct($template, $macroCharacter = '$')
    {
        $this->orgTemplate = $template;
        $this->macroCharacter = $macroCharacter;
        $this->template = explode($macroCharacter, $template);
        foreach ($this->template as $key => $value) {
            if (preg_match('/([^:]+):(.+)/', $value, $match)) {
                $wildCardKey = $match[1];
                $this->template[$key] = $wildCardKey;
                $this->wildCards[$wildCardKey] = $match[2];
            }
        }

        if (! (count($this->template) % 2)) {
            throw new InvalidArgumentException(
                'template contains odd number of ' . var_export($macroCharacter, true)
                    . 's: ' . var_export($template, true)
            );
        }
    }

    /**
     * Return a string based on this template with the macros resolved from the given variables
     *
     * @param   string[]  $variables
     * @param   string          $default    The default value for missing variables.
     *                                      By default the macro just isn't replaced.
     *
     * @return  string
     */
    public function resolve(array $variables, $default = null)
    {
        $macro = false;
        $result = []; // kind of string builder

        foreach ($this->template as $part) {
            if ($macro) {
                if (isset($variables[$part])) {
                    $result[] = $variables[$part];
                } elseif ($part === '') {
                    $result[] = $this->macroCharacter;
                } elseif ($default === null) {
                    $result[] = $this->macroCharacter;
                    $result[] = $part;
                    // add wildcards to result before they are
                    // overwritten from Template::getFullCurves()
                    if (isset($this->wildCards[$part])) {
                        $result[] = ':' . $this->wildCards[$part];
                    }

                    $result[] = $this->macroCharacter;
                } else {
                    if (isset($this->wildCards[$part])) {
                        $result[] = $this->wildCards[$part];
                    } else {
                        $result[] = $default;
                    }
                }
            } else {
                $result[] = $part;
            }

            $macro = ! $macro;
        }

        return implode($result);
    }

    /**
     * Try to reverse-resolve the given string
     *
     * @param   string  $resolved       A result of {@link resolve()}
     *
     * @return  string[]|false    Variables as passed to {@link resolve()} if successful
     */
    public function reverseResolve($resolved)
    {
        $matches = [];
        if (! preg_match($this->getReverseResolvePattern(), $resolved, $matches)) {
            return false;
        }

        $macro = false;
        $macros = [];
        $currentCapturedSubPatternIndex = 0;

        foreach ($this->template as $part) {
            if ($macro && ! isset($macros[$part])) {
                $macros[$part] = ++$currentCapturedSubPatternIndex;
            }

            $macro = ! $macro;
        }

        $macros = array_flip($macros);

        $result = [];
        foreach ($matches as $index => $match) {
            if ($index > 0) {
                $result[$macros[$index]] = $match;
            }
        }

        return $result;
    }

    /**
     * Return the raw template string this instance was constructed from
     *
     * @return string
     */
    public function __toString()
    {
        return $this->orgTemplate;
    }

    /**
     * Return the macros of this template
     *
     * @return string[]
     */
    public function getMacros()
    {
        $macro = false;
        $macros = [];

        foreach ($this->template as $part) {
            if ($macro) {
                $macros[$part] = null;
            }

            $macro = ! $macro;
        }

        unset($macros['']);

        return array_keys($macros);
    }

    /**
     * Get macros' start and end character
     *
     * @return string
     */
    public function getMacroCharacter()
    {
        return $this->macroCharacter;
    }

    /**
     * Get {@link reverseResolvePattern}
     *
     * @return string
     */
    protected function getReverseResolvePattern()
    {
        if ($this->reverseResolvePattern === null) {
            $result = ['/\A']; // kind of string builder
            $macro = false;
            $macros = [];
            $currentCapturedSubPatternIndex = 0;

            foreach ($this->template as $part) {
                if ($macro) {
                    if (isset($macros[$part])) {
                        $result[] = '\g{';
                        $result[] = $macros[$part];
                        $result[] = '}';
                    } else {
                        $macros[$part] = ++$currentCapturedSubPatternIndex;
                        $result[] = '(.*)';
                    }
                } else {
                    $result[] = preg_quote($part, '/');
                }

                $macro = ! $macro;
            }

            $result[] = '\z/s';

            $this->reverseResolvePattern = implode($result);
        }

        return $this->reverseResolvePattern;
    }
}