summaryrefslogtreecommitdiffstats
path: root/library/Director/CustomVariable/CustomVariable.php
blob: 98eda84d0d1e124edfd0a555cfcafa388be28065 (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<?php

namespace Icinga\Module\Director\CustomVariable;

use Exception;
use Icinga\Module\Director\Db\Cache\PrefetchCache;
use Icinga\Module\Director\IcingaConfig\IcingaConfigHelper as c;
use Icinga\Module\Director\IcingaConfig\IcingaConfigRenderer;
use InvalidArgumentException;
use LogicException;

abstract class CustomVariable implements IcingaConfigRenderer
{
    protected $key;

    protected $value;

    protected $storedValue;

    protected $type;

    protected $modified = false;

    protected $loadedFromDb = false;

    protected $deleted = false;

    protected $checksum;

    protected function __construct($key, $value = null)
    {
        $this->key = $key;
        $this->setValue($value);
    }

    public function is($type)
    {
        return $this->getType() === $type;
    }

    public function getType()
    {
        if ($this->type === null) {
            $parts = explode('\\', get_class($this));
            $class = end($parts);
            // strlen('CustomVariable') === 14
            $this->type = substr($class, 14);
        }

        return $this->type;
    }

    // TODO: implement delete()
    public function hasBeenDeleted()
    {
        return $this->deleted;
    }

    public function delete()
    {
        $this->deleted = true;
        return $this;
    }

    // TODO: abstract
    public function getDbValue()
    {
        return $this->getValue();
    }

    public function toJson()
    {
        if ($this->getDbFormat() === 'string') {
            return json_encode($this->getDbValue());
        } else {
            return $this->getDbValue();
        }
    }

    // TODO: abstract
    public function getDbFormat()
    {
        return 'string';
    }

    public function getKey()
    {
        return $this->key;
    }

    /**
     * @param $value
     * @return $this
     */
    abstract public function setValue($value);

    abstract public function getValue();

    /**
     * @param bool $renderExpressions
     * @return string
     */
    public function toConfigString($renderExpressions = false)
    {
        // TODO: this should be an abstract method once we deprecate PHP < 5.3.9
        throw new LogicException(sprintf(
            '%s has no toConfigString() implementation',
            get_class($this)
        ));
    }

    public function flatten(array &$flat, $prefix)
    {
        $flat[$prefix] = $this->getDbValue();
    }

    public function render($renderExpressions = false)
    {
        return c::renderKeyValue(
            $this->renderKeyName($this->getKey()),
            $this->toConfigStringPrefetchable($renderExpressions)
        );
    }

    protected function renderKeyName($key)
    {
        if (preg_match('/^[a-z][a-z0-9_]*$/i', $key)) {
            return 'vars.' . c::escapeIfReserved($key);
        } else {
            return 'vars[' . c::renderString($key) . ']';
        }
    }

    public function checksum()
    {
        // TODO: remember checksum, invalidate on change
        return sha1($this->getKey() . '=' . $this->toJson(), true);
    }

    public function isNew()
    {
        return ! $this->loadedFromDb;
    }

    public function hasBeenModified()
    {
        return $this->modified;
    }

    public function toConfigStringPrefetchable($renderExpressions = false)
    {
        if (PrefetchCache::shouldBeUsed()) {
            return PrefetchCache::instance()->renderVar($this, $renderExpressions);
        } else {
            return $this->toConfigString($renderExpressions);
        }
    }

    public function setModified($modified = true)
    {
        $this->modified = $modified;
        if (! $this->modified) {
            if (is_object($this->value)) {
                $this->storedValue = clone($this->value);
            } else {
                $this->storedValue = $this->value;
            }
        }

        return $this;
    }

    public function setUnmodified()
    {
        return $this->setModified(false);
    }

    public function setLoadedFromDb($loaded = true)
    {
        $this->loadedFromDb = $loaded;
        return $this;
    }

    abstract public function equals(CustomVariable $var);

    public function differsFrom(CustomVariable $var)
    {
        return ! $this->equals($var);
    }

    protected function setChecksum($checksum)
    {
        $this->checksum = $checksum;
        return $this;
    }

    public function getChecksum()
    {
        return $this->checksum;
    }

    public static function wantCustomVariable($key, $value)
    {
        if ($value instanceof CustomVariable) {
            return $value;
        }

        return self::create($key, $value);
    }

    public static function create($key, $value)
    {
        if (is_null($value)) {
            return new CustomVariableNull($key, $value);
        }

        if (is_bool($value)) {
            return new CustomVariableBoolean($key, $value);
        }

        if (is_int($value) || is_float($value)) {
            return new CustomVariableNumber($key, $value);
        }

        if (is_string($value)) {
            return new CustomVariableString($key, $value);
        } elseif (is_array($value)) {
            foreach (array_keys($value) as $k) {
                if (! (is_int($k) || ctype_digit($k))) {
                    return new CustomVariableDictionary($key, $value);
                }
            }

            return new CustomVariableArray($key, array_values($value));
        } elseif (is_object($value)) {
            // TODO: check for specific class/stdClass/interface?
            return new CustomVariableDictionary($key, $value);
        } else {
            throw new LogicException(sprintf('WTF (%s): %s', $key, var_export($value, 1)));
        }
    }

    public static function fromDbRow($row)
    {
        switch ($row->format) {
            case 'string':
                $var = new CustomVariableString($row->varname, $row->varvalue);
                break;
            case 'json':
                $var = self::create($row->varname, json_decode($row->varvalue));
                break;
            case 'expression':
                throw new InvalidArgumentException(
                    'Icinga code expressions are not yet supported'
                );
            default:
                throw new InvalidArgumentException(sprintf(
                    '%s is not a supported custom variable format',
                    $row->format
                ));
        }
        if (property_exists($row, 'checksum')) {
            $var->setChecksum($row->checksum);
        }

        $var->loadedFromDb = true;
        $var->setUnmodified();
        return $var;
    }

    public function __toString()
    {
        try {
            return $this->toConfigString();
        } catch (Exception $e) {
            trigger_error($e);
            $previousHandler = set_exception_handler(
                function () {
                }
            );
            restore_error_handler();
            call_user_func($previousHandler, $e);
            die();
        }
    }
}