midcom_helper_reflector::get_create_icon()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
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
use Doctrine\Common\Util\ClassUtils;
12
13
/**
14
 * The Grand Unified Reflector
15
 *
16
 * @package midcom.helper.reflector
17
 */
18
class midcom_helper_reflector extends midgard_reflection_property
19
{
20
    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...
21
22
    public string $mgdschema_class = '';
23
24
    private static array $_cache = [
25
        'l10n' => [],
26
        'instance' => [],
27
        'title' => [],
28
        'name' => [],
29
        'fieldnames' => [],
30
        'object_icon_map' => null,
31
        'create_type_map' => null
32
    ];
33
34
    /**
35
     * Takes classname or object, resolves MgdSchema root class automagically
36
     *
37
     * @param string|mgdobject $src classname or object
38
     */
39 210
    public function __construct($src)
40
    {
41 210
        $this->_component = 'midcom.helper.reflector';
42
43
        // Resolve root class name
44 210
        $this->mgdschema_class = self::resolve_baseclass($src);
45
46
        // Instantiate midgard reflector
47 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

47
        parent::/** @scrutinizer ignore-call */ 
48
                __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...
48
    }
49
50
    /**
51
     * Get cached reflector instance
52
     *
53
     * @return static
54
     */
55 426
    public static function get(string|object $src) : self
56
    {
57 426
        $identifier = static::class . (is_object($src) ? $src::class : $src);
58
59 426
        return self::$_cache['instance'][$identifier] ??= new static($src);
60
    }
61
62
    /**
63
     * Get object's (mgdschema) fieldnames.
64
     */
65 265
    public static function get_object_fieldnames(object $object) : array
66
    {
67 265
        $classname = $object::class;
68 265
        $metadata = false;
69
70 265
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
71 255
            $classname = $object->__mgdschema_class_name__;
72 249
        } elseif ($object instanceof midcom_helper_metadata) {
73 239
            $metadata = true;
74 239
            $classname = $object->object->__mgdschema_class_name__;
75
        }
76
77 265
        if (is_subclass_of($classname, mgdobject::class)) {
78 265
            $cm = connection::get_em()->getClassMetadata($classname);
79 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

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

404
        $classname = ClassUtils::getRealClass(/** @scrutinizer ignore-type */ $classname);
Loading history...
405
406 224
        if (isset($cached[$classname])) {
407 200
            return $cached[$classname];
408
        }
409
410 37
        if (!isset($class_instance)) {
411 8
            $class_instance = new $classname();
412
        }
413
414
        // Check for decorators first
415 37
        if (!empty($class_instance->__mgdschema_class_name__)) {
416 29
            $parent_class = $class_instance->__mgdschema_class_name__;
417
        } else {
418 8
            $parent_class = $classname;
419
        }
420
421 37
        $cached[$classname] = self::class_rewrite($parent_class);
422
423 37
        return $cached[$classname];
424
    }
425
426 417
    private function get_property(string $type, object $object) : ?string
427
    {
428
        // Cache results per class within request
429 417
        $key = $object::class;
430 417
        if (array_key_exists($key, self::$_cache[$type])) {
431 403
            return self::$_cache[$type][$key];
432
        }
433 49
        self::$_cache[$type][$key] = null;
434
435
        // Configured properties
436 49
        foreach ($this->_config->get_array($type . '_exceptions') as $class => $property) {
437 49
            if (midcom::get()->dbfactory->is_a($object, $class)) {
438 8
                if ($property !== false) {
439 7
                    if ($this->property_exists($property)) {
440 7
                        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 8
                return self::$_cache[$type][$key];
446
            }
447
        }
448
        // The simple heuristic
449 44
        if ($this->property_exists($type)) {
450 19
            self::$_cache[$type][$key] = $type;
451
        }
452 44
        return self::$_cache[$type][$key];
453
    }
454
455
    /**
456
     * Resolve the "name" property of given object
457
     */
458 329
    public static function get_name_property(object $object) : ?string
459
    {
460 329
        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 215
    public static function get_title_property(object $object) : ?string
486
    {
487 215
        return self::get($object)->get_property('title', $object);
488
    }
489
}
490