1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Iatstuti\Database\Support; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
6
|
|
|
use LogicException; |
7
|
|
|
|
8
|
|
|
trait CascadeSoftDeletes |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Boot the trait. |
12
|
|
|
* |
13
|
|
|
* Listen for the deleting event of a soft deleting model, and run |
14
|
|
|
* the delete operation for any configured relationship methods. |
15
|
|
|
* |
16
|
|
|
* @throws \RuntimeException |
17
|
|
|
*/ |
18
|
4 |
|
protected static function bootCascadeSoftDeletes() |
19
|
|
|
{ |
20
|
|
|
static::deleting(function ($model) { |
21
|
4 |
|
if (! $model->implementsSoftDeletes()) { |
22
|
1 |
|
throw new LogicException(sprintf( |
23
|
1 |
|
'%s does not implement Illuminate\Database\Eloquent\SoftDeletes', |
24
|
1 |
|
get_called_class() |
25
|
1 |
|
)); |
26
|
|
|
} |
27
|
|
|
|
28
|
3 |
|
if ($invalidCascadingRelationships = $model->hasInvalidCascadingRelationships()) { |
29
|
2 |
|
throw new LogicException(sprintf( |
30
|
2 |
|
'%s [%s] must return an object of type Illuminate\Database\Eloquent\Relations\Relation', |
31
|
2 |
|
str_plural('Relationship', count($invalidCascadingRelationships)), |
32
|
2 |
|
join(', ', $invalidCascadingRelationships) |
33
|
2 |
|
)); |
34
|
|
|
} |
35
|
|
|
|
36
|
1 |
|
foreach ($model->cascadeDeletes as $relationship) { |
37
|
1 |
|
$model->{$relationship}()->delete(); |
38
|
1 |
|
} |
39
|
3 |
|
}); |
40
|
3 |
|
} |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Determine if the current model implements soft deletes. |
45
|
|
|
* |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
4 |
|
protected function implementsSoftDeletes() |
49
|
|
|
{ |
50
|
4 |
|
return in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this)); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Determine if the current model has any invalid cascading relationships defined. |
56
|
|
|
* |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
protected function hasInvalidCascadingRelationships() |
60
|
|
|
{ |
61
|
3 |
|
return collect($this->cascadeDeletes)->filter(function ($relationship) { |
|
|
|
|
62
|
3 |
|
return ! $this->{$relationship}() instanceof Relation; |
63
|
3 |
|
})->toArray(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: