Passed
Push — master ( 7f11bc...601709 )
by Andreas
12:40
created

midcom_helper_reflector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 9
ccs 4
cts 4
cp 1
crap 1
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 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 = static::class . (is_object($src) ? get_class($src) : $src);
57
58 425
        return self::$_cache['instance'][$identifier] ??= new static($src);
59
    }
60
61
    /**
62
     * Get object's (mgdschema) fieldnames.
63
     */
64 264
    public static function get_object_fieldnames(object $object) : array
65
    {
66 264
        $classname = get_class($object);
67 264
        $metadata = false;
68
69 264
        if (midcom::get()->dbclassloader->is_midcom_db_object($object)) {
70 254
            $classname = $object->__mgdschema_class_name__;
71 248
        } elseif ($object instanceof midcom_helper_metadata) {
72 238
            $metadata = true;
73 238
            $classname = $object->object->__mgdschema_class_name__;
74
        }
75
76 264
        if (is_subclass_of($classname, mgdobject::class)) {
77 264
            $cm = connection::get_em()->getClassMetadata($classname);
78 264
            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

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