Configured the removal of old files that were not attached to the model or were marked as deleted.

This commit is contained in:
2024-07-26 22:18:01 +05:00
parent dde792b97a
commit c84ed9f12b
10 changed files with 235 additions and 8 deletions

View File

@@ -0,0 +1,50 @@
<?php declare(strict_types=1);
namespace App\Console\Commands\Files;
use App\Services\Commands\DeleteOldFilesService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
final class DeleteOldFilesFromStorage extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'files:delete-old-files-from-storage';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Remove temporary files or files that have been deleted from the storage table';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle(DeleteOldFilesService $deleteOldFilesService): void
{
$temporaryBeforeDate = Carbon::now()->subDays(3);
$deletedBeforeDate = Carbon::now()->subDays(7);
$result = $deleteOldFilesService->fromStorage($temporaryBeforeDate, $deletedBeforeDate);
if ($result->isError()) {
$this->error($result->getMessage());
return;
}
$this->info($result->getMessage());
}
}

View File

@@ -0,0 +1,46 @@
<?php declare(strict_types=1);
namespace App\Services\Commands;
use App\Models\Storage as StorageModel;
use App\ServiceResults\ServiceResultError;
use App\ServiceResults\ServiceResultSuccess;
use App\Services\Service;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage as StorageSupport;
final class DeleteOldFilesService extends Service
{
/**
* $temporaryBeforeDate = date of deletion of temporary files
* $deletedBeforeDate = date of deletion files that were marked as deleted
*
* @param Carbon $temporaryBeforeDate
* @param Carbon $deletedBeforeDate
* @return ServiceResultError|ServiceResultSuccess
*/
public function fromStorage(Carbon $temporaryBeforeDate, Carbon $deletedBeforeDate): ServiceResultError|ServiceResultSuccess
{
$disk = config('storage.disk');
StorageModel::withTrashed()
->where(function (Builder $query) use($temporaryBeforeDate) {
$query->whereNull('morph_id')->where('updated_at', '<', $temporaryBeforeDate);
})->orWhere(function (Builder $query) use($deletedBeforeDate) {
$query->whereNotNull('deleted_at')->where('deleted_at', '<', $deletedBeforeDate);
})->chunkById(100, function ($items) use($disk) {
$deleteIds = [];
foreach ($items as $item) {
$deleteIds[] = $item->id;
if (StorageSupport::disk($disk)->exists($item->file)) {
StorageSupport::disk($disk)->delete($item->file);
}
}
StorageModel::withTrashed()->whereIn('id', $deleteIds)->forceDelete();
});
return $this->ok(__('Old Files deleted.'));
}
}