Passed
Push — master ( 1857dc...a686c4 )
by Andreas
19:48
created

midcom_helper_reflector_tree::get_root_classes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
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 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 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 96
    private function _get_type_qb(string $schema_type, bool $deleted)
137
    {
138 96
        if (empty($schema_type)) {
139
            debug_add('Passed schema_type argument is empty, this is fatal', MIDCOM_LOG_ERROR);
140
            return false;
141
        }
142 96
        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 96
        $midcom_dba_classname = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type);
150 96
        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 96
        return $midcom_dba_classname::new_query_builder();
156
    }
157
158
    /**
159
     * Figure out constraint(s) to use to get child objects
160
     */
161 94
    private function _get_link_fields(string $schema_type, string $target_class) : array
162
    {
163 94
        static $cache = [];
164 94
        $cache_key = $schema_type . '-' . $target_class;
165 94
        if (empty($cache[$cache_key])) {
166 6
            $ref = new midgard_reflection_property($schema_type);
167
168 6
            $linkfields = array_filter([
169 6
                'up' => midgard_object_class::get_property_up($schema_type),
170 6
                'parent' => midgard_object_class::get_property_parent($schema_type)
171
            ]);
172 6
            $data = [];
173 6
            foreach ($linkfields as $link_type => $field) {
174
                $info = [
175 6
                    'name' => $field,
176 6
                    'type' => $ref->get_midgard_type($field),
177 6
                    'target' => $ref->get_link_target($field)
178
                ];
179
180 6
                if ($linked_class = $ref->get_link_name($field)) {
181 5
                    if (!self::is_same_class($linked_class, $target_class)) {
182
                        // This link points elsewhere
183 5
                        continue;
184
                    }
185 6
                } elseif ($info['type'] === MGD_TYPE_GUID && empty($info['target'])) {
186
                    // Guid link without class specification, valid for all classes
187 6
                    $info['target'] = 'guid';
188
                }
189 6
                $data[$link_type] = $info;
190
            }
191 6
            $cache[$cache_key] = $data;
192
        }
193 94
        return $cache[$cache_key];
194
    }
195
196
    /**
197
     * Creates a QB instance for _get_child_objects_type
198
     */
199 94
    public function _child_objects_type_qb(string $schema_type, object $for_object, bool $deleted)
200
    {
201 94
        $qb = $this->_get_type_qb($schema_type, $deleted);
202 94
        if (!$qb) {
203
            debug_add("Could not get QB for type '{$schema_type}'", MIDCOM_LOG_ERROR);
204
            return false;
205
        }
206
207 94
        $linkfields = $this->_get_link_fields($schema_type, get_class($for_object));
208
209 94
        if (empty($linkfields)) {
210
            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);
211
            return false;
212
        }
213
214 94
        $multiple_links = count($linkfields) > 1;
215 94
        if ($multiple_links) {
216
            $qb->begin_group('OR');
217
        }
218
219 94
        foreach ($linkfields as $link_type => $field_data) {
220 94
            $field_target = $field_data['target'];
221 94
            $field_type = $field_data['type'];
222 94
            $field = $field_data['name'];
223
224 94
            if (   !$field_target
225 94
                || !isset($for_object->$field_target)) {
226
                // Why return false ???
227
                return false;
228
            }
229 94
            switch ($field_type) {
230
                case MGD_TYPE_STRING:
231
                case MGD_TYPE_GUID:
232 94
                    $qb->add_constraint($field, '=', $for_object->$field_target);
233 94
                    break;
234
                case MGD_TYPE_INT:
235
                case MGD_TYPE_UINT:
236 91
                    if ($link_type == 'up') {
237 91
                        $qb->add_constraint($field, '=', $for_object->$field_target);
238
                    } else {
239 85
                        if (!empty($linkfields['up']['name'])) {
240
                            //we only return direct children (otherwise they would turn up twice in recursive queries)
241
                            $qb->begin_group('AND');
242
                            $qb->add_constraint($field, '=', $for_object->$field_target);
243
                            $qb->add_constraint($linkfields['up']['name'], '=', 0);
244
                            $qb->end_group();
245
                        } else {
246 85
                            $qb->add_constraint($field, '=', $for_object->$field_target);
247
                        }
248
                    }
249 91
                    break;
250
                default:
251
                    debug_add("Do not know how to handle linked field '{$field}', has type {$field_type}", MIDCOM_LOG_INFO);
252
253
                    // Why return false ???
254
                    return false;
255
            }
256
        }
257
258 94
        if ($multiple_links) {
259
            $qb->end_group();
260
        }
261
262 94
        return $qb;
263
    }
264
265
    /**
266
     * Get the parent class of the class this reflector was instantiated for
267
     *
268
     * @return string class name (or false if the type has no parent)
269
     */
270 2
    public function get_parent_class() : ?string
271
    {
272 2
        $parent_property = midgard_object_class::get_property_parent($this->mgdschema_class);
273 2
        if (!$parent_property) {
274 2
            return null;
275
        }
276
        $ref = new midgard_reflection_property($this->mgdschema_class);
277
        return $ref->get_link_name($parent_property);
278
    }
279
280
    /**
281
     * Get the child classes of the class this reflector was instantiated for
282
     */
283 95
    public function get_child_classes() : array
284
    {
285 95
        static $cache = [];
286 95
        if (!isset($cache[$this->mgdschema_class])) {
287 4
            $cache[$this->mgdschema_class] = [];
288
289 4
            $types = array_diff(midcom_connection::get_schema_types(), $this->_config->get_array('child_class_exceptions_neverchild'));
290 4
            foreach ($types as $schema_type) {
291 4
                if ($this->_get_link_fields($schema_type, $this->mgdschema_class)) {
292 4
                    $cache[$this->mgdschema_class][] = $schema_type;
293
                }
294
            }
295
296
            //make sure children of the same type come out on top
297 4
            if ($key = array_search($this->mgdschema_class, $cache[$this->mgdschema_class])) {
298 2
                unset($cache[$this->mgdschema_class][$key]);
299 2
                array_unshift($cache[$this->mgdschema_class], $this->mgdschema_class);
300
            }
301
        }
302 95
        return $cache[$this->mgdschema_class];
303
    }
304
305
    /**
306
     * Get an array of "root level" classes
307
     */
308 12
    public static function get_root_classes() : array
309
    {
310 12
        static $root_classes = false;
311 12
        if (empty($root_classes)) {
312
            $root_classes = self::_resolve_root_classes();
313
        }
314 12
        return $root_classes;
315
    }
316
317
    /**
318
     * Resolves the "root level" classes, used by get_root_classes()
319
     */
320
    private static function _resolve_root_classes() : array
321
    {
322
        $root_exceptions_notroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get_array('root_class_exceptions_notroot');
323
        $root_classes = [];
324
        $types = array_diff(midcom_connection::get_schema_types(), $root_exceptions_notroot);
325
        foreach ($types as $schema_type) {
326
            // Class extensions mapping
327
            $schema_type = self::class_rewrite($schema_type);
328
329
            // Make sure we only add classes once
330
            if (in_array($schema_type, $root_classes)) {
331
                // Already listed
332
                continue;
333
            }
334
335
            if (midgard_object_class::get_property_parent($schema_type)) {
336
                // type has parent set, thus cannot be root type
337
                continue;
338
            }
339
340
            if (!midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type)) {
341
                // Not a MidCOM DBA object, skip
342
                continue;
343
            }
344
345
            $root_classes[] = $schema_type;
346
        }
347
348
        usort($root_classes, 'strnatcmp');
349
        return $root_classes;
350
    }
351
352
    /**
353
     * Add default ("title" and "name") sorts to a QB instance
354
     *
355
     * @param midgard_query_builder $qb QB instance
356
     */
357 21
    public static function add_schema_sorts_to_qb($qb, string $schema_type)
358
    {
359
        // Sort by "title" and "name" if available
360 21
        $dummy = new $schema_type();
361 21
        if ($title_property = self::get_title_property($dummy)) {
362 21
            $qb->add_order($title_property);
363
        }
364 21
        if ($name_property = self::get_name_property($dummy)) {
365 16
            $qb->add_order($name_property);
366
        }
367 21
    }
368
369
    /**
370
     * List object children
371
     */
372
    public static function get_tree(midcom_core_dbaobject $parent) : array
373
    {
374
        static $shown_guids = [];
375
        $tree = [];
376
377
        foreach (self::get_child_objects($parent) as $class => $objects) {
378
            $reflector = parent::get($class);
379
380
            foreach ($objects as $object) {
381
                if (array_key_exists($object->guid, $shown_guids)) {
382
                    //we might see objects twice if they have both up and parent
383
                    continue;
384
                }
385
                $shown_guids[$object->guid] = true;
386
387
                $leaf = [
388
                    'title' => $reflector->get_object_label($object),
389
                    'icon' => $reflector->get_object_icon($object),
390
                    'class' => $class
391
                ];
392
                if ($grandchildren = self::get_tree($object)) {
393
                    $leaf['children'] = $grandchildren;
394
                }
395
                $tree[] = $leaf;
396
            }
397
        }
398
        return $tree;
399
    }
400
}
401