Completed
Push — master ( 98a062...441031 )
by Ryan
10:10
created

CascadeDelete   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C handle() 0 38 7
1
<?php namespace Anomaly\Streams\Platform\Model\Command;
2
3
use Anomaly\Streams\Platform\Model\EloquentCollection;
4
use Anomaly\Streams\Platform\Model\EloquentModel;
5
use Illuminate\Database\Eloquent\Relations\Relation;
6
7
/**
8
 * Class CascadeDelete
9
 *
10
 * @link   http://pyrocms.com/
11
 * @author PyroCMS, Inc. <[email protected]>
12
 * @author Ryan Thompson <[email protected]>
13
 */
14
class CascadeDelete
15
{
16
17
    /**
18
     * The eloquent model.
19
     *
20
     * @var EloquentModel
21
     */
22
    protected $model;
23
24
    /**
25
     * Create a new CascadeDelete instance.
26
     *
27
     * @param EloquentModel $model
28
     */
29
    public function __construct(EloquentModel $model)
30
    {
31
        $this->model = $model;
32
    }
33
34
    /**
35
     * Handle the command.
36
     */
37
    public function handle()
38
    {
39
        $action = $this->model->isForceDeleting() ? 'forceDelete' : 'delete';
40
41
        /**
42
         * If the model itself can not be trashed
43
         * then we have no reason to keep any
44
         * relations that cascade.
45
         */
46
        if (!method_exists($this->model, 'restore')) {
47
            $action = 'forceDelete';
48
        }
49
50
        foreach ($this->model->getCascades() as $relation) {
51
52
            /* @var Relation $relation */
53
            $relation = $this->model->{$relation}();
54
55
            if ($action == 'forceDelete') {
56
                $relation = $relation->withTrashed();
57
            }
58
59
            $relation = $relation->getResults();
60
61
            if ($relation instanceof EloquentModel) {
62
                $relation->{$action}();
63
            }
64
65
            if ($relation instanceof EloquentCollection) {
66
67
                $relation->each(
68
                    function (EloquentModel $item) use ($action) {
69
                        $item->{$action}();
70
                    }
71
                );
72
            }
73
        }
74
    }
75
}
76