hookTimestampableIntoLifecycle()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 17
c 1
b 0
f 1
nc 3
nop 0
dl 0
loc 26
rs 9.3888
1
<?php
2
3
namespace ByTIC\DataObjects\Behaviors\Timestampable;
4
5
use Nip\Records\AbstractModels\RecordManager;
6
use Nip\Records\EventManager\Events\Event;
7
8
/**
9
 * Trait TimestampableManagerTrait
10
 * @package ByTIC\DataObjects\Behaviors\Timestampable
11
 */
12
trait TimestampableManagerTrait
13
{
14
    use TimestampableTrait {
15
        usesTimestampsDefault as usesTimestampsDefaultTrait;
16
    }
17
18
    public function bootTimestampableManagerTrait()
19
    {
20
        if ($this->usesTimestamps()) {
21
            $this->hookTimestampableIntoLifecycle();
22
        }
23
    }
24
25
    /**
26
     * @inheritDoc
27
     */
28
    public function usesTimestampsDefault(): bool
29
    {
30
        if (method_exists($this, 'getModel')) {
31
            $recordClass = $this->getModel();
32
            $record = new $recordClass();
33
34
            if (method_exists($recordClass, 'usesTimestamps')) {
35
                return $record->usesTimestamps();
36
            }
37
        }
38
        return $this->usesTimestampsDefaultTrait();
39
    }
40
41
    protected function hookTimestampableIntoLifecycle()
42
    {
43
        $updateCallback = function ($record, $manager, $type) {
44
            if (method_exists($record, 'getTimestampAttributes')) {
45
                $attributes = $record->getTimestampAttributes($type);
46
            } elseif (method_exists($manager, 'getTimestampAttributes')) {
47
                $attributes = $this->getTimestampAttributes($type);
48
            } else {
49
                $attributes = [];
50
            }
51
52
            /** @var TimestampableTrait $record */
53
            $record->updatedTimestamps($attributes);
54
        };
55
56
        $events = ['creating' => 'create', 'updating' => 'update'];
57
        foreach ($events as $event => $type) {
58
            if (is_callable('static::' . $event) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
59
                continue;
60
            }
61
            static::$event(
62
                function (Event $event) use ($updateCallback, $type) {
63
                    $record = $event->getRecord();
64
                    /** @var static|RecordManager $manager */
65
                    $manager = $event->getManager();
66
                    $updateCallback($record, $manager, $type);
67
                }
68
            );
69
        }
70
    }
71
}
72