Passed
Push — master ( 56c06a...498ac3 )
by Andreas
18:49
created

midcom_helper_reflector::get_search_properties()   B

Complexity

Conditions 8
Paths 25

Size

Total Lines 54
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 8.0036

Importance

Changes 0
Metric Value
cc 8
eloc 31
nc 25
nop 0
dl 0
loc 54
ccs 25
cts 26
cp 0.9615
crap 8.0036
rs 8.1795
c 0
b 0
f 0

How to fix   Long Method   

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

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