|
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, 'getNew')) { |
|
31
|
|
|
$record = $this->getNew(); |
|
32
|
|
|
|
|
33
|
|
|
if (method_exists($record, 'usesTimestamps')) { |
|
34
|
|
|
return $record->usesTimestamps(); |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
return $this->usesTimestampsDefaultTrait(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
protected function hookTimestampableIntoLifecycle() |
|
41
|
|
|
{ |
|
42
|
|
|
$updateCallback = function ($record, $manager, $type) { |
|
43
|
|
|
if (method_exists($record, 'getTimestampAttributes')) { |
|
44
|
|
|
$attributes = $record->getTimestampAttributes($type); |
|
45
|
|
|
} elseif (method_exists($manager, 'getTimestampAttributes')) { |
|
46
|
|
|
$attributes = $this->getTimestampAttributes($type); |
|
47
|
|
|
} else { |
|
48
|
|
|
$attributes = []; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** @var TimestampableTrait $record */ |
|
52
|
|
|
$record->updatedTimestamps($attributes); |
|
53
|
|
|
}; |
|
54
|
|
|
|
|
55
|
|
|
$events = ['creating' => 'create', 'updating' => 'update']; |
|
56
|
|
|
foreach ($events as $event => $type) { |
|
57
|
|
|
if (is_callable('static::' . $event) == false) { |
|
|
|
|
|
|
58
|
|
|
continue; |
|
59
|
|
|
} |
|
60
|
|
|
static::$event( |
|
61
|
|
|
function (Event $event) use ($updateCallback, $type) { |
|
62
|
|
|
$record = $event->getRecord(); |
|
63
|
|
|
/** @var static|RecordManager $manager */ |
|
64
|
|
|
$manager = $event->getManager(); |
|
65
|
|
|
$updateCallback($record, $manager, $type); |
|
66
|
|
|
} |
|
67
|
|
|
); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
When comparing two booleans, it is generally considered safer to use the strict comparison operator.