Passed
Push — master ( ca8983...2b8004 )
by Andreas
25:20
created

midcom_helper_reflector_tree::resolve_path()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
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 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
            $qb->add_constraint($info['name'], '=', $for_object->{$info['target']});
211
            // we only return direct children (otherwise they would turn up twice in recursive queries)
212 104
            if ($info['type'] == 'parent' && $info['upfield']) {
213 95
                $qb->add_constraint($info['upfield'], '=', 0);
214
            }
215 104
            return $qb;
216
        }
217
218
        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);
219
        return false;
220
    }
221
222
    /**
223
     * Get the parent class of the class this reflector was instantiated for
224
     */
225 2
    public function get_parent_class() : ?string
226
    {
227 2
        $parent_property = midgard_object_class::get_property_parent($this->mgdschema_class);
228 2
        if (!$parent_property) {
229 2
            return null;
230
        }
231
        $ref = new midgard_reflection_property($this->mgdschema_class);
232
        return $ref->get_link_name($parent_property);
233
    }
234
235
    /**
236
     * Get the child classes of the class this reflector was instantiated for
237
     */
238 105
    public function get_child_classes() : array
239
    {
240 105
        static $cache = [];
241 105
        if (!isset($cache[$this->mgdschema_class])) {
242 4
            $cache[$this->mgdschema_class] = [];
243
244 4
            $types = array_diff(midcom_connection::get_schema_types(), $this->_config->get_array('child_class_exceptions_neverchild'));
245 4
            foreach ($types as $schema_type) {
246 4
                if ($this->get_link_field($schema_type, $this->mgdschema_class)) {
247 4
                    $cache[$this->mgdschema_class][] = $schema_type;
248
                }
249
            }
250
251
            //make sure children of the same type come out on top
252 4
            if ($key = array_search($this->mgdschema_class, $cache[$this->mgdschema_class])) {
253 2
                unset($cache[$this->mgdschema_class][$key]);
254 2
                array_unshift($cache[$this->mgdschema_class], $this->mgdschema_class);
255
            }
256
        }
257 105
        return $cache[$this->mgdschema_class];
258
    }
259
260
    /**
261
     * Get an array of "root level" classes
262
     */
263 12
    public static function get_root_classes() : array
264
    {
265 12
        static $root_classes = false;
266 12
        if (empty($root_classes)) {
267
            $root_classes = self::_resolve_root_classes();
268
        }
269 12
        return $root_classes;
270
    }
271
272
    /**
273
     * Resolves the "root level" DBA classes, used by get_root_classes()
274
     */
275
    private static function _resolve_root_classes() : array
276
    {
277
        $root_exceptions_notroot = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get_array('root_class_exceptions_notroot');
278
        $root_classes = [];
279
        $types = array_diff(midcom_connection::get_schema_types(), $root_exceptions_notroot);
280
        foreach ($types as $schema_type) {
281
            // Class extensions mapping
282
            $schema_type = self::class_rewrite($schema_type);
283
284
            // Make sure we only add classes once
285
            if (in_array($schema_type, $root_classes)) {
286
                // Already listed
287
                continue;
288
            }
289
290
            if (midgard_object_class::get_property_parent($schema_type)) {
291
                // type has parent set, thus cannot be root type
292
                continue;
293
            }
294
295
            if (!midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($schema_type)) {
296
                // Not a MidCOM DBA object, skip
297
                continue;
298
            }
299
300
            $root_classes[] = $schema_type;
301
        }
302
303
        usort($root_classes, 'strnatcmp');
304
        return $root_classes;
305
    }
306
307
    /**
308
     * Add default ("title" and "name") sorts to a QB instance
309
     *
310
     * @param midgard_query_builder $qb QB instance
311
     */
312 21
    public static function add_schema_sorts_to_qb($qb, string $schema_type)
313
    {
314
        // Sort by "title" and "name" if available
315 21
        $dummy = new $schema_type();
316 21
        if ($title_property = self::get_title_property($dummy)) {
317 21
            $qb->add_order($title_property);
318
        }
319 21
        if ($name_property = self::get_name_property($dummy)) {
320 16
            $qb->add_order($name_property);
321
        }
322 21
    }
323
324
    /**
325
     * List object children
326
     */
327
    public static function get_tree(midcom_core_dbaobject $parent) : array
328
    {
329
        $tree = [];
330
331
        foreach (self::get_child_objects($parent) as $class => $objects) {
332
            $reflector = parent::get($class);
333
334
            foreach ($objects as $object) {
335
                $leaf = [
336
                    'title' => $reflector->get_object_label($object),
337
                    'icon' => $reflector->get_object_icon($object),
338
                    'class' => $class
339
                ];
340
                if ($grandchildren = self::get_tree($object)) {
341
                    $leaf['children'] = $grandchildren;
342
                }
343
                $tree[] = $leaf;
344
            }
345
        }
346
        return $tree;
347
    }
348
}
349