1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Analogue\ORM\Plugins\SoftDeletes; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
use Analogue\ORM\System\Mapper; |
7
|
|
|
use Analogue\ORM\Plugins\AnaloguePlugin; |
8
|
|
|
use Analogue\ORM\System\Wrappers\Factory; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* This Plugin enables a softDeletes behaviour equivalent |
12
|
|
|
* to Eloquent ORM. |
13
|
|
|
*/ |
14
|
|
|
class SoftDeletesPlugin extends AnaloguePlugin |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Register the plugin |
18
|
|
|
* |
19
|
|
|
* @throws \Exception |
20
|
|
|
* @return void |
21
|
|
|
*/ |
22
|
|
|
public function register() |
23
|
|
|
{ |
24
|
|
|
$host = $this; |
25
|
|
|
|
26
|
|
|
// Hook any mapper init and check the mapping include soft deletes. |
27
|
|
|
$this->manager->registerGlobalEvent('initialized', function (Mapper $mapper) use ($host) { |
28
|
|
|
$entityMap = $mapper->getEntityMap(); |
29
|
|
|
|
30
|
|
|
if ($entityMap->usesSoftDeletes()) { |
31
|
|
|
$host->registerSoftDelete($mapper); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
}); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* By hooking to the mapper initialization event, we can extend it |
39
|
|
|
* with the softDelete capacity. |
40
|
|
|
* |
41
|
|
|
* @param \Analogue\ORM\System\Mapper $mapper |
42
|
|
|
* @throws \Analogue\ORM\Exceptions\MappingException |
43
|
|
|
* @return bool|void |
44
|
|
|
*/ |
45
|
|
|
protected function registerSoftDelete(Mapper $mapper) |
46
|
|
|
{ |
47
|
|
|
$entityMap = $mapper->getEntityMap(); |
48
|
|
|
|
49
|
|
|
// Add Scopes |
50
|
|
|
$mapper->addGlobalScope(new SoftDeletingScope); |
51
|
|
|
|
52
|
|
|
$host = $this; |
53
|
|
|
|
54
|
|
|
// Register 'deleting' events |
55
|
|
|
$mapper->registerEvent('deleting', function ($entity) use ($entityMap, $host) { |
56
|
|
|
|
57
|
|
|
// Convert Entity into an EntityWrapper |
58
|
|
|
$factory = new Factory; |
59
|
|
|
|
60
|
|
|
$wrappedEntity = $factory->make($entity); |
61
|
|
|
|
62
|
|
|
$deletedAtField = $entityMap->getQualifiedDeletedAtColumn(); |
63
|
|
|
|
64
|
|
|
if (!is_null($wrappedEntity->getEntityAttribute($deletedAtField))) { |
65
|
|
|
return true; |
66
|
|
|
} else { |
67
|
|
|
$time = new Carbon; |
68
|
|
|
|
69
|
|
|
$wrappedEntity->setEntityAttribute($deletedAtField, $time); |
70
|
|
|
|
71
|
|
|
$plainObject = $wrappedEntity->getObject(); |
72
|
|
|
$host->manager->mapper(get_class($plainObject))->store($plainObject); |
73
|
|
|
|
74
|
|
|
return false; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
}); |
78
|
|
|
|
79
|
|
|
// Register RestoreCommand |
80
|
|
|
$mapper->addCustomCommand('Analogue\ORM\Plugins\SoftDeletes\Restore'); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Get custom events provided by the plugin |
85
|
|
|
* |
86
|
|
|
* @return string[] |
87
|
|
|
*/ |
88
|
|
|
public function getCustomEvents() |
89
|
|
|
{ |
90
|
|
|
return ['restoring', 'restored']; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|