Passed
Push — master ( 8c276a...ee35e3 )
by Andreas
18:09
created

midcom_helper_reflector   F

Complexity

Total Complexity 84

Size/Duplication

Total Lines 517
Duplicated Lines 0 %

Test Coverage

Coverage 95.73%

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 217
c 8
b 0
f 0
dl 0
loc 517
ccs 202
cts 211
cp 0.9573
rs 2
wmc 84

21 Methods

Rating   Name   Duplication   Size   Complexity  
A class_rewrite() 0 8 3
A get_label_property() 0 11 3
A __construct() 0 12 1
A resolve_baseclass() 0 31 6
A _get_icon_map() 0 12 3
B get_object_label() 0 30 8
A get() 0 8 3
A property_exists() 0 3 1
A get_object_title() 0 7 2
A get_class_label() 0 32 5
A get_object_icon() 0 10 2
B get_link_properties() 0 42 8
B get_search_properties() 0 54 8
A get_create_icon() 0 7 2
A get_title_property() 0 3 1
A get_object_fieldnames() 0 17 4
A is_same_class() 0 3 1
B get_property() 0 26 7
C get_icon() 0 30 12
A get_name_property() 0 3 1
A get_component_l10n() 0 12 3

How to fix   Complexity   

Complex Class

Complex classes like midcom_helper_reflector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use midcom_helper_reflector, and based on these observations, apply Extract Interface, too.

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 midcom_baseclasses_components_purecode
18
{
19
    public $mgdschema_class = '';
20
21
    /**
22
     * @var midgard_reflection_property
23
     */
24
    protected $_mgd_reflector;
25
26
    protected $_dummy_object;
27
28
    private static $_cache = [
29
        'l10n' => [],
30
        'instance' => [],
31
        'title' => [],
32
        'name' => [],
33
        'fieldnames' => [],
34
        'object_icon_map' => null,
35
        'create_type_map' => null
36
    ];
37
38
    /**
39
     * Constructor, takes classname or object, resolved MgdSchema root class automagically
40
     *
41
     * @param string|mgdobject $src classname or object
42
     */
43 194
    public function __construct($src)
44
    {
45 194
        parent::__construct();
46
47
        // Resolve root class name
48 194
        $this->mgdschema_class = self::resolve_baseclass($src);
49
50
        // Instantiate midgard reflector
51 194
        $this->_mgd_reflector = new midgard_reflection_property($this->mgdschema_class);
52
53
        // Instantiate dummy object
54 194
        $this->_dummy_object = new $this->mgdschema_class;
55 194
    }
56
57
    /**
58
     * Get cached reflector instance
59
     *
60
     * @param mixed $src Object or classname
61
     * @return static
62
     */
63 396
    public static function &get($src)
64
    {
65 396
        $identifier = get_called_class() . (is_object($src) ? get_class($src) : $src);
66
67 396
        if (!isset(self::$_cache['instance'][$identifier])) {
68 38
            self::$_cache['instance'][$identifier] = new static($src);
69
        }
70 396
        return self::$_cache['instance'][$identifier];
71
    }
72
73
    /**
74
     * Get object's (mgdschema) fieldnames.
75
     *
76
     * @param object $object Object The object to query
77
     */
78 111
    public static function get_object_fieldnames(object $object) : array
79
    {
80 111
        $classname = get_class($object);
81 111
        $metadata = false;
82
83 111
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
84 101
            $classname = $object->__mgdschema_class_name__;
85 88
        } elseif ($object instanceof midcom_helper_metadata) {
86 78
            $metadata = true;
87 78
            $classname = $object->object->__mgdschema_class_name__;
88
        }
89
90 111
        if (is_subclass_of($classname, mgdobject::class)) {
91 111
            $cm = connection::get_em()->getClassMetadata($classname);
92 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

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