/
DeleteRecordPolicy.php
103 lines (91 loc) · 2.83 KB
/
DeleteRecordPolicy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace TractorCow\Fluent\Model\Delete;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\Queries\SQLDelete;
use TractorCow\Fluent\State\FluentState;
/**
* A policy that deletes the root record
*/
class DeleteRecordPolicy implements DeletePolicy
{
/**
* List of dependant policies
*
* @var DeletePolicy[]
*/
protected $dependantPolicies = [];
/**
* @return DeletePolicy[]
*/
public function getDependantPolicies()
{
return $this->dependantPolicies;
}
/**
* @param DeletePolicy[] $dependantPolicies
* @return $this
*/
public function setDependantPolicies($dependantPolicies)
{
$this->dependantPolicies = $dependantPolicies;
return $this;
}
/**
* @param DataObject $record
* @return bool Determines if any dependent objects block upstream deletion (e.g. db / model constraints)
* If this returns true, then there are additional conditions that must be satisfied before
* upstream relational constraints are safe to delete.
* If this returns true, then all downstream entities are reported purged, and upstream
* relational constraints can be deleted.
*/
public function delete(DataObject $record)
{
$blocked = false;
foreach ($this->getDependantPolicies() as $filter) {
$blocked = $filter->delete($record) || $blocked;
}
// Blocked by upstream policy
if ($blocked) {
return true;
}
// Delete base record
$this->deleteBaseRecord($record);
return false;
}
/**
* Do base record deletion
*
* @param DataObject $record
*/
protected function deleteBaseRecord(DataObject $record)
{
$queriedTables = $this->getTargetTables($record);
foreach ($queriedTables as $table) {
$delete = SQLDelete::create("\"{$table}\"", array('"ID"' => $record->ID));
$delete->execute();
}
}
/**
* Generate table list to delete base record
*
* @param DataObject $record
* @return mixed
*/
protected function getTargetTables(DataObject $record)
{
return FluentState::singleton()
->withState(
function (FluentState $state) use ($record) {
// Disable fluent and delete unlocalised record only
$state->setLocale(null);
// Copy DataObject::delete() here for now
$srcQuery = DataList::create(get_class($record))
->filter('ID', $record->ID)
->dataQuery()
->query();
return $srcQuery->queriedTables();
}
);
}
}