Passed
Push — master ( a25a71...153b53 )
by Andreas
10:54
created

midcom_helper_reflector::class_rewrite()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 3
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
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
    }
48
49
    /**
50
     * Get cached reflector instance
51
     *
52
     * @param mixed $src Object or classname
53
     * @return static
54
     */
55 422
    public static function get($src) : self
56
    {
57 422
        $identifier = get_called_class() . (is_object($src) ? get_class($src) : $src);
58
59 422
        if (!isset(self::$_cache['instance'][$identifier])) {
60 37
            self::$_cache['instance'][$identifier] = new static($src);
61
        }
62 422
        return self::$_cache['instance'][$identifier];
63
    }
64
65
    /**
66
     * Get object's (mgdschema) fieldnames.
67
     */
68 263
    public static function get_object_fieldnames(object $object) : array
69
    {
70 263
        $classname = get_class($object);
71 263
        $metadata = false;
72
73 263
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
74 253
            $classname = $object->__mgdschema_class_name__;
75 246
        } elseif ($object instanceof midcom_helper_metadata) {
76 236
            $metadata = true;
77 236
            $classname = $object->object->__mgdschema_class_name__;
78
        }
79
80 263
        if (is_subclass_of($classname, mgdobject::class)) {
81 263
            $cm = connection::get_em()->getClassMetadata($classname);
82 263
            return $cm->get_schema_properties($metadata);
0 ignored issues
show
Bug introduced by
The method get_schema_properties() does not exist on Doctrine\Persistence\Mapping\ClassMetadata. It seems like you code against a sub-type of Doctrine\Persistence\Mapping\ClassMetadata such as midgard\portable\mapping\classmetadata. ( 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
        if (null === self::$_cache[$mode . '_map']) {
206 2
            self::$_cache[$mode . '_map'] = self::_get_icon_map($mode . '_magic', $mode === 'create_type' ? 'file-o' : 'file');
207
        }
208 37
        $map = self::$_cache[$mode . '_map'];
209
210
        switch (true) {
211 37
            case (isset($map[$object_class])):
212 18
                return $map[$object_class];
213
214 33
            case (isset($map[$object_baseclass])):
215 3
                return $map[$object_baseclass];
216
217 32
            case (str_contains($object_class, 'person')):
218 4
                return $mode === 'create_type' ? 'user-o' : 'user';
219
220 30
            case (str_contains($object_class, 'event')):
221 2
                return 'calendar-o';
222
223 28
            case (str_contains($object_class, 'member')):
224 28
            case (str_contains($object_class, 'organization')):
225 27
            case (str_contains($object_class, 'group')):
226 6
                return 'users';
227
228 26
            case (str_contains($object_class, 'element')):
229 1
                return 'file-code-o';
230
231
            default:
232 25
                return $map['__default__'];
233
        }
234
    }
235
236
    /**
237
     * Get the object icon
238
     */
239 13
    public static function get_object_icon(object $obj) : string
240
    {
241 13
        if (method_exists($obj, 'get_icon')) {
242
            // object knows it's icon, how handy!
243 4
            $icon = $obj->get_icon();
244
        } else {
245 10
            $icon = self::get_icon(get_class($obj), self::resolve_baseclass($obj), 'object_icon');
246
        }
247
248 13
        return '<i class="fa fa-' . $icon . '"></i>';
249
    }
250
251 2
    private static function _get_icon_map(string $config_key, string $fallback) : array
252
    {
253 2
        $config = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config');
254 2
        $icon_map = [];
255
256 2
        foreach ($config->get_array($config_key) as $icon => $classes) {
257 2
            $icon_map = array_merge($icon_map, array_fill_keys($classes, $icon));
258
        }
259 2
        if (!isset($icon_map['__default__'])) {
260
            $icon_map['__default__'] = $fallback;
261
        }
262 2
        return $icon_map;
263
    }
264
265
    /**
266
     * Get class properties to use as search fields in choosers or other direct DB searches
267
     */
268 15
    public function get_search_properties() : array
269
    {
270
        // Return cached results if we have them
271 15
        static $cache = [];
272 15
        if (isset($cache[$this->mgdschema_class])) {
273 9
            return $cache[$this->mgdschema_class];
274
        }
275 7
        debug_add("Starting analysis for class {$this->mgdschema_class}");
276
277 7
        $properties = self::get_object_fieldnames(new $this->mgdschema_class);
278
279 7
        $default_properties = [
280 7
            'title' => true,
281 7
            'tag' => true,
282 7
            'firstname' => true,
283 7
            'lastname' => true,
284 7
            'official' => true,
285 7
            'username' => true,
286 7
        ];
287
288 7
        $search_properties = array_intersect_key($default_properties, array_flip($properties));
289
290 7
        foreach ($properties as $property) {
291 7
            if (str_contains($property, 'name')) {
292 6
                $search_properties[$property] = true;
293
            }
294
            // TODO: More per property heuristics
295
        }
296
        // TODO: parent and up heuristics
297
298 7
        $label_prop = $this->get_label_property();
299
300 7
        if (    $label_prop != 'guid'
301 7
             && $this->property_exists($label_prop)) {
302 6
            $search_properties[$label_prop] = true;
303
        }
304
305
        // Exceptions - always search these fields
306 7
        $always_search_all = $this->_config->get_array('always_search_fields');
307 7
        if (!empty($always_search_all[$this->mgdschema_class])) {
308 1
            $fields = array_intersect($always_search_all[$this->mgdschema_class], $properties);
309 1
            $search_properties += array_flip($fields);
310
        }
311
312
        // Exceptions - never search these fields
313 7
        $never_search_all = $this->_config->get_array('never_search_fields');
314 7
        if (!empty($never_search_all[$this->mgdschema_class])) {
315
            $search_properties = array_diff_key($search_properties, array_flip($never_search_all[$this->mgdschema_class]));
316
        }
317
318 7
        $search_properties = array_keys($search_properties);
319 7
        debug_print_r("Search properties for {$this->mgdschema_class}: ", $search_properties);
320 7
        $cache[$this->mgdschema_class] = $search_properties;
321 7
        return $search_properties;
322
    }
323
324
    /**
325
     * Gets a list of link properties and the links target info
326
     *
327
     * Link info key specification
328
     *     'class' string link target class name
329
     *     'target' string link target property (of target class)
330
     *
331
     * @return array multidimensional array keyed by property, values are arrays with link info (or false in case of failure)
332
     */
333 4
    public function get_link_properties() : array
334
    {
335
        // Return cached results if we have them
336 4
        static $cache = [];
337 4
        if (isset($cache[$this->mgdschema_class])) {
338 1
            return $cache[$this->mgdschema_class];
339
        }
340 3
        debug_add("Starting analysis for class {$this->mgdschema_class}");
341
342
        // Get property list and start checking (or abort on error)
343 3
        $links = [];
344 3
        foreach (self::get_object_fieldnames(new $this->mgdschema_class) as $property) {
345 3
            if ($property == 'guid') {
346
                // GUID, even though of type MGD_TYPE_GUID, is never a link
347 3
                continue;
348
            }
349
350 3
            if (   !$this->is_link($property)
351 3
                && $this->get_midgard_type($property) != MGD_TYPE_GUID) {
352 3
                continue;
353
            }
354 3
            debug_add("Processing property '{$property}'");
355 3
            $linkinfo = [
356 3
                'class' => $this->get_link_name($property),
357 3
                'target' => $this->get_link_target($property),
358 3
                'type' => $this->get_midgard_type($property),
359 3
            ];
360
361 3
            if (!$linkinfo['target'] && $linkinfo['type'] == MGD_TYPE_GUID) {
362 1
                $linkinfo['target'] = 'guid';
363
            }
364
365 3
            $links[$property] = $linkinfo;
366
        }
367
368 3
        debug_print_r("Links for {$this->mgdschema_class}: ", $links);
369 3
        $cache[$this->mgdschema_class] = $links;
370 3
        return $links;
371
    }
372
373
    /**
374
     * Map extended classes
375
     *
376
     * For example org.openpsa.* components often expand core objects,
377
     * in config we specify which classes we wish to substitute with which
378
     *
379
     * @return string new classname (or original in case no rewriting is to be done)
380
     */
381 37
    protected static function class_rewrite(string $schema_type) : string
382
    {
383 37
        $extends = midcom_baseclasses_components_configuration::get('midcom.helper.reflector', 'config')->get_array('class_extends');
384 37
        if (   isset($extends[$schema_type])
385 37
            && class_exists($extends[$schema_type])) {
386 1
            return $extends[$schema_type];
387
        }
388 36
        return $schema_type;
389
    }
390
391
    /**
392
     * See if two MgdSchema classes are the same
393
     *
394
     * NOTE: also takes into account the various extended class scenarios
395
     */
396 11
    public static function is_same_class(string $class1, string $class2) : bool
397
    {
398 11
        return self::resolve_baseclass($class1) == self::resolve_baseclass($class2);
399
    }
400
401
    /**
402
     * Get the MgdSchema classname for given class
403
     *
404
     * @param string|object $classname either string (class name) or object
405
     */
406 225
    public static function resolve_baseclass($classname) : string
407
    {
408 225
        static $cached = [];
409
410 225
        if (is_object($classname)) {
411 187
            $class_instance = $classname;
412 187
            $classname = get_class($classname);
413
        }
414
415 225
        if (!$classname) {
416
            throw new midcom_error('Class name must not be empty');
417
        }
418
419 225
        if (isset($cached[$classname])) {
420 201
            return $cached[$classname];
421
        }
422
423 37
        if (!isset($class_instance)) {
424 8
            $class_instance = new $classname();
425
        }
426
427
        // Check for decorators first
428 37
        if (!empty($class_instance->__mgdschema_class_name__)) {
429 29
            $parent_class = $class_instance->__mgdschema_class_name__;
430
        } else {
431 8
            $parent_class = $classname;
432
        }
433
434 37
        $cached[$classname] = self::class_rewrite($parent_class);
435
436 37
        return $cached[$classname];
437
    }
438
439 416
    private function get_property(string $type, object $object) : ?string
440
    {
441
        // Cache results per class within request
442 416
        $key = get_class($object);
443 416
        if (array_key_exists($key, self::$_cache[$type])) {
444 402
            return self::$_cache[$type][$key];
445
        }
446 51
        self::$_cache[$type][$key] = null;
447
448
        // Configured properties
449 51
        foreach ($this->_config->get_array($type . '_exceptions') as $class => $property) {
450 51
            if (midcom::get()->dbfactory->is_a($object, $class)) {
451 9
                if ($property !== false) {
452 8
                    if ($this->property_exists($property)) {
453 8
                        self::$_cache[$type][$key] = $property;
454
                    } else {
455
                        debug_add("Matched class '{$key}' to '{$class}' via is_a but property '{$property}' does not exist", MIDCOM_LOG_ERROR);
456
                    }
457
                }
458 9
                return self::$_cache[$type][$key];
459
            }
460
        }
461
        // The simple heuristic
462 46
        if ($this->property_exists($type)) {
463 20
            self::$_cache[$type][$key] = $type;
464
        }
465 46
        return self::$_cache[$type][$key];
466
    }
467
468
    /**
469
     * Resolve the "name" property of given object
470
     */
471 329
    public static function get_name_property(object $object) : ?string
472
    {
473 329
        return self::get($object)->get_property('name', $object);
474
    }
475
476
    /**
477
     * Resolve the "title" of given object
478
     *
479
     * NOTE: This is distinctly different from get_object_label, which will always return something
480
     * even if it's just the class name and GUID, also it will for some classes include extra info (like datetimes)
481
     * which we do not want here.
482
     */
483 202
    public static function get_object_title(object $object) : ?string
484
    {
485 202
        if ($title_property = self::get_title_property($object)) {
486 199
            return (string) $object->{$title_property};
487
        }
488
        // Could not resolve valid property
489 3
        return null;
490
    }
491
492
    /**
493
     * Resolve the "title" property of given object
494
     *
495
     * NOTE: This is distinctly different from get_label_property, which will always return something
496
     * even if it's just the guid
497
     */
498 224
    public static function get_title_property(object $object) : ?string
499
    {
500 224
        return self::get($object)->get_property('title', $object);
501
    }
502
}
503