Passed
Push — master ( aea92c...5347c1 )
by Andreas
28:06 queued 12s
created

midcom_helper_reflector::get_link_properties()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 22
c 2
b 0
f 0
nc 6
nop 0
dl 0
loc 38
ccs 22
cts 22
cp 1
crap 8
rs 8.4444
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
use midgard\portable\storage\connection;
10
use midgard\portable\api\mgdobject;
11
12
/**
13
 * The Grand Unified Reflector
14
 *
15
 * @package midcom.helper.reflector
16
 */
17
class midcom_helper_reflector extends midgard_reflection_property
18
{
19
    use midcom_baseclasses_components_base;
0 ignored issues
show
introduced by
The trait midcom_baseclasses_components_base requires some properties which are not provided by midcom_helper_reflector: $i18n, $head
Loading history...
20
21
    public $mgdschema_class = '';
22
23
    private static $_cache = [
24
        'l10n' => [],
25
        'instance' => [],
26
        'title' => [],
27
        'name' => [],
28
        'fieldnames' => [],
29
        'object_icon_map' => null,
30
        'create_type_map' => null
31
    ];
32
33
    /**
34
     * Takes classname or object, resolves MgdSchema root class automagically
35
     *
36
     * @param string|mgdobject $src classname or object
37
     */
38 211
    public function __construct($src)
39
    {
40 211
        $this->_component = 'midcom.helper.reflector';
41
42
        // Resolve root class name
43 211
        $this->mgdschema_class = self::resolve_baseclass($src);
44
45
        // Instantiate midgard reflector
46 211
        parent::__construct($this->mgdschema_class);
0 ignored issues
show
Unused Code introduced by
The call to midcom_baseclasses_components_base::__construct() has too many arguments starting with $this->mgdschema_class. ( Ignorable by Annotation )

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

46
        parent::/** @scrutinizer ignore-call */ 
47
                __construct($this->mgdschema_class);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
47 211
    }
48
49
    /**
50
     * Get cached reflector instance
51
     *
52
     * @param mixed $src Object or classname
53
     * @return static
54
     */
55 406
    public static function get($src) : self
56
    {
57 406
        $identifier = get_called_class() . (is_object($src) ? get_class($src) : $src);
58
59 406
        if (!isset(self::$_cache['instance'][$identifier])) {
60 37
            self::$_cache['instance'][$identifier] = new static($src);
61
        }
62 406
        return self::$_cache['instance'][$identifier];
63
    }
64
65
    /**
66
     * Get object's (mgdschema) fieldnames.
67
     */
68 111
    public static function get_object_fieldnames(object $object) : array
69
    {
70 111
        $classname = get_class($object);
71 111
        $metadata = false;
72
73 111
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
74 101
            $classname = $object->__mgdschema_class_name__;
75 88
        } elseif ($object instanceof midcom_helper_metadata) {
76 78
            $metadata = true;
77 78
            $classname = $object->object->__mgdschema_class_name__;
78
        }
79
80 111
        if (is_subclass_of($classname, mgdobject::class)) {
81 111
            $cm = connection::get_em()->getClassMetadata($classname);
82 111
            return $cm->get_schema_properties($metadata);
0 ignored issues
show
introduced by
The method get_schema_properties() does not exist on Doctrine\ORM\Mapping\ClassMetadata. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

82
            return $cm->/** @scrutinizer ignore-call */ get_schema_properties($metadata);
Loading history...
83
        }
84 5
        return array_keys(get_object_vars($object));
85
    }
86
87
    /**
88
     * Gets a midcom_helper_l10n instance for component governing the type
89
     */
90 67
    public function get_component_l10n() : midcom_services_i18n_l10n
91
    {
92 67
        if (!isset(self::$_cache['l10n'][$this->mgdschema_class])) {
93 11
            if ($component = midcom::get()->dbclassloader->get_component_for_class($this->mgdschema_class)) {
94 10
                self::$_cache['l10n'][$this->mgdschema_class] = $this->_i18n->get_l10n($component);
95
            } else {
96 1
                debug_add("Could not resolve component for class {$this->mgdschema_class}, using our own l10n", MIDCOM_LOG_INFO);
97 1
                self::$_cache['l10n'][$this->mgdschema_class] = $this->_l10n;
98
            }
99
        }
100
101 67
        return self::$_cache['l10n'][$this->mgdschema_class];
102
    }
103
104
    /**
105
     * Get the localized label of the class
106
     *
107
     * @todo remove any hardcoded class names/prefixes
108
     */
109 67
    public function get_class_label() : string
110
    {
111 67
        $component_l10n = $this->get_component_l10n();
112 67
        $use_classname = $this->mgdschema_class;
113
114 67
        $midcom_dba_classname = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($use_classname);
115
116 67
        if (!empty($midcom_dba_classname)) {
117 67
            $use_classname = $midcom_dba_classname;
118
        }
119
120 67
        $use_classname = preg_replace('/_(db|dba)$/', '', $use_classname);
121
122 67
        $label = $component_l10n->get($use_classname);
123 67
        if ($label == $use_classname) {
124
            // Class string not localized, try Bergie's way to pretty-print
125 67
            $classname_parts = explode('_', $use_classname);
126 67
            if (count($classname_parts) >= 3) {
127
                // Drop first two parts of class name
128 67
                array_shift($classname_parts);
129 67
                array_shift($classname_parts);
130
            }
131
            // FIXME: Remove hardcoded class prefixes
132 67
            $use_label = preg_replace('/(openpsa|notifications)_/', '', implode('_', $classname_parts));
133
134 67
            $use_label = str_replace('_', ' ', $use_label);
135 67
            $label = $component_l10n->get($use_label);
136 67
            if ($use_label == $label) {
137 62
                $label = ucwords($use_label);
138
            }
139
        }
140 67
        return $label;
141
    }
142
143
    /**
144
     * Get property name to use as label
145
     */
146 23
    public function get_label_property() : string
147
    {
148 23
        $midcom_class = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($this->mgdschema_class);
149 23
        $obj = ($midcom_class) ? new $midcom_class : new $this->mgdschema_class;
150
151 23
        if (method_exists($obj, 'get_label_property')) {
152 3
            return $obj->get_label_property();
153
        }
154 20
        return $this->get_property('title', $obj) ??
155 4
            $this->get_property('name', $obj) ??
156 20
            'guid';
157
    }
158
159
    /**
160
     * Get the object label property value
161
     */
162 55
    public function get_object_label(object $object) : ?string
163
    {
164 55
        if ($object instanceof mgdobject) {
165
            try {
166 2
                $obj = midcom::get()->dbfactory->convert_midgard_to_midcom($object);
167
            } catch (midcom_error $e) {
168 2
                return null;
169
            }
170
        } else {
171 53
            $obj = $object;
172
        }
173 55
        if (method_exists($obj, 'get_label')) {
174 43
            return $obj->get_label();
175
        }
176
177 14
        $properties = array_flip($obj->get_properties());
178 14
        if (empty($properties)) {
179
            debug_add("Could not list object properties, aborting", MIDCOM_LOG_ERROR);
180
            return null;
181
        }
182 14
        if (isset($properties['title'])) {
183 12
            return $obj->title;
184
        }
185 3
        if (isset($properties['name'])) {
186 2
            return $obj->name;
187
        }
188 1
        if ($obj->id > 0) {
189
            return $this->get_class_label() . ' #' . $obj->id;
190
        }
191 1
        return '';
192
    }
193
194
    /**
195
     * Get the name of the create icon image
196
     */
197 28
    public static function get_create_icon(string $type) : string
198
    {
199 28
        if (is_callable([$type, 'get_create_icon'])) {
200
            // class has static method to tell us the answer ? great !
201
            return $type::get_create_icon();
202
        }
203 28
        return self::get_icon($type, self::resolve_baseclass($type), 'create_type');
204
    }
205
206
    /**
207
     * heuristics magic (instead of adding something here, take a look at
208
     * config keys "create_type_magic" and "object_icon_magic")
209
     */
210 37
    private static function get_icon(string $object_class, string $object_baseclass, string $mode) : string
211
    {
212 37
        if (null === self::$_cache[$mode . '_map']) {
213 2
            self::$_cache[$mode . '_map'] = self::_get_icon_map($mode . '_magic', $mode === 'create_type' ? 'file-o' : 'file');
214
        }
215 37
        $map = self::$_cache[$mode . '_map'];
216
217
        switch (true) {
218 37
            case (isset($map[$object_class])):
219 18
                return $map[$object_class];
220
221 33
            case (isset($map[$object_baseclass])):
222 3
                return $map[$object_baseclass];
223
224 32
            case (str_contains($object_class, 'person')):
225 4
                return $mode === 'create_type' ? 'user-o' : 'user';
226
227 30
            case (str_contains($object_class, 'event')):
228 2
                return 'calendar-o';
229
230 28
            case (str_contains($object_class, 'member')):
231 28
            case (str_contains($object_class, 'organization')):
232 27
            case (str_contains($object_class, 'group')):
233 6
                return 'users';
234
235 26
            case (str_contains($object_class, 'element')):
236 1
                return 'file-code-o';
237
238
            default:
239 25
                return $map['__default__'];
240
        }
241
    }
242
243
    /**
244
     * Get the object icon
245
     */
246 13
    public static function get_object_icon(object $obj) : string
247
    {
248 13
        if (method_exists($obj, 'get_icon')) {
249
            // object knows it's icon, how handy!
250 4
            $icon = $obj->get_icon();
251
        } else {
252 10
            $icon = self::get_icon(get_class($obj), self::resolve_baseclass($obj), 'object_icon');
253
        }
254
255 13
        return '<i class="fa fa-' . $icon . '"></i>';
256
    }
257
258 2
    private static function _get_icon_map(string $config_key, string $fallback) : array
259
    {
260 2
        $config = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config');
261 2
        $icon_map = [];
262
263 2
        foreach ($config->get_array($config_key) as $icon => $classes) {
264 2
            $icon_map = array_merge($icon_map, array_fill_keys($classes, $icon));
265
        }
266 2
        if (!isset($icon_map['__default__'])) {
267
            $icon_map['__default__'] = $fallback;
268
        }
269 2
        return $icon_map;
270
    }
271
272
    /**
273
     * Get class properties to use as search fields in choosers or other direct DB searches
274
     */
275 15
    public function get_search_properties() : array
276
    {
277
        // Return cached results if we have them
278 15
        static $cache = [];
279 15
        if (isset($cache[$this->mgdschema_class])) {
280 9
            return $cache[$this->mgdschema_class];
281
        }
282 7
        debug_add("Starting analysis for class {$this->mgdschema_class}");
283
284 7
        $properties = self::get_object_fieldnames(new $this->mgdschema_class);
285
286
        $default_properties = [
287 7
            'title' => true,
288
            'tag' => true,
289
            'firstname' => true,
290
            'lastname' => true,
291
            'official' => true,
292
            'username' => true,
293
        ];
294
295 7
        $search_properties = array_intersect_key($default_properties, array_flip($properties));
296
297 7
        foreach ($properties as $property) {
298 7
            if (str_contains($property, 'name')) {
299 6
                $search_properties[$property] = true;
300
            }
301
            // TODO: More per property heuristics
302
        }
303
        // TODO: parent and up heuristics
304
305 7
        $label_prop = $this->get_label_property();
306
307 7
        if (    $label_prop != 'guid'
308 7
             && $this->property_exists($label_prop)) {
309 6
            $search_properties[$label_prop] = true;
310
        }
311
312
        // Exceptions - always search these fields
313 7
        $always_search_all = $this->_config->get_array('always_search_fields');
314 7
        if (!empty($always_search_all[$this->mgdschema_class])) {
315 1
            $fields = array_intersect($always_search_all[$this->mgdschema_class], $properties);
316 1
            $search_properties += array_flip($fields);
317
        }
318
319
        // Exceptions - never search these fields
320 7
        $never_search_all = $this->_config->get_array('never_search_fields');
321 7
        if (!empty($never_search_all[$this->mgdschema_class])) {
322
            $search_properties = array_diff_key($search_properties, array_flip($never_search_all[$this->mgdschema_class]));
323
        }
324
325 7
        $search_properties = array_keys($search_properties);
326 7
        debug_print_r("Search properties for {$this->mgdschema_class}: ", $search_properties);
327 7
        $cache[$this->mgdschema_class] = $search_properties;
328 7
        return $search_properties;
329
    }
330
331
    /**
332
     * Gets a list of link properties and the links target info
333
     *
334
     * Link info key specification
335
     *     'class' string link target class name
336
     *     'target' string link target property (of target class)
337
     *
338
     * @return array multidimensional array keyed by property, values are arrays with link info (or false in case of failure)
339
     */
340 4
    public function get_link_properties() : array
341
    {
342
        // Return cached results if we have them
343 4
        static $cache = [];
344 4
        if (isset($cache[$this->mgdschema_class])) {
345 1
            return $cache[$this->mgdschema_class];
346
        }
347 3
        debug_add("Starting analysis for class {$this->mgdschema_class}");
348
349
        // Get property list and start checking (or abort on error)
350 3
        $links = [];
351 3
        foreach (self::get_object_fieldnames(new $this->mgdschema_class) as $property) {
352 3
            if ($property == 'guid') {
353
                // GUID, even though of type MGD_TYPE_GUID, is never a link
354 3
                continue;
355
            }
356
357 3
            if (   !$this->is_link($property)
358 3
                && $this->get_midgard_type($property) != MGD_TYPE_GUID) {
359 3
                continue;
360
            }
361 3
            debug_add("Processing property '{$property}'");
362
            $linkinfo = [
363 3
                'class' => $this->get_link_name($property),
364 3
                'target' => $this->get_link_target($property),
365 3
                'type' => $this->get_midgard_type($property),
366
            ];
367
368 3
            if (!$linkinfo['target'] && $linkinfo['type'] == MGD_TYPE_GUID) {
369 1
                $linkinfo['target'] = 'guid';
370
            }
371
372 3
            $links[$property] = $linkinfo;
373
        }
374
375 3
        debug_print_r("Links for {$this->mgdschema_class}: ", $links);
376 3
        $cache[$this->mgdschema_class] = $links;
377 3
        return $links;
378
    }
379
380
    /**
381
     * Map extended classes
382
     *
383
     * For example org.openpsa.* components often expand core objects,
384
     * in config we specify which classes we wish to substitute with which
385
     *
386
     * @return string new classname (or original in case no rewriting is to be done)
387
     */
388 38
    protected static function class_rewrite(string $schema_type) : string
389
    {
390 38
        $extends = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get_array('class_extends');
391 38
        if (   isset($extends[$schema_type])
392 38
            && class_exists($extends[$schema_type])) {
393 1
            return $extends[$schema_type];
394
        }
395 37
        return $schema_type;
396
    }
397
398
    /**
399
     * See if two MgdSchema classes are the same
400
     *
401
     * NOTE: also takes into account the various extended class scenarios
402
     */
403 11
    public static function is_same_class(string $class1, string $class2) : bool
404
    {
405 11
        return self::resolve_baseclass($class1) == self::resolve_baseclass($class2);
406
    }
407
408
    /**
409
     * Get the MgdSchema classname for given class
410
     *
411
     * @param string|object $classname either string (class name) or object
412
     */
413 225
    public static function resolve_baseclass($classname) : string
414
    {
415 225
        static $cached = [];
416
417 225
        if (is_object($classname)) {
418 187
            $class_instance = $classname;
419 187
            $classname = get_class($classname);
420
        }
421
422 225
        if (!$classname) {
423
            throw new midcom_error('Class name must not be empty');
424
        }
425
426 225
        if (isset($cached[$classname])) {
427 202
            return $cached[$classname];
428
        }
429
430 38
        if (!isset($class_instance)) {
431 8
            $class_instance = new $classname();
432
        }
433
434
        // Check for decorators first
435 38
        if (!empty($class_instance->__mgdschema_class_name__)) {
436 30
            $parent_class = $class_instance->__mgdschema_class_name__;
437
        } else {
438 8
            $parent_class = $classname;
439
        }
440
441 38
        $cached[$classname] = self::class_rewrite($parent_class);
442
443 38
        return $cached[$classname];
444
    }
445
446 400
    private function get_property(string $type, object $object) : ?string
447
    {
448
        // Cache results per class within request
449 400
        $key = get_class($object);
450 400
        if (array_key_exists($key, self::$_cache[$type])) {
451 386
            return self::$_cache[$type][$key];
452
        }
453 51
        self::$_cache[$type][$key] = null;
454
455
        // Configured properties
456 51
        foreach ($this->_config->get_array($type . '_exceptions') as $class => $property) {
457 51
            if (midcom::get()->dbfactory->is_a($object, $class)) {
458 9
                if ($property !== false) {
459 8
                    if ($this->property_exists($property)) {
460 8
                        self::$_cache[$type][$key] = $property;
461
                    } else {
462
                        debug_add("Matched class '{$key}' to '{$class}' via is_a but property '{$property}' does not exist", MIDCOM_LOG_ERROR);
463
                    }
464
                }
465 9
                return self::$_cache[$type][$key];
466
            }
467
        }
468
        // The simple heuristic
469 46
        if ($this->property_exists($type)) {
470 21
            self::$_cache[$type][$key] = $type;
471
        }
472 46
        return self::$_cache[$type][$key];
473
    }
474
475
    /**
476
     * Resolve the "name" property of given object
477
     */
478 315
    public static function get_name_property(object $object) : ?string
479
    {
480 315
        return self::get($object)->get_property('name', $object);
481
    }
482
483
    /**
484
     * Resolve the "title" of given object
485
     *
486
     * NOTE: This is distinctly different from get_object_label, which will always return something
487
     * even if it's just the class name and GUID, also it will for some classes include extra info (like datetimes)
488
     * which we do not want here.
489
     */
490 195
    public static function get_object_title(object $object) : ?string
491
    {
492 195
        if ($title_property = self::get_title_property($object)) {
493 192
            return (string) $object->{$title_property};
494
        }
495
        // Could not resolve valid property
496 3
        return null;
497
    }
498
499
    /**
500
     * Resolve the "title" property of given object
501
     *
502
     * NOTE: This is distinctly different from get_label_property, which will always return something
503
     * even if it's just the guid
504
     */
505 217
    public static function get_title_property(object $object) : ?string
506
    {
507 217
        return self::get($object)->get_property('title', $object);
508
    }
509
}
510