Completed
Branch master (c1061b)
by Andreas
20:29
created

midcom_helper_reflector_tree::get_child_objects()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 16
ccs 9
cts 10
cp 0.9
crap 4.016
rs 9.9666
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 6
    public function _root_objects_qb($deleted)
20
    {
21 6
        $schema_type = $this->mgdschema_class;
22 6
        $root_classes = self::get_root_classes();
23 6
        if (!in_array($schema_type, $root_classes)) {
24
            debug_add("Type {$schema_type} is not a \"root\" type", MIDCOM_LOG_ERROR);
25
            return false;
26
        }
27
28 6
        $qb = $this->_get_type_qb($schema_type, $deleted);
0 ignored issues
show
Bug introduced by
It seems like $schema_type can also be of type null; however, parameter $schema_type of midcom_helper_reflector_tree::_get_type_qb() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

28
        $qb = $this->_get_type_qb(/** @scrutinizer ignore-type */ $schema_type, $deleted);
Loading history...
29 6
        if (!$qb) {
30
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
31
            return false;
32
        }
33
34
        // Figure out constraint to use to get root level objects
35 6
        $upfield = midgard_object_class::get_property_up($schema_type);
36 6
        if (!empty($upfield)) {
37 6
            $uptype = $this->_mgd_reflector->get_midgard_type($upfield);
38 6
            switch ($uptype) {
39
                case MGD_TYPE_STRING:
40
                case MGD_TYPE_GUID:
41
                    $qb->add_constraint($upfield, '=', '');
42
                    break;
43
                case MGD_TYPE_INT:
44
                case MGD_TYPE_UINT:
45 6
                    $qb->add_constraint($upfield, '=', 0);
46 6
                    break;
47
                default:
48
                    debug_add("Do not know how to handle upfield '{$upfield}' has type {$uptype}", MIDCOM_LOG_ERROR);
49
                    return false;
50
            }
51
        }
52 6
        return $qb;
53
    }
54
55
    /**
56
     * Get rendered path for object
57
     *
58
     * @param midgard\portable\api\mgdobject $object The object to get path for
59
     * @param string $separator the string used to separate path components
60
     */
61 1
    public static function resolve_path($object, $separator = ' &gt; ') : string
62
    {
63 1
        $parts = self::resolve_path_parts($object);
64 1
        return implode($separator, array_column($parts, 'label'));
65
    }
66
67
    /**
68
     * Get path components for object
69
     *
70
     * @param midgard\portable\api\mgdobject $object The object to get path for
71
     */
72 3
    public static function resolve_path_parts($object) : array
73
    {
74 3
        static $cache = [];
75 3
        if (isset($cache[$object->guid])) {
76 1
            return $cache[$object->guid];
77
        }
78
79 2
        $ret = [];
80 2
        $ret[] = [
81 2
            'object' => $object,
82 2
            'label' => parent::get($object)->get_object_label($object),
83
        ];
84
85 2
        $parent = $object->get_parent();
86 2
        while (is_object($parent)) {
87 1
            $ret[] = [
88 1
                'object' => $parent,
89 1
                'label' => parent::get($parent)->get_object_label($parent),
90
            ];
91 1
            $parent = $parent->get_parent();
92
        }
93
94 2
        $cache[$object->guid] = array_reverse($ret);
95 2
        return $cache[$object->guid];
96
    }
97
98 20
    private static function _check_permissions(bool $deleted) : bool
99
    {
100
        // PONDER: Check for some generic user privilege instead  ??
101 20
        if (   $deleted
102 20
            && !midcom_connection::is_admin()
103 20
            && !midcom::get()->auth->is_component_sudo()) {
104
            debug_add('Non-admins are not allowed to list deleted objects', MIDCOM_LOG_ERROR);
105
            return false;
106
        }
107 20
        return true;
108
    }
109
110
    /**
111
     * Get children of given object
112
     *
113
     * @param midgard\portable\api\mgdobject $object object to get children for
114
     * @param boolean $deleted whether to get (only) deleted or not-deleted objects
115
     * @return array multidimensional array (keyed by classname) of objects or false on failure
116
     */
117 20
    public static function get_child_objects($object, $deleted = false)
118
    {
119 20
        if (!self::_check_permissions($deleted)) {
120
            return false;
121
        }
122 20
        $resolver = new self($object);
123
124 20
        $child_objects = [];
125 20
        foreach ($resolver->get_child_classes() as $schema_type) {
126 20
            $type_children = $resolver->_get_child_objects_type($schema_type, $object, $deleted);
127
            // PONDER: check for boolean false as result ??
128 20
            if (!empty($type_children)) {
129 1
                $child_objects[$schema_type] = $type_children;
130
            }
131
        }
132 20
        return $child_objects;
133
    }
134
135 96
    private function _get_type_qb(string $schema_type, bool $deleted)
136
    {
137 96
        if (empty($schema_type)) {
138
            debug_add('Passed schema_type argument is empty, this is fatal', MIDCOM_LOG_ERROR);
139
            return false;
140
        }
141 96
        if ($deleted) {
142
            $qb = new midgard_query_builder($schema_type);
143
            $qb->include_deleted();
144
            $qb->add_constraint('metadata.deleted', '<>', 0);
145
            return $qb;
146
        }
147
        // Figure correct MidCOM DBA class to use and get midcom QB
148 96
        $midcom_dba_classname = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type);
149 96
        if (empty($midcom_dba_classname)) {
150
            debug_add("MidCOM DBA does not know how to handle {$schema_type}", MIDCOM_LOG_ERROR);
151
            return false;
152
        }
153
154 96
        return call_user_func([$midcom_dba_classname, 'new_query_builder']);
155
    }
156
157
    /**
158
     * Figure out constraint(s) to use to get child objects
159
     */
160 94
    private function _get_link_fields(string $schema_type, $for_object) : array
161
    {
162 94
        static $cache = [];
163 94
        $cache_key = $schema_type . '-' . get_class($for_object);
164 94
        if (empty($cache[$cache_key])) {
165 7
            $ref = new midgard_reflection_property($schema_type);
166
167
            $linkfields = [
168 7
                'up' => midgard_object_class::get_property_up($schema_type),
169 7
                'parent' => midgard_object_class::get_property_parent($schema_type)
170
            ];
171 7
            $linkfields = array_filter($linkfields);
172 7
            $data = [];
173 7
            foreach ($linkfields as $link_type => $field) {
174
                $info = [
175 7
                    'name' => $field,
176 7
                    'type' => $ref->get_midgard_type($field),
177 7
                    'target' => $ref->get_link_target($field)
178
                ];
179 7
                $linked_class = $ref->get_link_name($field);
180 7
                if (   empty($linked_class)
181 7
                    && $info['type'] === MGD_TYPE_GUID) {
182
                    // Guid link without class specification, valid for all classes
183 7
                    if (empty($info['target'])) {
184 7
                        $info['target'] = 'guid';
185
                    }
186 5
                } elseif (!self::is_same_class($linked_class, get_class($for_object))) {
187
                    // This link points elsewhere
188 2
                    continue;
189
                }
190 7
                $data[$link_type] = $info;
191
            }
192 7
            $cache[$cache_key] = $data;
193
        }
194 94
        return $cache[$cache_key];
195
    }
196
197
    /**
198
     * Creates a QB instance for _get_child_objects_type
199
     */
200 94
    public function _child_objects_type_qb($schema_type, $for_object, $deleted)
201
    {
202 94
        if (!is_object($for_object)) {
203
            debug_add('Passed for_object argument is not object, this is fatal', MIDCOM_LOG_ERROR);
204
            return false;
205
        }
206 94
        $qb = $this->_get_type_qb($schema_type, $deleted);
207 94
        if (!$qb) {
208
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
209
            return false;
210
        }
211
212 94
        $linkfields = $this->_get_link_fields($schema_type, $for_object);
213
214 94
        if (empty($linkfields)) {
215
            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);
216
            return false;
217
        }
218
219 94
        $multiple_links = false;
220 94
        if (count($linkfields) > 1) {
221
            $multiple_links = true;
222
            $qb->begin_group('OR');
223
        }
224
225 94
        foreach ($linkfields as $link_type => $field_data) {
226 94
            $field_target = $field_data['target'];
227 94
            $field_type = $field_data['type'];
228 94
            $field = $field_data['name'];
229
230 94
            if (   !$field_target
231 94
                || !isset($for_object->$field_target)) {
232
                // Why return false ???
233
                return false;
234
            }
235 94
            switch ($field_type) {
236
                case MGD_TYPE_STRING:
237
                case MGD_TYPE_GUID:
238 94
                    $qb->add_constraint($field, '=', (string) $for_object->$field_target);
239 94
                    break;
240
                case MGD_TYPE_INT:
241
                case MGD_TYPE_UINT:
242 91
                    if ($link_type == 'up') {
243 91
                        $qb->add_constraint($field, '=', (int) $for_object->$field_target);
244 85
                    } elseif ($link_type == 'parent') {
245 85
                        $up_property = midgard_object_class::get_property_up($schema_type);
246 85
                        if (!empty($up_property)) {
247
                            //we only return direct children (otherwise they would turn up twice in recursive queries)
248 85
                            $qb->begin_group('AND');
249 85
                            $qb->add_constraint($field, '=', (int) $for_object->$field_target);
250 85
                            $qb->add_constraint($up_property, '=', 0);
251 85
                            $qb->end_group();
252
                        } else {
253 85
                            $qb->add_constraint($field, '=', (int) $for_object->$field_target);
254
                        }
255
                    } else {
256
                        $qb->begin_group('AND');
257
                        $qb->add_constraint($field, '=', (int) $for_object->$field_target);
258
                        // make sure we don't accidentally find other objects with the same id
259
                        $qb->add_constraint($field . '.guid', '=', (string) $for_object->guid);
260
                        $qb->end_group();
261
                    }
262 91
                    break;
263
                default:
264
                    debug_add("Do not know how to handle linked field '{$field}', has type {$field_type}", MIDCOM_LOG_INFO);
265
266
                    // Why return false ???
267
                    return false;
268
            }
269
        }
270
271 94
        if ($multiple_links) {
272
            $qb->end_group();
273
        }
274
275 94
        return $qb;
276
    }
277
278
    /**
279
     * Used by get_child_objects
280
     *
281
     * @return array of objects
282
     */
283 20
    public function _get_child_objects_type($schema_type, $for_object, $deleted)
284
    {
285 20
        $qb = $this->_child_objects_type_qb($schema_type, $for_object, $deleted);
286 20
        if (!$qb) {
287
            debug_add('Could not get QB instance', MIDCOM_LOG_ERROR);
288
            return false;
289
        }
290
291
        // Sort by title and name if available
292 20
        self::add_schema_sorts_to_qb($qb, $schema_type);
293
294 20
        return $qb->execute();
295
    }
296
297
    /**
298
     * Get the parent class of the class this reflector was instantiated for
299
     *
300
     * @return string class name (or false if the type has no parent)
301
     */
302 2
    public function get_parent_class()
303
    {
304 2
        $parent_property = midgard_object_class::get_property_parent($this->mgdschema_class);
305 2
        if (!$parent_property) {
306 2
            return false;
307
        }
308
        $ref = new midgard_reflection_property($this->mgdschema_class);
309
        return $ref->get_link_name($parent_property);
310
    }
311
312
    /**
313
     * Get the child classes of the class this reflector was instantiated for
314
     */
315 95
    public function get_child_classes() : array
316
    {
317 95
        static $child_classes_all = [];
318 95
        if (!isset($child_classes_all[$this->mgdschema_class])) {
319 5
            $child_classes_all[$this->mgdschema_class] = $this->_resolve_child_classes();
320
        }
321 95
        return $child_classes_all[$this->mgdschema_class];
322
    }
323
324
    /**
325
     * Resolve the child classes of the class this reflector was instantiated for, used by get_child_classes()
326
     */
327 5
    private function _resolve_child_classes() : array
328
    {
329 5
        $child_class_exceptions_neverchild = $this->_config->get('child_class_exceptions_neverchild');
330
331
        // Safety against misconfiguration
332 5
        if (!is_array($child_class_exceptions_neverchild)) {
333
            debug_add("config->get('child_class_exceptions_neverchild') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
334
            $child_class_exceptions_neverchild = [];
335
        }
336 5
        $child_classes = [];
337 5
        $types = array_diff(midcom_connection::get_schema_types(), $child_class_exceptions_neverchild);
338 5
        foreach ($types as $schema_type) {
339 5
            $parent_property = midgard_object_class::get_property_parent($schema_type);
340 5
            $up_property = midgard_object_class::get_property_up($schema_type);
341
342 5
            if (   $this->is_link_to_current_class($parent_property, $schema_type)
343 5
                || $this->is_link_to_current_class($up_property, $schema_type)) {
344 5
                $child_classes[] = $schema_type;
345
            }
346
        }
347
348
        //make sure children of the same type come out on top
349 5
        if ($key = array_search($this->mgdschema_class, $child_classes)) {
350
            unset($child_classes[$key]);
351
            array_unshift($child_classes, $this->mgdschema_class);
352
        }
353 5
        return $child_classes;
354
    }
355
356 5
    private function is_link_to_current_class($property, string $prospect_type) : bool
357
    {
358 5
        if (empty($property)) {
359 5
            return false;
360
        }
361
362 5
        $ref = new midgard_reflection_property($prospect_type);
363 5
        $link_class = $ref->get_link_name($property);
364 5
        if (   empty($link_class)
365 5
            && $ref->get_midgard_type($property) === MGD_TYPE_GUID) {
366 5
            return true;
367
        }
368 5
        return self::is_same_class($link_class, $this->mgdschema_class);
369
    }
370
371
    /**
372
     * Get an array of "root level" classes
373
     */
374 13
    public static function get_root_classes() : array
375
    {
376 13
        static $root_classes = false;
377 13
        if (empty($root_classes)) {
378 1
            $root_classes = self::_resolve_root_classes();
379
        }
380 13
        return $root_classes;
381
    }
382
383
    /**
384
     * Resolves the "root level" classes, used by get_root_classes()
385
     */
386 1
    private static function _resolve_root_classes() : array
387
    {
388 1
        $root_exceptions_notroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get('root_class_exceptions_notroot');
389
        // Safety against misconfiguration
390 1
        if (!is_array($root_exceptions_notroot)) {
391
            debug_add("config->get('root_class_exceptions_notroot') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
392
            $root_exceptions_notroot = [];
393
        }
394 1
        $root_classes = [];
395 1
        $types = array_diff(midcom_connection::get_schema_types(), $root_exceptions_notroot);
396 1
        foreach ($types as $schema_type) {
397
            // Class extensions mapping
398 1
            $schema_type = self::class_rewrite($schema_type);
399
400
            // Make sure we only add classes once
401 1
            if (in_array($schema_type, $root_classes)) {
402
                // Already listed
403
                continue;
404
            }
405
406 1
            if (midgard_object_class::get_property_parent($schema_type)) {
407
                // type has parent set, thus cannot be root type
408 1
                continue;
409
            }
410
411 1
            if (!midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type)) {
412
                // Not a MidCOM DBA object, skip
413
                continue;
414
            }
415
416 1
            $root_classes[] = $schema_type;
417
        }
418
419 1
        $root_exceptions_forceroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get('root_class_exceptions_forceroot');
420
        // Safety against misconfiguration
421 1
        if (!is_array($root_exceptions_forceroot)) {
422
            debug_add("config->get('root_class_exceptions_forceroot') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
423
            $root_exceptions_forceroot = [];
424
        }
425 1
        $root_exceptions_forceroot = array_diff($root_exceptions_forceroot, $root_classes);
426 1
        foreach ($root_exceptions_forceroot as $schema_type) {
427
            if (!class_exists($schema_type)) {
428
                // Not a valid class
429
                debug_add("Type {$schema_type} has been listed to always be root class, but the class does not exist", MIDCOM_LOG_WARN);
430
                continue;
431
            }
432
            $root_classes[] = $schema_type;
433
        }
434
435 1
        usort($root_classes, 'strnatcmp');
436 1
        return $root_classes;
437
    }
438
439
    /**
440
     * Add default ("title" and "name") sorts to a QB instance
441
     *
442
     * @param midgard_query_builder $qb QB instance
443
     * @param string $schema_type valid mgdschema class name
444
     */
445 20
    public static function add_schema_sorts_to_qb($qb, $schema_type)
446
    {
447
        // Sort by "title" and "name" if available
448 20
        $ref = self::get($schema_type);
449 20
        $dummy = new $schema_type();
450 20
        if ($title_property = $ref->get_title_property($dummy)) {
451 20
            $qb->add_order($title_property);
452
        }
453 20
        if ($name_property = $ref->get_name_property($dummy)) {
454 15
            $qb->add_order($name_property);
455
        }
456 20
    }
457
458
    /**
459
     * List object children
460
     *
461
     * @param midcom_core_dbaobject $parent
462
     */
463
    public static function get_tree(midcom_core_dbaobject $parent) : array
464
    {
465
        static $shown_guids = [];
466
        $tree = [];
467
        try {
468
            $children = self::get_child_objects($parent);
0 ignored issues
show
Bug introduced by
$parent of type midcom_core_dbaobject is incompatible with the type midgard\portable\api\mgdobject expected by parameter $object of midcom_helper_reflector_tree::get_child_objects(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

468
            $children = self::get_child_objects(/** @scrutinizer ignore-type */ $parent);
Loading history...
469
        } catch (midcom_error $e) {
470
            return $tree;
471
        }
472
473
        foreach ($children as $class => $objects) {
474
            $reflector = parent::get($class);
475
476
            foreach ($objects as $object) {
477
                if (array_key_exists($object->guid, $shown_guids)) {
478
                    //we might see objects twice if they have both up and parent
479
                    continue;
480
                }
481
                $shown_guids[$object->guid] = true;
482
483
                $leaf = [
484
                    'title' => $reflector->get_object_label($object),
485
                    'icon' => $reflector->get_object_icon($object),
486
                    'class' => $class
487
                ];
488
                $grandchildren = self::get_tree($object);
489
                if (!empty($grandchildren)) {
490
                    $leaf['children'] = $grandchildren;
491
                }
492
                $tree[] = $leaf;
493
            }
494
        }
495
        return $tree;
496
    }
497
}
498