Prunable.php
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace Illuminate\Database\Eloquent;
use Illuminate\Database\Events\ModelsPruned;
use LogicException;
trait Prunable
{
/**
* Prune all prunable models in the database.
*
* @param int $chunkSize
* @return int
*/
public function pruneAll(int $chunkSize = 1000)
{
$total = 0;
$this->prunable()
->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($this))), function ($query) {
$query->withTrashed();
})->chunkById($chunkSize, function ($models) use (&$total) {
$models->each->prune();
$total += $models->count();
event(new ModelsPruned(static::class, $total));
});
return $total;
}
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
throw new LogicException('Please implement the prunable method on your model.');
}
/**
* Prune the model in the database.
*
* @return bool|null
*/
public function prune()
{
$this->pruning();
return in_array(SoftDeletes::class, class_uses_recursive(get_class($this)))
? $this->forceDelete()
: $this->delete();
}
/**
* Prepare the model for pruning.
*
* @return void
*/
protected function pruning()
{
//
}
}