EntityWasDeleted::handle()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.6666
c 0
b 0
f 0
cc 7
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Audit\Events;
6
7
use Pedreiro\Models\Attribute;
8
use Illuminate\Database\Eloquent\SoftDeletes;
9
use Illuminate\Database\Eloquent\Model as Entity;
10
11
class EntityWasDeleted
12
{
13
    /**
14
     * Handle the entity deletion.
15
     *
16
     * @param \Illuminate\Database\Eloquent\Model $entity
17
     *
18
     * @return void
19
     */
20
    public function handle(Entity $entity): void
21
    {
22
        // We will initially check if the model is using soft deletes. If so,
23
        // the attribute values will remain untouched as they should sill
24
        // be available till the entity is truly deleted from database.
25
        if (in_array(SoftDeletes::class, class_uses_recursive(get_class($entity))) && ! $entity->isForceDeleting()) {
0 ignored issues
show
Bug introduced by
The method isForceDeleting() does not exist on Illuminate\Database\Eloquent\Model. Did you maybe mean deleting()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
26
            return;
27
        }
28
29
        foreach ($entity->getEntityAttributes() as $attribute) {
30
            if ($entity->relationLoaded($relation = $attribute->getAttribute('slug'))
31
                && ($values = $entity->getRelationValue($relation)) && ! $values->isEmpty()
32
            ) {
33
                // Calling the `destroy` method from the given $type model class name
34
                // will finally delete the records from database if any was found.
35
                // We'll just provide an array containing the ids to be deleted.
36
                forward_static_call_array([Attribute::getTypeModel($attribute->getAttribute('type')), 'destroy'], [$values->pluck('id')->toArray()]);
37
            }
38
        }
39
    }
40
}
41