Passed
Push — master ( 179526...2874e4 )
by Andreas
28:11
created

midcom_helper_reflector::get_icon()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 1
nop 3
dl 0
loc 21
ccs 13
cts 13
cp 1
crap 3
rs 9.8666
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 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
     * @return static
53
     */
54 425
    public static function get(string|object $src) : self
55
    {
56 425
        $identifier = get_called_class() . (is_object($src) ? get_class($src) : $src);
57
58 425
        if (!isset(self::$_cache['instance'][$identifier])) {
59 36
            self::$_cache['instance'][$identifier] = new static($src);
60
        }
61 425
        return self::$_cache['instance'][$identifier];
62
    }
63
64
    /**
65
     * Get object's (mgdschema) fieldnames.
66
     */
67 265
    public static function get_object_fieldnames(object $object) : array
68
    {
69 265
        $classname = get_class($object);
70 265
        $metadata = false;
71
72 265
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
73 255
            $classname = $object->__mgdschema_class_name__;
74 249
        } elseif ($object instanceof midcom_helper_metadata) {
75 239
            $metadata = true;
76 239
            $classname = $object->object->__mgdschema_class_name__;
77
        }
78
79 265
        if (is_subclass_of($classname, mgdobject::class)) {
80 265
            $cm = connection::get_em()->getClassMetadata($classname);
81 265
            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

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