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

CascadeDelete::handle()   C

Complexity

Conditions 7
Paths 36

Size

Total Lines 38
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 36
nop 0
dl 0
loc 38
rs 6.7272
c 0
b 0
f 0
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