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) { |
|
|
|
|
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
|
|
|
|
When comparing two booleans, it is generally considered safer to use the strict comparison operator.