summaryrefslogtreecommitdiffstats
path: root/library/Director/DirectorObject/Automation/BasketSnapshotFieldResolver.php
blob: 465325550b7bd8e9d11e00058c08eeac0f18eca7 (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
<?php

namespace Icinga\Module\Director\DirectorObject\Automation;

use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\DirectorDatafield;
use Icinga\Module\Director\Objects\IcingaObject;

class BasketSnapshotFieldResolver
{
    /** @var BasketSnapshot */
    protected $snapshot;

    /** @var \Icinga\Module\Director\Data\Db\DbConnection */
    protected $targetDb;

    /** @var array|null */
    protected $requiredIds;

    protected $objects;

    /** @var int */
    protected $nextNewId = 1;

    /** @var array|null */
    protected $idMap;

    /** @var DirectorDatafield[]|null */
    protected $targetFields;

    public function __construct($objects, Db $targetDb)
    {
        $this->objects = $objects;
        $this->targetDb = $targetDb;
    }

    /**
     * @param Db $db
     * @return DirectorDatafield[]
     * @throws \Icinga\Exception\NotFoundError
     */
    public function loadCurrentFields(Db $db)
    {
        $fields = [];
        foreach ($this->getRequiredIds() as $id) {
            $fields[$id] = DirectorDatafield::loadWithAutoIncId((int) $id, $db);
        }

        return $fields;
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     * @throws \Icinga\Module\Director\Exception\DuplicateKeyException
     */
    public function storeNewFields()
    {
        $this->targetFields = null; // Clear Cache
        foreach ($this->getTargetFields() as $id => $field) {
            if ($field->hasBeenModified()) {
                $field->store();
                $this->idMap[$id] = $field->get('id');
            }
        }
    }

    /**
     * @param IcingaObject $new
     * @param $object
     * @throws \Icinga\Exception\NotFoundError
     * @throws \Zend_Db_Adapter_Exception
     */
    public function relinkObjectFields(IcingaObject $new, $object)
    {
        if (! $new->supportsFields() || ! isset($object->fields)) {
            return;
        }
        $fieldMap = $this->getIdMap();

        $objectId = (int) $new->get('id');
        $table = $new->getTableName() . '_field';
        $objectKey = $new->getShortTableName() . '_id';
        $existingFields = [];

        $db = $this->targetDb->getDbAdapter();

        foreach ($db->fetchAll(
            $db->select()->from($table)->where("$objectKey = ?", $objectId)
        ) as $mapping) {
            $existingFields[(int) $mapping->datafield_id] = $mapping;
        }
        foreach ($object->fields as $field) {
            $id = $fieldMap[(int) $field->datafield_id];
            if (isset($existingFields[$id])) {
                unset($existingFields[$id]);
            } else {
                $db->insert($table, [
                    $objectKey     => $objectId,
                    'datafield_id' => $id,
                    'is_required'  => $field->is_required,
                    'var_filter'   => $field->var_filter,
                ]);
            }
        }
        if (! empty($existingFields)) {
            $db->delete(
                $table,
                $db->quoteInto(
                    "$objectKey = $objectId AND datafield_id IN (?)",
                    array_keys($existingFields)
                )
            );
        }
    }

    /**
     * @param object $object
     * @throws \Icinga\Exception\NotFoundError
     */
    public function tweakTargetIds($object)
    {
        $forward = $this->getIdMap();
        $map = array_flip($forward);
        if (isset($object->fields)) {
            foreach ($object->fields as $field) {
                $id = $field->datafield_id;
                if (isset($map[$id])) {
                    $field->datafield_id = $map[$id];
                } else {
                    $field->datafield_id = "(NEW)";
                }
            }
        }
    }

    /**
     * @return int
     */
    protected function getNextNewId()
    {
        return $this->nextNewId++;
    }

    protected function getRequiredIds()
    {
        if ($this->requiredIds === null) {
            if (isset($this->objects['Datafield'])) {
                $this->requiredIds = array_keys($this->objects['Datafield']);
            } else {
                $ids = [];
                foreach ($this->objects as $typeName => $objects) {
                    foreach ($objects as $key => $object) {
                        if (isset($object->fields)) {
                            foreach ($object->fields as $field) {
                                $ids[$field->datafield_id] = true;
                            }
                        }
                    }
                }

                $this->requiredIds = array_keys($ids);
            }
        }

        return $this->requiredIds;
    }

    /**
     * @param $type
     * @return object[]
     */
    protected function getObjectsByType($type)
    {
        if (isset($this->objects->$type)) {
            return (array) $this->objects->$type;
        } else {
            return [];
        }
    }

    /**
     * @return DirectorDatafield[]
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function getTargetFields()
    {
        if ($this->targetFields === null) {
            $this->calculateIdMap();
        }

        return $this->targetFields;
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function getIdMap()
    {
        if ($this->idMap === null) {
            $this->calculateIdMap();
        }

        return $this->idMap;
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function calculateIdMap()
    {
        $this->idMap = [];
        $this->targetFields = [];
        foreach ($this->getObjectsByType('Datafield') as $id => $object) {
            unset($object->category_id); // Fix old baskets
            // Hint: import() doesn't store!
            $new = DirectorDatafield::import($object, $this->targetDb);
            if ($new->hasBeenLoadedFromDb()) {
                $newId = (int) $new->get('id');
            } else {
                $newId = sprintf('NEW(%s)', $this->getNextNewId());
            }
            $this->idMap[$id] = $newId;
            $this->targetFields[$id] = $new;
        }
    }
}