EntityWasDeleted   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 29
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 19 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Attributes\Events;
6
7
use Rinvex\Attributes\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()) {
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
                // Calling the `destroy` method from the given $type model class name
33
                // will finally delete the records from database if any was found.
34
                // We'll just provide an array containing the ids to be deleted.
35
                forward_static_call_array([Attribute::getTypeModel($attribute->getAttribute('type')), 'destroy'], [$values->pluck('id')->toArray()]);
36
            }
37
        }
38
    }
39
}
40