1 | <?php |
||
9 | trait CascadeSoftDeletes |
||
10 | { |
||
11 | /** |
||
12 | * Boot the trait. |
||
13 | * |
||
14 | * Listen for the deleting event of a soft deleting model, and run |
||
15 | * the delete operation for any configured relationship methods. |
||
16 | * |
||
17 | * @throws \LogicException |
||
18 | */ |
||
19 | 10 | protected static function bootCascadeSoftDeletes() |
|
20 | { |
||
21 | static::deleting(function ($model) { |
||
22 | 10 | if (! $model->implementsSoftDeletes()) { |
|
23 | 1 | throw new LogicException(sprintf( |
|
24 | 1 | '%s does not implement Illuminate\Database\Eloquent\SoftDeletes', |
|
25 | get_called_class() |
||
26 | )); |
||
27 | } |
||
28 | |||
29 | 9 | if ($invalidCascadingRelationships = $model->hasInvalidCascadingRelationships()) { |
|
30 | 3 | throw new LogicException(sprintf( |
|
31 | 3 | '%s [%s] must exist and return an object of type Illuminate\Database\Eloquent\Relations\Relation', |
|
32 | 3 | str_plural('Relationship', count($invalidCascadingRelationships)), |
|
33 | 3 | join(', ', $invalidCascadingRelationships) |
|
34 | )); |
||
35 | } |
||
36 | |||
37 | 6 | $delete = $model->forceDeleting ? 'forceDelete' : 'delete'; |
|
38 | |||
39 | 6 | foreach ($model->getActiveCascadingDeletes() as $relationship) { |
|
40 | 6 | if ($model->{$relationship} instanceof Model) { |
|
41 | 1 | $model->{$relationship}->{$delete}(); |
|
42 | } else { |
||
43 | 6 | foreach ($model->{$relationship} as $child) { |
|
44 | 6 | $child->{$delete}(); |
|
45 | } |
||
46 | } |
||
47 | } |
||
48 | 9 | }); |
|
49 | 7 | } |
|
50 | |||
51 | |||
52 | /** |
||
53 | * Determine if the current model implements soft deletes. |
||
54 | * |
||
55 | * @return bool |
||
56 | */ |
||
57 | 10 | protected function implementsSoftDeletes() |
|
61 | |||
62 | |||
63 | /** |
||
64 | * Determine if the current model has any invalid cascading relationships defined. |
||
65 | * |
||
66 | * A relationship is considered invalid when the method does not exist, or the relationship |
||
67 | * method does not return an instance of Illuminate\Database\Eloquent\Relations\Relation. |
||
68 | * |
||
69 | * @return array |
||
70 | */ |
||
71 | 9 | protected function hasInvalidCascadingRelationships() |
|
77 | |||
78 | |||
79 | /** |
||
80 | * Fetch the defined cascading soft deletes for this model. |
||
81 | * |
||
82 | * @return array |
||
83 | */ |
||
84 | 9 | protected function getCascadingDeletes() |
|
88 | |||
89 | |||
90 | /** |
||
91 | * For the cascading deletes defined on the model, return only those that are not null. |
||
92 | * |
||
93 | * @return array |
||
94 | */ |
||
95 | protected function getActiveCascadingDeletes() |
||
101 | } |
||
102 |