Passed
Push — master ( 2275f4...6b55ec )
by Andreas
25:05
created

midcom_helper_reflector::get_icon()   B

Complexity

Conditions 11
Paths 10

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 11

Importance

Changes 0
Metric Value
cc 11
eloc 19
nc 10
nop 3
dl 0
loc 28
ccs 18
cts 18
cp 1
crap 11
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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