Completed
Push — master ( c3e146...876d54 )
by Andreas
20:21
created

midcom_helper_reflector_tree::resolve_path_parts()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 1
dl 0
loc 24
ccs 16
cts 16
cp 1
crap 3
rs 9.7666
c 0
b 0
f 0
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 get_root_objects
18
     */
19 5
    public function _root_objects_qb($deleted)
20
    {
21 5
        $schema_type = $this->mgdschema_class;
22 5
        $root_classes = self::get_root_classes();
23 5
        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 5
        $qb = $this->_get_type_qb($schema_type, $deleted);
29 5
        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 5
        $upfield = midgard_object_class::get_property_up($schema_type);
36 5
        if (!empty($upfield)) {
37 5
            $uptype = $this->_mgd_reflector->get_midgard_type($upfield);
38 5
            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 5
                    $qb->add_constraint($upfield, '=', 0);
46 5
                    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 5
        return $qb;
53
    }
54
55
    /**
56
     * Get "root" objects for the class this reflector was instantiated for
57
     *
58
     * NOTE: deleted objects can only be listed as admin, also: they do not come
59
     * MidCOM DBA wrapped (since you cannot normally instantiate such object)
60
     *
61
     * @param boolean $deleted whether to get (only) deleted or not-deleted objects
62
     * @return array of objects or false on failure
63
     */
64
    public function get_root_objects($deleted = false)
65
    {
66
        if (!self::_check_permissions($deleted)) {
67
            return false;
68
        }
69
70
        $qb = $this->_root_objects_qb($deleted);
71
        if (!$qb) {
72
            debug_add('Could not get QB instance', MIDCOM_LOG_ERROR);
73
            return false;
74
        }
75
        self::add_schema_sorts_to_qb($qb, $this->mgdschema_class);
76
77
        return $qb->execute();
78
    }
79
80
    /**
81
     * Get rendered path for object
82
     *
83
     * @param midgard\portable\api\mgdobject $object The object to get path for
84
     * @param string $separator the string used to separate path components
85
     */
86 1
    public static function resolve_path($object, $separator = ' &gt; ') : string
87
    {
88 1
        $parts = self::resolve_path_parts($object);
89 1
        return implode($separator, array_column($parts, 'label'));
90
    }
91
92
    /**
93
     * Get path components for object
94
     *
95
     * @param midgard\portable\api\mgdobject $object The object to get path for
96
     */
97 3
    public static function resolve_path_parts($object) : array
98
    {
99 3
        static $cache = [];
100 3
        if (isset($cache[$object->guid])) {
101 1
            return $cache[$object->guid];
102
        }
103
104 2
        $ret = [];
105 2
        $ret[] = [
106 2
            'object' => $object,
107 2
            'label' => parent::get($object)->get_object_label($object),
108
        ];
109
110 2
        $parent = self::get_parent($object);
111 2
        while (is_object($parent)) {
112 1
            $ret[] = [
113 1
                'object' => $parent,
114 1
                'label' => parent::get($parent)->get_object_label($parent),
115
            ];
116 1
            $parent = self::get_parent($parent);
117
        }
118
119 2
        $cache[$object->guid] = array_reverse($ret);
120 2
        return $cache[$object->guid];
121
    }
122
123
    /**
124
     * Get the parent object of given object
125
     *
126
     * Tries to utilize MidCOM DBA features first but can fallback on pure MgdSchema
127
     * as necessary
128
     *
129
     * NOTE: since this might fall back to pure MgdSchema never trust that MidCOM DBA features
130
     * are available, check for is_callable/method_exists first !
131
     *
132
     * @param midgard\portable\api\mgdobject $object the object to get parent for
133
     */
134 91
    public static function get_parent($object)
135
    {
136 91
        if (method_exists($object, 'get_parent')) {
137
            /**
138
             * The object might have valid reasons for returning empty value here, but we can't know if it's
139
             * because it's valid or because the get_parent* methods have not been overridden in the actually
140
             * used class
141
             */
142 91
            return $object->get_parent();
143
        }
144
145
        return false;
146
    }
147
148 20
    private static function _check_permissions(bool $deleted) : bool
149
    {
150
        // PONDER: Check for some generic user privilege instead  ??
151 20
        if (   $deleted
152 20
            && !midcom_connection::is_admin()
153 20
            && !midcom::get()->auth->is_component_sudo()) {
154
            debug_add('Non-admins are not allowed to list deleted objects', MIDCOM_LOG_ERROR);
155
            return false;
156
        }
157 20
        return true;
158
    }
159
160
    /**
161
     * Get children of given object
162
     *
163
     * @param midgard\portable\api\mgdobject $object object to get children for
164
     * @param boolean $deleted whether to get (only) deleted or not-deleted objects
165
     * @return array multidimensional array (keyed by classname) of objects or false on failure
166
     */
167 20
    public static function get_child_objects($object, $deleted = false)
168
    {
169 20
        if (!self::_check_permissions($deleted)) {
170
            return false;
171
        }
172 20
        $resolver = new self($object);
173 20
        $child_classes = $resolver->get_child_classes();
174 20
        if (!$child_classes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $child_classes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
175
            return false;
176
        }
177
178 20
        $child_objects = [];
179 20
        foreach ($child_classes as $schema_type) {
180 20
            $type_children = $resolver->_get_child_objects_type($schema_type, $object, $deleted);
181
            // PONDER: check for boolean false as result ??
182 20
            if (empty($type_children)) {
183 20
                continue;
184
            }
185 1
            $child_objects[$schema_type] = $type_children;
186
        }
187 20
        return $child_objects;
188
    }
189
190 97
    private function _get_type_qb(string $schema_type, bool $deleted)
191
    {
192 97
        if (empty($schema_type)) {
193
            debug_add('Passed schema_type argument is empty, this is fatal', MIDCOM_LOG_ERROR);
194
            return false;
195
        }
196 97
        if ($deleted) {
197
            $qb = new midgard_query_builder($schema_type);
198
            $qb->include_deleted();
199
            $qb->add_constraint('metadata.deleted', '<>', 0);
200
            return $qb;
201
        }
202
        // Figure correct MidCOM DBA class to use and get midcom QB
203 97
        $midcom_dba_classname = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type);
204 97
        if (empty($midcom_dba_classname)) {
205
            debug_add("MidCOM DBA does not know how to handle {$schema_type}", MIDCOM_LOG_ERROR);
206
            return false;
207
        }
208
209 97
        return call_user_func([$midcom_dba_classname, 'new_query_builder']);
210
    }
211
212
    /**
213
     * Figure out constraint(s) to use to get child objects
214
     */
215 96
    private function _get_link_fields(string $schema_type, $for_object) : array
216
    {
217 96
        static $cache = [];
218 96
        $cache_key = $schema_type . '-' . get_class($for_object);
219 96
        if (empty($cache[$cache_key])) {
220 7
            $ref = new midgard_reflection_property($schema_type);
221
222
            $linkfields = [
223 7
                'up' => midgard_object_class::get_property_up($schema_type),
224 7
                'parent' => midgard_object_class::get_property_parent($schema_type)
225
            ];
226 7
            $linkfields = array_filter($linkfields);
227 7
            $data = [];
228 7
            foreach ($linkfields as $link_type => $field) {
229
                $info = [
230 7
                    'name' => $field,
231 7
                    'type' => $ref->get_midgard_type($field),
232 7
                    'target' => $ref->get_link_target($field)
233
                ];
234 7
                $linked_class = $ref->get_link_name($field);
235 7
                if (   empty($linked_class)
236 7
                    && $info['type'] === MGD_TYPE_GUID) {
237
                    // Guid link without class specification, valid for all classes
238 7
                    if (empty($info['target'])) {
239 7
                        $info['target'] = 'guid';
240
                    }
241 5
                } elseif (!self::is_same_class($linked_class, get_class($for_object))) {
242
                    // This link points elsewhere
243 2
                    continue;
244
                }
245 7
                $data[$link_type] = $info;
246
            }
247 7
            $cache[$cache_key] = $data;
248
        }
249 96
        return $cache[$cache_key];
250
    }
251
252
    /**
253
     * Creates a QB instance for _get_child_objects_type
254
     */
255 96
    public function _child_objects_type_qb($schema_type, $for_object, $deleted)
256
    {
257 96
        if (!is_object($for_object)) {
258
            debug_add('Passed for_object argument is not object, this is fatal', MIDCOM_LOG_ERROR);
259
            return false;
260
        }
261 96
        $qb = $this->_get_type_qb($schema_type, $deleted);
262 96
        if (!$qb) {
263
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
264
            return false;
265
        }
266
267 96
        $linkfields = $this->_get_link_fields($schema_type, $for_object);
268
269 96
        if (empty($linkfields)) {
270
            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);
271
            return false;
272
        }
273
274 96
        $multiple_links = false;
275 96
        if (count($linkfields) > 1) {
276
            $multiple_links = true;
277
            $qb->begin_group('OR');
278
        }
279
280 96
        foreach ($linkfields as $link_type => $field_data) {
281 96
            $field_target = $field_data['target'];
282 96
            $field_type = $field_data['type'];
283 96
            $field = $field_data['name'];
284
285 96
            if (   !$field_target
286 96
                || !isset($for_object->$field_target)) {
287
                // Why return false ???
288
                return false;
289
            }
290 96
            switch ($field_type) {
291
                case MGD_TYPE_STRING:
292
                case MGD_TYPE_GUID:
293 96
                    $qb->add_constraint($field, '=', (string) $for_object->$field_target);
294 96
                    break;
295
                case MGD_TYPE_INT:
296
                case MGD_TYPE_UINT:
297 93
                    if ($link_type == 'up') {
298 93
                        $qb->add_constraint($field, '=', (int) $for_object->$field_target);
299 87
                    } elseif ($link_type == 'parent') {
300 87
                        $up_property = midgard_object_class::get_property_up($schema_type);
301 87
                        if (!empty($up_property)) {
302
                            //we only return direct children (otherwise they would turn up twice in recursive queries)
303 87
                            $qb->begin_group('AND');
304 87
                            $qb->add_constraint($field, '=', (int) $for_object->$field_target);
305 87
                            $qb->add_constraint($up_property, '=', 0);
306 87
                            $qb->end_group();
307
                        } else {
308 87
                            $qb->add_constraint($field, '=', (int) $for_object->$field_target);
309
                        }
310
                    } else {
311
                        $qb->begin_group('AND');
312
                        $qb->add_constraint($field, '=', (int) $for_object->$field_target);
313
                        // make sure we don't accidentally find other objects with the same id
314
                        $qb->add_constraint($field . '.guid', '=', (string) $for_object->guid);
315
                        $qb->end_group();
316
                    }
317 93
                    break;
318
                default:
319
                    debug_add("Do not know how to handle linked field '{$field}', has type {$field_type}", MIDCOM_LOG_INFO);
320
321
                    // Why return false ???
322
                    return false;
323
            }
324
        }
325
326 96
        if ($multiple_links) {
327
            $qb->end_group();
328
        }
329
330 96
        return $qb;
331
    }
332
333
    /**
334
     * Used by get_child_objects
335
     *
336
     * @return array of objects
337
     */
338 20
    public function _get_child_objects_type($schema_type, $for_object, $deleted)
339
    {
340 20
        $qb = $this->_child_objects_type_qb($schema_type, $for_object, $deleted);
341 20
        if (!$qb) {
342
            debug_add('Could not get QB instance', MIDCOM_LOG_ERROR);
343
            return false;
344
        }
345
346
        // Sort by title and name if available
347 20
        self::add_schema_sorts_to_qb($qb, $schema_type);
348
349 20
        return $qb->execute();
350
    }
351
352
    /**
353
     * Get the parent class of the class this reflector was instantiated for
354
     *
355
     * @return string class name (or false if the type has no parent)
356
     */
357 2
    public function get_parent_class()
358
    {
359 2
        $parent_property = midgard_object_class::get_property_parent($this->mgdschema_class);
360 2
        if (!$parent_property) {
361 2
            return false;
362
        }
363
        $ref = new midgard_reflection_property($this->mgdschema_class);
364
        return $ref->get_link_name($parent_property);
365
    }
366
367
    /**
368
     * Get the child classes of the class this reflector was instantiated for
369
     */
370 97
    public function get_child_classes() : array
371
    {
372 97
        static $child_classes_all = [];
373 97
        if (!isset($child_classes_all[$this->mgdschema_class])) {
374 5
            $child_classes_all[$this->mgdschema_class] = $this->_resolve_child_classes();
375
        }
376 97
        return $child_classes_all[$this->mgdschema_class];
377
    }
378
379
    /**
380
     * Resolve the child classes of the class this reflector was instantiated for, used by get_child_classes()
381
     */
382 5
    private function _resolve_child_classes() : array
383
    {
384 5
        $child_class_exceptions_neverchild = $this->_config->get('child_class_exceptions_neverchild');
385
386
        // Safety against misconfiguration
387 5
        if (!is_array($child_class_exceptions_neverchild)) {
388
            debug_add("config->get('child_class_exceptions_neverchild') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
389
            $child_class_exceptions_neverchild = [];
390
        }
391 5
        $child_classes = [];
392 5
        $types = array_diff(midcom_connection::get_schema_types(), $child_class_exceptions_neverchild);
393 5
        foreach ($types as $schema_type) {
394 5
            $parent_property = midgard_object_class::get_property_parent($schema_type);
395 5
            $up_property = midgard_object_class::get_property_up($schema_type);
396
397 5
            if (   !$this->_resolve_child_classes_links_back($parent_property, $schema_type, $this->mgdschema_class)
398 5
                && !$this->_resolve_child_classes_links_back($up_property, $schema_type, $this->mgdschema_class)) {
399 5
                continue;
400
            }
401
402 5
            $child_classes[] = $schema_type;
403
        }
404
405
        //make sure children of the same type come out on top
406 5
        if ($key = array_search($this->mgdschema_class, $child_classes)) {
407
            unset($child_classes[$key]);
408
            array_unshift($child_classes, $this->mgdschema_class);
409
        }
410 5
        return $child_classes;
411
    }
412
413 5
    private function _resolve_child_classes_links_back($property, $prospect_type, string $schema_type) : bool
414
    {
415 5
        if (empty($property)) {
416 5
            return false;
417
        }
418
419 5
        $ref = new midgard_reflection_property($prospect_type);
420 5
        $link_class = $ref->get_link_name($property);
421 5
        if (   empty($link_class)
422 5
            && $ref->get_midgard_type($property) === MGD_TYPE_GUID) {
423 5
            return true;
424
        }
425 5
        return self::is_same_class($link_class, $schema_type);
426
    }
427
428
    /**
429
     * Get an array of "root level" classes
430
     */
431 12
    public static function get_root_classes() : array
432
    {
433 12
        static $root_classes = false;
434 12
        if (empty($root_classes)) {
435 1
            $root_classes = self::_resolve_root_classes();
436
        }
437 12
        return $root_classes;
438
    }
439
440
    /**
441
     * Resolves the "root level" classes, used by get_root_classes()
442
     */
443 1
    private static function _resolve_root_classes() : array
444
    {
445 1
        $root_exceptions_notroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get('root_class_exceptions_notroot');
446
        // Safety against misconfiguration
447 1
        if (!is_array($root_exceptions_notroot)) {
448
            debug_add("config->get('root_class_exceptions_notroot') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
449
            $root_exceptions_notroot = [];
450
        }
451 1
        $root_classes = [];
452 1
        $types = array_diff(midcom_connection::get_schema_types(), $root_exceptions_notroot);
453 1
        foreach ($types as $schema_type) {
454
            // Class extensions mapping
455 1
            $schema_type = self::class_rewrite($schema_type);
456
457
            // Make sure we only add classes once
458 1
            if (in_array($schema_type, $root_classes)) {
459
                // Already listed
460
                continue;
461
            }
462
463 1
            if (midgard_object_class::get_property_parent($schema_type)) {
464
                // type has parent set, thus cannot be root type
465 1
                continue;
466
            }
467
468 1
            if (!midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type)) {
469
                // Not a MidCOM DBA object, skip
470
                continue;
471
            }
472
473 1
            $root_classes[] = $schema_type;
474
        }
475
476 1
        $root_exceptions_forceroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get('root_class_exceptions_forceroot');
477
        // Safety against misconfiguration
478 1
        if (!is_array($root_exceptions_forceroot)) {
479
            debug_add("config->get('root_class_exceptions_forceroot') did not return array, invalid configuration ??", MIDCOM_LOG_ERROR);
480
            $root_exceptions_forceroot = [];
481
        }
482 1
        $root_exceptions_forceroot = array_diff($root_exceptions_forceroot, $root_classes);
483 1
        foreach ($root_exceptions_forceroot as $schema_type) {
484
            if (!class_exists($schema_type)) {
485
                // Not a valid class
486
                debug_add("Type {$schema_type} has been listed to always be root class, but the class does not exist", MIDCOM_LOG_WARN);
487
                continue;
488
            }
489
            $root_classes[] = $schema_type;
490
        }
491
492 1
        usort($root_classes, 'strnatcmp');
493 1
        return $root_classes;
494
    }
495
496
    /**
497
     * Add default ("title" and "name") sorts to a QB instance
498
     *
499
     * @param midgard_query_builder $qb QB instance
500
     * @param string $schema_type valid mgdschema class name
501
     */
502 20
    public static function add_schema_sorts_to_qb($qb, $schema_type)
503
    {
504
        // Sort by "title" and "name" if available
505 20
        $ref = self::get($schema_type);
506 20
        $dummy = new $schema_type();
507 20
        if ($title_property = $ref->get_title_property($dummy)) {
508 20
            $qb->add_order($title_property);
509
        }
510 20
        if ($name_property = $ref->get_name_property($dummy)) {
511 15
            $qb->add_order($name_property);
512
        }
513 20
    }
514
515
    /**
516
     * List object children
517
     *
518
     * @param midcom_core_dbaobject $parent
519
     */
520
    public static function get_tree(midcom_core_dbaobject $parent) : array
521
    {
522
        static $shown_guids = [];
523
        $tree = [];
524
        try {
525
            $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

525
            $children = self::get_child_objects(/** @scrutinizer ignore-type */ $parent);
Loading history...
526
        } catch (midcom_error $e) {
527
            return $tree;
528
        }
529
530
        foreach ($children as $class => $objects) {
531
            $reflector = parent::get($class);
532
533
            foreach ($objects as $object) {
534
                if (array_key_exists($object->guid, $shown_guids)) {
535
                    //we might see objects twice if they have both up and parent
536
                    continue;
537
                }
538
                $shown_guids[$object->guid] = true;
539
540
                $leaf = [
541
                    'title' => $reflector->get_object_label($object),
542
                    'icon' => $reflector->get_object_icon($object),
543
                    'class' => $class
544
                ];
545
                $grandchildren = self::get_tree($object);
546
                if (!empty($grandchildren)) {
547
                    $leaf['children'] = $grandchildren;
548
                }
549
                $tree[] = $leaf;
550
            }
551
        }
552
        return $tree;
553
    }
554
}
555