1: <?php
2:
3: namespace Baril\Bonsai\Concerns;
4:
5: use Illuminate\Database\Eloquent\SoftDeletes as EloquentSoftDeletes;
6:
7: trait 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: }
69: