Skip to content

Commit 17e6484

Browse files
Ensure no deletes are performed if invalid relationships are defined
1 parent 514301f commit 17e6484

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

src/CascadeSoftDeletes.php

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
namespace Iatstuti\Database\Support;
44

5-
use Illuminate\Database\Eloquent\SoftDeletes;
65
use Illuminate\Database\Eloquent\Relations\Relation;
6+
use LogicException;
77

88
trait CascadeSoftDeletes
99
{
@@ -19,20 +19,21 @@ protected static function bootCascadeSoftDeletes()
1919
{
2020
static::deleting(function ($model) {
2121
if (! $model->implementsSoftDeletes()) {
22-
throw new RuntimeException(sprintf(
22+
throw new LogicException(sprintf(
2323
'%s does not implement Illuminate\Database\Eloquent\SoftDeletes',
2424
get_called_class()
2525
));
2626
}
2727

28-
foreach ($model->cascadeDeletes as $relationship) {
29-
if (! $model->{$relationship}() instanceof Relation) {
30-
throw new LogicException(sprintf(
31-
'Relationship [%s] must return an object of type Illuminate\Database\Eloquent\SoftDeletes',
32-
$relationship
33-
));
34-
}
28+
if ($invalidCascadingRelationships = $model->hasInvalidCascadingRelationships()) {
29+
throw new LogicException(sprintf(
30+
'%s [%s] must return an object of type Illuminate\Database\Eloquent\Relations\Relation',
31+
str_plural('Relationship', count($invalidCascadingRelationships)),
32+
join(', ', $invalidCascadingRelationships)
33+
));
34+
}
3535

36+
foreach ($model->cascadeDeletes as $relationship) {
3637
$model->{$relationship}()->delete();
3738
}
3839
});
@@ -49,4 +50,16 @@ protected function implementsSoftDeletes()
4950
return in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this));
5051
}
5152

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+
return collect($this->cascadeDeletes)->filter(function ($relationship) {
62+
return ! $this->{$relationship}() instanceof Relation;
63+
})->toArray();
64+
}
5265
}

0 commit comments

Comments
 (0)