Completed
Push — master ( 01ca5d...148252 )
by Andreas
17:12
created

midcom_helper_metadata   F

Complexity

Total Complexity 67

Size/Duplication

Total Lines 444
Duplicated Lines 0 %

Test Coverage

Coverage 77.85%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 141
dl 0
loc 444
ccs 116
cts 149
cp 0.7785
rs 3.04
c 1
b 0
f 0
wmc 67

20 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 7 2
A __isset() 0 7 2
A __get() 0 6 2
A __construct() 0 4 1
A get_datamanager() 0 18 4
A is_approved() 0 3 1
A is_locked() 0 21 5
B _set_property() 0 31 9
A unapprove() 0 5 1
A can_unlock() 0 4 2
A lock() 0 10 2
A is_object_visible_onsite() 0 7 4
A __set() 0 3 1
A is_visible() 0 16 6
A approve() 0 5 1
A set() 0 16 3
A on_update() 0 10 3
A retrieve() 0 25 5
A unlock() 0 9 3
B _retrieve_value() 0 35 10

How to fix   Complexity   

Complex Class

Complex classes like midcom_helper_metadata often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use midcom_helper_metadata, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package midcom.helper
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 midcom\datamanager\schemadb;
10
use midcom\datamanager\datamanager;
11
12
/**
13
 * This class is an interface to the metadata of MidCOM objects.
14
 *
15
 * It will use an internal mechanism to cache repeated accesses to the same
16
 * metadata key during its lifetime. (Invalidating this cache will be possible
17
 * though.)
18
 *
19
 * <b>Metadata Key Reference</b>
20
 *
21
 * See the schema in /midcom/config/metadata_default.inc
22
 *
23
 * <b>Example Usage, Metadata Retrieval</b>
24
 *
25
 * <code>
26
 * <?php
27
 * $nap = new midcom_helper_nav();
28
 * $node = $nap->get_node($nap->get_current_node());
29
 *
30
 * $meta = $node[MIDCOM_NAV_OBJECT]->metadata;
31
 * echo "Visible : " . $meta->is_visible() . "</br>";
32
 * echo "Approved : " . $meta->is_approved() . "</br>";
33
 * echo "Keywords: " . $meta->get('keywords') . "</br>";
34
 * </code>
35
 *
36
 * <b>Example Usage, Approval</b>
37
 *
38
 * <code>
39
 * <?php
40
 * $article = new midcom_db_article($my_article_created_id);
41
 *
42
 * $article->metadata->approve();
43
 * </code>
44
 *
45
 * @property integer $schedulestart The time upon which the object should be made visible. 0 for no restriction.
46
 * @property integer $scheduleend The time upon which the object should be made invisible. 0 for no restriction.
47
 * @property boolean $navnoentry Set this to true if you do not want this object to appear in the navigation without it being completely hidden.
48
 * @property boolean $hidden Set this to true to hide the object on-site, overriding scheduling.
49
 * @property integer $published The publication time of the object.
50
 * @property string $publisher The person that published the object (i.e. author), read-only except on articles and pages.
51
 * @property string $authors The persons that worked on the object, pipe-separated list of GUIDs
52
 * @property string $owner The group that owns the object.
53
 * @property-read integer $created The creation time of the object.
54
 * @property-read string $creator The person that created the object.
55
 * @property-read integer $revised The last-modified time of the object.
56
 * @property-read string $revisor The person that modified the object.
57
 * @property-read integer $revision The object's revision.
58
 * @property-read integer $locked The lock time of the object.
59
 * @property-read string $locker The person that locked the object.
60
 * @property-read integer $size The object's size in bytes.
61
 * @property-read boolean $deleted Is the object deleted.
62
 * @property integer $approved The time of approval of the object, or 0 if not approved. Set automatically through approve/unapprove.
63
 * @property string $approver The person that approved/unapproved the object. Set automatically through approve/unapprove.
64
 * @property integer $score The object's score for sorting.
65
 * @property midcom_core_dbaobject $object Object to which we are attached.
66
 * @package midcom.helper
67
 */
68
class midcom_helper_metadata
69
{
70
    /**
71
     * @var midcom_core_dbaobject
72
     */
73
    private $__object;
74
75
    /**
76
     * Metadata object of the current object
77
     *
78
     * @var midgard\portable\api\metadata
79
     */
80
    private $__metadata;
81
82
    /**
83
     * Holds the values already read from the database.
84
     *
85
     * @var Array
86
     */
87
    private $_cache = [];
88
89
    private $field_config = [
90
        'readonly' => ['creator', 'created', 'revisor', 'revised', 'locker', 'locked', 'revision', 'size', 'deleted', 'exported', 'imported'],
91
        'timebased' => ['created', 'revised', 'published', 'locked', 'approved', 'schedulestart', 'scheduleend', 'exported', 'imported'],
92
        'person' => ['creator', 'revisor', 'locker', 'approver'],
93
        'other' => ['authors', 'owner', 'hidden', 'navnoentry', 'score', 'revision', 'size', 'deleted']
94
    ];
95
96
    /**
97
     * This will construct a new metadata object for an existing content object.
98
     *
99
     * @param midcom_core_dbaobject $object The object to attach to.
100
     */
101 389
    public function __construct(midcom_core_dbaobject $object)
102
    {
103 389
        $this->__metadata = $object->__object->metadata;
104 389
        $this->__object = $object;
105 389
    }
106
107
    /* ------- BASIC METADATA INTERFACE --------- */
108
109
    /**
110
     * Return a single metadata key from the object. The return
111
     * type depends on the metadata key that is requested (see the class introduction).
112
     *
113
     * You will not get the data from the datamanager using this calls, but the only
114
     * slightly post-processed metadata values. See _retrieve_value for post processing.
115
     *
116
     * @see midcom_helper_metadata::_retrieve_value()
117
     * @param string $key The key to retrieve
118
     * @return mixed The key's value.
119
     */
120 401
    public function get(string $key)
121
    {
122 401
        if (!isset($this->_cache[$key])) {
123 289
            $this->_cache[$key] = $this->_retrieve_value($key);
124
        }
125
126 401
        return $this->_cache[$key];
127
    }
128
129 357
    public function __get($key)
130
    {
131 357
        if ($key == 'object') {
132 78
            return $this->__object;
133
        }
134 357
        return $this->get($key);
135
    }
136
137 306
    public function __isset($key)
138
    {
139 306
        if (!isset($this->_cache[$key])) {
140 306
            $this->_cache[$key] = $this->_retrieve_value($key);
141
        }
142
143 306
        return isset($this->_cache[$key]);
144
    }
145
146
    /**
147
     * Return a Datamanager instance for the current object.
148
     *
149
     * Also, whenever the containing datamanager stores its data, you
150
     * <b>must</b> call the on_update() method of this class. This is
151
     * very important or backwards compatibility will be broken.
152
     *
153
     * @see midcom_helper_metadata::on_update()
154
     */
155 98
    public function get_datamanager() : datamanager
156
    {
157 98
        $schemadb = schemadb::from_path(midcom::get()->config->get('metadata_schema'));
0 ignored issues
show
Bug introduced by
It seems like midcom::get()->config->get('metadata_schema') can also be of type null; however, parameter $path of midcom\datamanager\schemadb::from_path() 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

157
        $schemadb = schemadb::from_path(/** @scrutinizer ignore-type */ midcom::get()->config->get('metadata_schema'));
Loading history...
158
159
        // Check if we have metadata schema defined in the schemadb specific for the object's schema or component
160 98
        $object_schema = $this->__object->get_parameter('midcom.helper.datamanager2', 'schema_name');
161 98
        if (!$object_schema || !$schemadb->has($object_schema)) {
162 98
            $component_schema = str_replace('.', '_', midcom_core_context::get()->get_key(MIDCOM_CONTEXT_COMPONENT));
163 98
            if ($schemadb->has($component_schema)) {
164
                // No specific metadata schema for object, fall back to component-specific metadata schema
165
                $object_schema = $component_schema;
166
            } else {
167
                // No metadata schema for component, fall back to default
168 98
                $object_schema = 'metadata';
169
            }
170
        }
171 98
        $dm = new datamanager($schemadb);
172 98
        return $dm->set_storage($this->__object, $object_schema);
173
    }
174
175
    /**
176
     * Frontend for setting a single metadata option
177
     */
178 287
    public function set(string $key, $value) : bool
179
    {
180
        // Store the RCS mode
181 287
        $rcs_mode = $this->__object->_use_rcs;
182
183 287
        if ($return = $this->_set_property($key, $value)) {
184 286
            if ($this->__object->guid) {
185 9
                $return = $this->__object->update();
186
            }
187
188
            // Update the corresponding cache variable
189 286
            $this->on_update($key);
190
        }
191
        // Return the original RCS mode
192 287
        $this->__object->_use_rcs = $rcs_mode;
193 287
        return $return;
194
    }
195
196 15
    public function __set($key, $value)
197
    {
198 15
        $this->set($key, $value);
199 15
    }
200
201
    /**
202
     * Directly set a metadata option.
203
     *
204
     * The passed value will be stored using the follow transformations:
205
     *
206
     * - Storing into the approver field will automatically recognize Person Objects and simple
207
     *   IDs and transform them into a GUID.
208
     * - created can only be set with articles.
209
     * - creator, editor and edited cannot be set.
210
     *
211
     * Any error will trigger midcom_error.
212
     *
213
     * @param string $key The key to set.
214
     * @param mixed $value The value to set.
215
     */
216 287
    private function _set_property(string $key, $value) : bool
217
    {
218 287
        if (is_object($value)) {
219
            $classname = get_class($value);
220
            debug_add("Can not set metadata '{$key}' property with '{$classname}' object as value", MIDCOM_LOG_WARN);
221
            return false;
222
        }
223
224 287
        if (in_array($key, $this->field_config['readonly'])) {
225
            midcom_connection::set_error(MGD_ERR_ACCESS_DENIED);
226
            return false;
227
        }
228
229 287
        if (in_array($key, ['approver', 'approved'])) {
230
            // Prevent lock changes from creating new revisions
231
            $this->__object->_use_rcs = false;
232
        }
233
234 287
        if (in_array($key, $this->field_config['timebased'])) {
235 285
            if (!is_numeric($value) || $value == 0) {
236 3
                $value = null;
237
            } else {
238 285
                $value = new midgard_datetime(gmstrftime('%Y-%m-%d %T', $value));
239
            }
240 151
        } elseif (!in_array($key, $this->field_config['other']) && $key !== 'approver') {
241
            // Fall-back for non-core properties
242 4
            return $this->__object->set_parameter('midcom.helper.metadata', $key, $value);
243
        }
244
245 286
        $this->__metadata->$key = $value;
246 286
        return true;
247
    }
248
249
    /**
250
     * This is the update event handler for the Metadata system. It must be called
251
     * whenever metadata changes to synchronize the various backwards-compatibility
252
     * values in place throughout the system.
253
     *
254
     * @param string $key The key that was updated. Leave empty for a complete update by the Datamanager.
255
     */
256 286
    private function on_update(string $key = null)
257
    {
258 286
        if ($key) {
259 286
            unset($this->_cache[$key]);
260
        } else {
261
            $this->_cache = [];
262
        }
263
264 286
        if (!empty($this->__object->guid)) {
265 9
            midcom::get()->cache->invalidate($this->__object->guid);
266
        }
267 286
    }
268
269
    /* ------- METADATA I/O INTERFACE -------- */
270
271
    /**
272
     * Retrieves a given metadata key, postprocesses it where necessary
273
     * and stores it into the local cache.
274
     *
275
     * - Person references (both guid and id) get resolved into the corresponding
276
     *   Person object.
277
     * - created, creator, edited and editor are taken from the corresponding
278
     *   MidgardObject fields.
279
     * - Parameters are accessed using $object->get_parameter directly
280
     *
281
     * Note, that we hide any errors from not existent properties explicitly,
282
     * as a few of the MidCOM objects do not support all of the predefined meta
283
     * data fields, PHP will default to "0" in these cases. For Person IDs, this
284
     * "0" is rewritten to "1" to use the MidgardAdministrator account instead.
285
     *
286
     * @param string $key The key to retrieve.
287
     */
288 401
    private function _retrieve_value(string $key)
289
    {
290 401
        if (in_array($key, $this->field_config['timebased'])) {
291
            // This is ugly, but seems the only possible way...
292 368
            if (   isset($this->__metadata->$key)
293 368
                && (string) $this->__metadata->$key !== "0001-01-01T00:00:00+00:00") {
294 171
                return (int) $this->__metadata->$key->format('U');
295
            }
296 320
            return 0;
297
        }
298 277
        if (in_array($key, $this->field_config['person'])) {
299 108
            if (!$this->__metadata->$key) {
300
                // Fall back to "Midgard root user" if person is not found
301 80
                static $root_user_guid = null;
302 80
                if (!$root_user_guid) {
303
                    $mc = new midgard_collector('midgard_person', 'id', 1);
304
                    $mc->set_key_property('guid');
305
                    $mc->execute();
306
                    $root_user_guid = key($mc->list_keys()) ?: 'f6b665f1984503790ed91f39b11b5392';
307
                }
308
309 80
                return $root_user_guid;
310
            }
311 65
            return $this->__metadata->$key;
312
        }
313 266
        if (!in_array($key, $this->field_config['other'])) {
314
            // Fall-back for non-core properties
315 97
            $dm = $this->get_datamanager();
316 97
            if (!$dm->get_schema()->has_field($key)) {
317
                // Fall back to the parameter reader for non-core MidCOM metadata params
318 95
                return $this->__object->get_parameter('midcom.helper.metadata', $key);
319
            }
320 2
            return $dm->get_content_csv()[$key];
321
        }
322 250
        return $this->__metadata->$key;
323
    }
324
325
    /* ------- CONVENIENCE METADATA INTERFACE --------- */
326
327
    /**
328
     * Checks whether the object has been approved since its last editing.
329
     */
330
    public function is_approved() : bool
331
    {
332
        return $this->__object->is_approved();
333
    }
334
335
    /**
336
     * Checks the object's visibility regarding scheduling and the hide flag.
337
     *
338
     * This does not check approval, use is_approved for that.
339
     *
340
     * @see midcom_helper_metadata::is_approved()
341
     */
342
    public function is_visible() : bool
343
    {
344
        if ($this->get('hidden')) {
345
            return false;
346
        }
347
348
        $now = time();
349
        if (   $this->get('schedulestart')
350
            && $this->get('schedulestart') > $now) {
351
            return false;
352
        }
353
        if (   $this->get('scheduleend')
354
            && $this->get('scheduleend') < $now) {
355
            return false;
356
        }
357
        return true;
358
    }
359
360
    /**
361
     * This is a helper function which indicates whether a given object may be shown onsite
362
     * taking approval, scheduling and visibility settings into account. The important point
363
     * here is that it also checks the global configuration defaults, so that this is
364
     * basically the same base on which NAP decides whether to show an item or not.
365
     */
366 126
    public function is_object_visible_onsite() : bool
367
    {
368
        return
369 126
        (   (   midcom::get()->config->get('show_hidden_objects')
370 126
             || $this->is_visible())
371 126
         && (   midcom::get()->config->get('show_unapproved_objects')
372 126
             || $this->is_approved())
373
        );
374
    }
375
376
    /**
377
     * Approves the object.
378
     *
379
     * This sets the approved timestamp to the current time and the
380
     * approver person GUID to the GUID of the person currently
381
     * authenticated.
382
     */
383 1
    public function approve() : bool
384
    {
385 1
        midcom::get()->auth->require_do('midcom:approve', $this->__object);
386 1
        midcom::get()->auth->require_do('midgard:update', $this->__object);
387 1
        return $this->__object->approve();
388
    }
389
390
    /**
391
     * Unapproves the object.
392
     *
393
     * This resets the approved timestamp and sets the
394
     * approver person GUID to the GUID of the person currently
395
     * authenticated.
396
     */
397 1
    public function unapprove() : bool
398
    {
399 1
        midcom::get()->auth->require_do('midcom:approve', $this->__object);
400 1
        midcom::get()->auth->require_do('midgard:update', $this->__object);
401 1
        return $this->__object->unapprove();
402
    }
403
404
    /* ------- CLASS MEMBER FUNCTIONS ------- */
405
406
    /**
407
     * Returns a metadata object for a given content object.
408
     *
409
     * You may bass any one of the following arguments to the function:
410
     *
411
     * - Any class derived from MidgardObject, you must only ensure, that the parameter
412
     *   and guid member functions stays available.
413
     * - Any valid GUID
414
     *
415
     * @param mixed $source The object to attach to, this may be either a MidgardObject or a GUID.
416
     */
417 51
    public static function retrieve($source) : ?self
418
    {
419 51
        $object = null;
420
421 51
        if (is_object($source)) {
422 51
            $object = $source;
423 51
            $guid = $source->guid;
424
        } else {
425
            $guid = $source;
426
        }
427
428 51
        if (   $object === null
429 51
            && mgd_is_guid($guid)) {
430
            try {
431
                $object = midcom::get()->dbfactory->get_object_by_guid($guid);
432
            } catch (midcom_error $e) {
433
                debug_add("Failed to create a metadata instance for the GUID {$guid}: " . $e->getMessage(), MIDCOM_LOG_WARN);
434
                debug_print_r("Source was:", $source);
435
436
                return null;
437
            }
438
        }
439
440
        // $object is now populated, too
441 51
        return new self($object);
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type null; however, parameter $object of midcom_helper_metadata::__construct() does only seem to accept midcom_core_dbaobject, 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

441
        return new self(/** @scrutinizer ignore-type */ $object);
Loading history...
442
    }
443
444
    /**
445
     * Check if the requested object is locked
446
     */
447 89
    public function is_locked() : bool
448
    {
449
        // Object hasn't been marked to be edited
450 89
        if ($this->get('locked') == 0) {
451 58
            return false;
452
        }
453
454 31
        if (($this->get('locked') + (midcom::get()->config->get('metadata_lock_timeout') * 60)) < time()) {
455
            // lock expired, explicitly clear lock
456
            $this->unlock();
457
            return false;
458
        }
459
460
        // Lock was created by the user, return "not locked"
461 31
        if (   !empty(midcom::get()->auth->user->guid)
462 31
            && $this->get('locker') === midcom::get()->auth->user->guid) {
463 30
            return false;
464
        }
465
466
        // Unlocked states checked and none matched, consider locked
467 1
        return $this->__object->is_locked();
468
    }
469
470
    /**
471
     * Set the object lock
472
     *
473
     * @return boolean       Indicating success
474
     */
475 44
    public function lock() : bool
476
    {
477 44
        midcom::get()->auth->require_do('midgard:update', $this->__object);
478
479 44
        if ($this->__object->lock()) {
480 32
            $this->_cache = [];
481 32
            return true;
482
        }
483
484 12
        return false;
485
    }
486
487
    /**
488
     * Check whether current user can unlock the object
489
     *
490
     * @todo enable specifying user ?
491
     */
492 14
    public function can_unlock() : bool
493
    {
494 14
        return (   $this->__object->can_do('midcom:unlock')
495 14
                || midcom::get()->auth->can_user_do('midcom:unlock', null, midcom_services_auth::class));
496
    }
497
498
    /**
499
     * Unlock the object
500
     *
501
     * @return boolean    Indicating success
502
     */
503 13
    public function unlock() : bool
504
    {
505 13
        if (   $this->can_unlock()
506 13
            && $this->__object->unlock()) {
507 12
            $this->_cache = [];
508 12
            return true;
509
        }
510
511 1
        return false;
512
    }
513
}
514