Prunable.php 1.4 KB

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