summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Model/CustomvarFlat.php
blob: e7a04598a37802dd97d145e0cbaf42a6258d7533 (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
<?php

/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Model;

use ipl\Orm\Behavior\Binary;
use ipl\Orm\Behaviors;
use ipl\Orm\Contract\RewriteFilterBehavior;
use ipl\Orm\Model;
use ipl\Orm\Query;
use ipl\Orm\Relations;
use ipl\Stdlib\Filter;
use ipl\Stdlib\Filter\Condition;
use Traversable;

/**
 * @property string $id
 * @property string $environment_id
 * @property string $customvar_id
 * @property string $flatname_checksum
 * @property string $flatname
 * @property ?string $flatvalue
 */
class CustomvarFlat extends Model
{
    public function getTableName()
    {
        return 'customvar_flat';
    }

    public function getKeyName()
    {
        return 'id';
    }

    public function getColumns()
    {
        return [
            'environment_id',
            'customvar_id',
            'flatname_checksum',
            'flatname',
            'flatvalue'
        ];
    }

    public function createBehaviors(Behaviors $behaviors)
    {
        $behaviors->add(new Binary([
            'id',
            'environment_id',
            'customvar_id',
            'flatname_checksum'
        ]));
        $behaviors->add(new class implements RewriteFilterBehavior {
            public function rewriteCondition(Condition $condition, $relation = null)
            {
                if ($condition->metaData()->has('requiresTransformation')) {
                    /** @var string $columnName */
                    $columnName = $condition->metaData()->get('columnName');
                    $nameFilter = Filter::like($relation . 'flatname', $columnName);
                    $class = get_class($condition);
                    $valueFilter = new $class($relation . 'flatvalue', $condition->getValue());

                    return Filter::all($nameFilter, $valueFilter);
                }
            }
        });
    }

    public function createRelations(Relations $relations)
    {
        $relations->belongsTo('environment', Environment::class);
        $relations->belongsTo('customvar', Customvar::class);

        $relations->belongsToMany('checkcommand', Checkcommand::class)
            ->through(CheckcommandCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('eventcommand', Eventcommand::class)
            ->through(EventcommandCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('host', Host::class)
            ->through(HostCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('hostgroup', Hostgroup::class)
            ->through(HostgroupCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('notification', Notification::class)
            ->through(NotificationCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('notificationcommand', Notificationcommand::class)
            ->through(NotificationcommandCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('service', Service::class)
            ->through(ServiceCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('servicegroup', Servicegroup::class)
            ->through(ServicegroupCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('timeperiod', Timeperiod::class)
            ->through(TimeperiodCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('user', User::class)
            ->through(UserCustomvar::class)
            ->setCandidateKey('customvar_id');
        $relations->belongsToMany('usergroup', Usergroup::class)
            ->through(UsergroupCustomvar::class)
            ->setCandidateKey('customvar_id');
    }

    /**
     * Restore flattened custom variables to their previous structure
     *
     * @param Traversable $flattenedVars
     *
     * @return array
     */
    public function unFlattenVars(Traversable $flattenedVars): array
    {
        $registerValue = function (&$data, $source, $path, $value) use (&$registerValue) {
            $step = array_shift($path);

            $isIndex = (bool) preg_match('/^\[(\d+)]$/', $step, $m);
            if ($isIndex) {
                $step = $m[1];
            }

            if ($source !== null) {
                while (! isset($source[$step])) {
                    if ($isIndex) {
                        $step = sprintf('[%d]', $step);
                        $isIndex = false;
                    } else {
                        if (empty($path)) {
                            break;
                        }

                        $step = implode('.', [$step, array_shift($path)]);
                    }
                }
            }

            if (! empty($path)) {
                if (! isset($data[$step])) {
                    $data[$step] = [];
                }

                $registerValue($data[$step], $source[$step] ?? null, $path, $value);
            } else {
                // Since empty custom vars of type dictionaries and arrays have null values in customvar_flat table,
                // we won't be able to render them as such. Therefore, we have to use the value of the `customvar`
                // table if it's not null, otherwise the current value, which is a "null" string.
                $data[$step] = $value === null && ($source[$step] ?? null) === [] ? $source[$step] : $value;
            }
        };

        if ($flattenedVars instanceof Query) {
            $flattenedVars->withColumns(['customvar.name', 'customvar.value']);
        }

        $vars = [];
        foreach ($flattenedVars as $var) {
            if (isset($var->customvar->name)) {
                $var->customvar->value = json_decode($var->customvar->value, true);

                $realName = $var->customvar->name;
                $source = [$realName => $var->customvar->value];

                $sourcePath = ltrim(substr($var->flatname, strlen($realName)), '.');
                $path = array_merge(
                    [$realName],
                    $sourcePath
                        ? preg_split('/(?<=\w|])\.|(?<!^|\.)(?=\[)/', $sourcePath)
                        : []
                );
            } else {
                $path = explode('.', $var->flatname);
                $source = null;
            }

            $registerValue($vars, $source, $path, $var->flatvalue);

            if (isset($var->customvar->name)) {
                $var->customvar->name = null;
                $var->customvar->value = null;
            }
        }

        return $vars;
    }
}