Passed
Push — master ( c27313...295f5c )
by Andreas
24:45
created

midcom_helper_reflector::get_create_icon()   A

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

98
            return $cm->/** @scrutinizer ignore-call */ get_schema_properties($metadata);
Loading history...
99
        }
100 5
        return array_keys(get_object_vars($object));
101
    }
102
103 150
    public function property_exists(string $property, bool $metadata = false) : bool
104
    {
105 150
        return $this->_mgd_reflector->property_exists($property, $metadata);
106
    }
107
108
    /**
109
     * Gets a midcom_helper_l10n instance for component governing the type
110
     */
111 67
    public function get_component_l10n() : midcom_services_i18n_l10n
112
    {
113 67
        if (!isset(self::$_cache['l10n'][$this->mgdschema_class])) {
114 11
            if ($component = midcom::get()->dbclassloader->get_component_for_class($this->mgdschema_class)) {
0 ignored issues
show
Bug introduced by
It seems like $this->mgdschema_class can also be of type null; however, parameter $classname of midcom_services_dbclassl...t_component_for_class() 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

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