summaryrefslogtreecommitdiffstats
path: root/library/Director/CustomVariable/CustomVariableArray.php
blob: 7e430a4ec0436c7159ff16e13eb8692a2bd26572 (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
<?php

namespace Icinga\Module\Director\CustomVariable;

use Icinga\Module\Director\IcingaConfig\IcingaConfigHelper as c;
use Icinga\Module\Director\IcingaConfig\IcingaLegacyConfigHelper as c1;

class CustomVariableArray extends CustomVariable
{
    /** @var  CustomVariable[] */
    protected $value;

    public function equals(CustomVariable $var)
    {
        if (! $var instanceof CustomVariableArray) {
            return false;
        }

        return $var->getDbValue() === $this->getDbValue();
    }

    public function getValue()
    {
        $ret = array();
        foreach ($this->value as $var) {
            $ret[] = $var->getValue();
        }

        return $ret;
    }

    public function getDbValue()
    {
        return json_encode($this->getValue());
    }

    public function getDbFormat()
    {
        return 'json';
    }

    public function setValue($value)
    {
        $new = array();

        foreach ($value as $k => $v) {
            $new[] = self::wantCustomVariable($k, $v);
        }

        $equals = true;
        if (is_array($this->value) && count($new) === count($this->value)) {
            foreach ($this->value as $k => $v) {
                if (! $new[$k]->equals($v)) {
                    $equals = false;
                    break;
                }
            }
        } else {
            $equals = false;
        }

        if (! $equals) {
            $this->value = $new;
            $this->setModified();
        }

        $this->deleted = false;

        return $this;
    }

    public function flatten(array &$flat, $prefix)
    {
        foreach ($this->value as $k => $v) {
            $v->flatten($flat, sprintf('%s[%d]', $prefix, $k));
        }
    }

    public function toConfigString($renderExpressions = false)
    {
        $parts = array();
        foreach ($this->value as $k => $v) {
            $parts[] = $v->toConfigString($renderExpressions);
        }

        return c::renderEscapedArray($parts);
    }

    public function __clone()
    {
        foreach ($this->value as $key => $value) {
            $this->value[$key] = clone($value);
        }
    }

    public function toLegacyConfigString()
    {
        return c1::renderArray($this->value);
    }
}