summaryrefslogtreecommitdiff
path: root/app/Console/Commands/CleanupExpiredFiles.php
blob: cbf840df9591528dce21c154025eb906981d1adf (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

namespace App\Console\Commands;

use App\Models\File;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class CleanupExpiredFiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'files:cleanup-expired
                            {--dry-run : Show what would be deleted without actually deleting}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete expired files and update expiration flags';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $isDryRun = $this->option('dry-run');

        // Update is_expired flag for files past expiration
        $this->updateExpiredFlags();

        // Get expired files
        $expiredFiles = File::where('is_expired', true)
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->get();

        $this->info("Found {$expiredFiles->count()} expired files");

        foreach ($expiredFiles as $file) {
            if ($isDryRun) {
                $this->line("Would delete: {$file->filename_og}");
                continue;
            }

            // Delete physical file
            try {
                Storage::disk($file->disk)->delete($file->storage_path);
                $this->info("Deleted file: {$file->filename_og}");
            } catch (\Exception $e) {
                $this->error("Failed to delete file {$file->filename_og}: {$e->getMessage()}");
            }

            // Soft delete database record
            $file->delete();
        }

        if (!$isDryRun) {
            $this->info("Cleanup complete. Deleted {$expiredFiles->count()} files.");
        }

        return 0;
    }

    /**
     * Update is_expired flags for files past their expiration date
     */
    protected function updateExpiredFlags()
    {
        $updated = File::whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->where('is_expired', false)
            ->update(['is_expired' => true]);

        if ($updated > 0) {
            $this->info("Updated {$updated} files as expired");
        }
    }
}