Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
SoftDeletes
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
3 / 3
4
100.00% covered (success)
100.00%
1 / 1
 bootSoftDeletes
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 forceDeleteTree
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 restoreTree
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace Baril\Bonsai\Concerns;
4
5use Illuminate\Database\Eloquent\SoftDeletes as EloquentSoftDeletes;
6
7trait SoftDeletes
8{
9    use EloquentSoftDeletes {
10        bootSoftDeletes as _bootSoftDeletes;
11    }
12
13    public static function bootSoftDeletes()
14    {
15        static::_bootSoftDeletes();
16
17        // When we're force deleting, we need to delete the closures before
18        // the node is deleted, because the ON CASCADE would delete the node's
19        // closure and we wouldn't be able to detach its ancestors any more.
20        // @todo replace with forceDeleting in v4 and remove if
21        static::deleting(function ($item) {
22            if ($item->forceDeleting) {
23                $item->deleteClosures('>=');
24            }
25        });
26    }
27
28    /**
29     * Force a hard delete on a soft deleted model and its descendants.
30     *
31     * @param  bool  $withTrashed
32     * @return int
33     */
34    public function forceDeleteTree($withTrashed = true)
35    {
36        return $this
37            ->descendants()
38            ->withSelf()
39            ->when($withTrashed, function ($query) {
40                $query->withTrashed();
41            })
42            ->orderByDepth('desc')
43            ->select($this->getKeyName())
44            ->cursor()
45            ->map
46            ->forceDelete()
47            ->sum();
48    }
49
50    /**
51     * Restore the model and its soft-deleted descendants.
52     *
53     * @return int
54     */
55    public function restoreTree()
56    {
57        return $this
58            ->descendants()
59            ->withSelf()
60            ->withTrashed()
61            ->orderByDepth('asc')
62            ->select($this->getKeyName())
63            ->cursor()
64            ->map
65            ->restore()
66            ->sum();
67    }
68}