MediaGarbageCollector.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\{Media, Status};
  5. use Carbon\Carbon;
  6. class MediaGarbageCollector extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'media:gc';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Delete media uploads not attached to any active statuses';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return mixed
  33. */
  34. public function handle()
  35. {
  36. $limit = 20000;
  37. $gc = Media::doesntHave('status')
  38. ->where('created_at', '<', Carbon::now()->subHours(1)->toDateTimeString())
  39. ->orderBy('created_at','asc')
  40. ->take($limit)
  41. ->get();
  42. $bar = $this->output->createProgressBar($gc->count());
  43. $bar->start();
  44. foreach($gc as $media) {
  45. $path = storage_path("app/$media->media_path");
  46. $thumb = storage_path("app/$media->thumbnail_path");
  47. if(is_file($path)) {
  48. unlink($path);
  49. }
  50. if(is_file($thumb)) {
  51. unlink($thumb);
  52. }
  53. $media->forceDelete();
  54. $bar->advance();
  55. }
  56. $bar->finish();
  57. }
  58. }