Passed
Push — master ( e75fe1...ca8983 )
by Andreas
17:50
created

midcom_helper_reflector_tree::get_link_field()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 22
c 2
b 0
f 0
nc 5
nop 2
dl 0
loc 35
ccs 22
cts 22
cp 1
crap 7
rs 8.6346
1
<?php
2
/**
3
 * @package midcom.helper.reflector
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * The Grand Unified Reflector, Tree information
11
 *
12
 * @package midcom.helper.reflector
13
 */
14
class midcom_helper_reflector_tree extends midcom_helper_reflector
15
{
16
    /**
17
     * Creates a QB instance for root objects
18
     */
19 5
    public function _root_objects_qb()
20
    {
21 5
        $schema_type = $this->mgdschema_class;
22
23 5
        $qb = $this->_get_type_qb($schema_type, false);
24 5
        if (!$qb) {
25
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
26
            return false;
27
        }
28
29
        // Figure out constraint to use to get root level objects
30 5
        if ($upfield = midgard_object_class::get_property_up($schema_type)) {
31 5
            $uptype = $this->_mgd_reflector->get_midgard_type($upfield);
32 5
            switch ($uptype) {
33
                case MGD_TYPE_STRING:
34
                case MGD_TYPE_GUID:
35
                    $qb->add_constraint($upfield, '=', '');
36
                    break;
37
                case MGD_TYPE_INT:
38
                case MGD_TYPE_UINT:
39 5
                    $qb->add_constraint($upfield, '=', 0);
40 5
                    break;
41
                default:
42
                    debug_add("Do not know how to handle upfield '{$upfield}' has type {$uptype}", MIDCOM_LOG_ERROR);
43
                    return false;
44
            }
45
        }
46 5
        return $qb;
47
    }
48
49
    /**
50
     * Get rendered path for object
51
     *
52
     * @param midgard\portable\api\mgdobject $object The object to get path for
53
     * @param string $separator the string used to separate path components
54
     */
55 1
    public static function resolve_path($object, string $separator = ' &gt; ') : string
56
    {
57 1
        $parts = self::resolve_path_parts($object);
58 1
        return implode($separator, array_column($parts, 'label'));
59
    }
60
61
    /**
62
     * Get path components for object
63
     *
64
     * @param midgard\portable\api\mgdobject $object The object to get path for
65
     */
66 3
    public static function resolve_path_parts($object) : array
67
    {
68 3
        static $cache = [];
69 3
        if (isset($cache[$object->guid])) {
70 1
            return $cache[$object->guid];
71
        }
72
73 2
        $ret = [];
74 2
        $ret[] = [
75 2
            'object' => $object,
76 2
            'label' => parent::get($object)->get_object_label($object),
77
        ];
78
79 2
        $parent = $object->get_parent();
80 2
        while (is_object($parent)) {
81 1
            $ret[] = [
82 1
                'object' => $parent,
83 1
                'label' => parent::get($parent)->get_object_label($parent),
84
            ];
85 1
            $parent = $parent->get_parent();
86
        }
87
88 2
        $cache[$object->guid] = array_reverse($ret);
89 2
        return $cache[$object->guid];
90
    }
91
92 21
    private static function _check_permissions(bool $deleted) : bool
93
    {
94
        // PONDER: Check for some generic user privilege instead  ??
95 21
        if (   $deleted
96 21
            && !midcom_connection::is_admin()
97 21
            && !midcom::get()->auth->is_component_sudo()) {
98
            debug_add('Non-admins are not allowed to list deleted objects', MIDCOM_LOG_ERROR);
99
            return false;
100
        }
101 21
        return true;
102
    }
103
104
    /**
105
     * Get direct children of given object
106
     *
107
     * @param midgard\portable\api\mgdobject $object object to get children for
108
     * @param boolean $deleted whether to get (only) deleted or not-deleted objects
109
     * @return array multidimensional array (keyed by classname) of objects
110
     */
111 21
    public static function get_child_objects(object $object, bool $deleted = false) : array
112
    {
113 21
        if (!self::_check_permissions($deleted)) {
114
            return [];
115
        }
116 21
        $resolver = new self($object);
117
118 21
        $child_objects = [];
119 21
        foreach ($resolver->get_child_classes() as $schema_type) {
120 21
            $qb = $resolver->_child_objects_type_qb($schema_type, $object, $deleted);
121 21
            if (!$qb) {
122
                debug_add('Could not get QB instance', MIDCOM_LOG_ERROR);
123
                continue;
124
            }
125
126
            // Sort by title and name if available
127 21
            self::add_schema_sorts_to_qb($qb, $schema_type);
128
129 21
            if ($type_children = $qb->execute()) {
130 1
                $child_objects[$schema_type] = $type_children;
131
            }
132
        }
133 21
        return $child_objects;
134
    }
135
136 106
    private function _get_type_qb(string $schema_type, bool $deleted)
137
    {
138 106
        if (empty($schema_type)) {
139
            debug_add('Passed schema_type argument is empty, this is fatal', MIDCOM_LOG_ERROR);
140
            return false;
141
        }
142 106
        if ($deleted) {
143
            $qb = new midgard_query_builder($schema_type);
144
            $qb->include_deleted();
145
            $qb->add_constraint('metadata.deleted', '<>', 0);
146
            return $qb;
147
        }
148
        // Figure correct MidCOM DBA class to use and get midcom QB
149 106
        $midcom_dba_classname = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type);
150 106
        if (empty($midcom_dba_classname)) {
151
            debug_add("MidCOM DBA does not know how to handle {$schema_type}", MIDCOM_LOG_ERROR);
152
            return false;
153
        }
154
155 106
        return $midcom_dba_classname::new_query_builder();
156
    }
157
158
    /**
159
     * Figure out if $schema_type can be a child of $target_class
160
     */
161 104
    private function get_link_field(string $schema_type, string $target_class) : ?array
162
    {
163 104
        static $cache = [];
164 104
        $cache_key = $schema_type . '-' . $target_class;
165 104
        if (!array_key_exists($cache_key, $cache)) {
166 6
            $cache[$cache_key] = null;
167 6
            $ref = new midgard_reflection_property($schema_type);
168
169 6
            $candidates = array_filter([
170 6
                'up' => midgard_object_class::get_property_up($schema_type),
171 6
                'parent' => midgard_object_class::get_property_parent($schema_type)
172
            ]);
173
174 6
            foreach ($candidates as $type => $field) {
175
                $info = [
176 6
                    'type' => $type,
177 6
                    'name' => $field,
178 6
                    'target' => $ref->get_link_target($field),
179 6
                    'upfield' => $candidates['up'] ?? null
180
                ];
181
182 6
                if ($linked_class = $ref->get_link_name($field)) {
183 5
                    if (!self::is_same_class($linked_class, $target_class)) {
184
                        // This link points elsewhere
185 5
                        continue;
186
                    }
187 6
                } elseif ($ref->get_midgard_type($field) === MGD_TYPE_GUID && empty($info['target'])) {
188
                    // Guid link without class specification, valid for all classes
189 6
                    $info['target'] = 'guid';
190
                }
191 6
                $cache[$cache_key] = $info;
192 6
                break;
193
            }
194
        }
195 104
        return $cache[$cache_key];
196
    }
197
198
    /**
199
     * Creates a QB instance for get_child_objects
200
     */
201 104
    public function _child_objects_type_qb(string $schema_type, object $for_object, bool $deleted)
202
    {
203 104
        $qb = $this->_get_type_qb($schema_type, $deleted);
204 104
        if (!$qb) {
205
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
206
            return false;
207
        }
208
209 104
        if ($info = $this->get_link_field($schema_type, get_class($for_object))) {
210 104
            if ($info['type'] == 'parent' && $info['upfield']) {
211
                // we only return direct children (otherwise they would turn up twice in recursive queries)
212 95
                $qb->begin_group('AND');
213 95
                    $qb->add_constraint($info['name'], '=', $for_object->{$info['target']});
214 95
                    $qb->add_constraint($info['upfield'], '=', 0);
215 95
                $qb->end_group();
216
            } else {
217 104
                $qb->add_constraint($info['name'], '=', $for_object->{$info['target']});
218
            }
219 104
            return $qb;
220
        }
221
222
        debug_add("Class '{$schema_type}' has no valid link properties pointing to class '" . get_class($for_object) . "', this should not happen here", MIDCOM_LOG_ERROR);
223
        return false;
224
    }
225
226
    /**
227
     * Get the parent class of the class this reflector was instantiated for
228
     */
229 2
    public function get_parent_class() : ?string
230
    {
231 2
        $parent_property = midgard_object_class::get_property_parent($this->mgdschema_class);
232 2
        if (!$parent_property) {
233 2
            return null;
234
        }
235
        $ref = new midgard_reflection_property($this->mgdschema_class);
236
        return $ref->get_link_name($parent_property);
237
    }
238
239
    /**
240
     * Get the child classes of the class this reflector was instantiated for
241
     */
242 105
    public function get_child_classes() : array
243
    {
244 105
        static $cache = [];
245 105
        if (!isset($cache[$this->mgdschema_class])) {
246 4
            $cache[$this->mgdschema_class] = [];
247
248 4
            $types = array_diff(midcom_connection::get_schema_types(), $this->_config->get_array('child_class_exceptions_neverchild'));
249 4
            foreach ($types as $schema_type) {
250 4
                if ($this->get_link_field($schema_type, $this->mgdschema_class)) {
251 4
                    $cache[$this->mgdschema_class][] = $schema_type;
252
                }
253
            }
254
255
            //make sure children of the same type come out on top
256 4
            if ($key = array_search($this->mgdschema_class, $cache[$this->mgdschema_class])) {
257 2
                unset($cache[$this->mgdschema_class][$key]);
258 2
                array_unshift($cache[$this->mgdschema_class], $this->mgdschema_class);
259
            }
260
        }
261 105
        return $cache[$this->mgdschema_class];
262
    }
263
264
    /**
265
     * Get an array of "root level" classes
266
     */
267 12
    public static function get_root_classes() : array
268
    {
269 12
        static $root_classes = false;
270 12
        if (empty($root_classes)) {
271
            $root_classes = self::_resolve_root_classes();
272
        }
273 12
        return $root_classes;
274
    }
275
276
    /**
277
     * Resolves the "root level" DBA classes, used by get_root_classes()
278
     */
279
    private static function _resolve_root_classes() : array
280
    {
281
        $root_exceptions_notroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get_array('root_class_exceptions_notroot');
282
        $root_classes = [];
283
        $types = array_diff(midcom_connection::get_schema_types(), $root_exceptions_notroot);
284
        foreach ($types as $schema_type) {
285
            // Class extensions mapping
286
            $schema_type = self::class_rewrite($schema_type);
287
288
            // Make sure we only add classes once
289
            if (in_array($schema_type, $root_classes)) {
290
                // Already listed
291
                continue;
292
            }
293
294
            if (midgard_object_class::get_property_parent($schema_type)) {
295
                // type has parent set, thus cannot be root type
296
                continue;
297
            }
298
299
            if (!midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type)) {
300
                // Not a MidCOM DBA object, skip
301
                continue;
302
            }
303
304
            $root_classes[] = $schema_type;
305
        }
306
307
        usort($root_classes, 'strnatcmp');
308
        return $root_classes;
309
    }
310
311
    /**
312
     * Add default ("title" and "name") sorts to a QB instance
313
     *
314
     * @param midgard_query_builder $qb QB instance
315
     */
316 21
    public static function add_schema_sorts_to_qb($qb, string $schema_type)
317
    {
318
        // Sort by "title" and "name" if available
319 21
        $dummy = new $schema_type();
320 21
        if ($title_property = self::get_title_property($dummy)) {
321 21
            $qb->add_order($title_property);
322
        }
323 21
        if ($name_property = self::get_name_property($dummy)) {
324 16
            $qb->add_order($name_property);
325
        }
326 21
    }
327
328
    /**
329
     * List object children
330
     */
331
    public static function get_tree(midcom_core_dbaobject $parent) : array
332
    {
333
        $tree = [];
334
335
        foreach (self::get_child_objects($parent) as $class => $objects) {
336
            $reflector = parent::get($class);
337
338
            foreach ($objects as $object) {
339
                $leaf = [
340
                    'title' => $reflector->get_object_label($object),
341
                    'icon' => $reflector->get_object_icon($object),
342
                    'class' => $class
343
                ];
344
                if ($grandchildren = self::get_tree($object)) {
345
                    $leaf['children'] = $grandchildren;
346
                }
347
                $tree[] = $leaf;
348
            }
349
        }
350
        return $tree;
351
    }
352
}
353