PruneOutdatedFiles   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 54
ccs 19
cts 19
cp 1
rs 10
c 2
b 0
f 0
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A filterExtension() 0 3 1
A handle() 0 15 5
A filterSeconds() 0 3 1
A needDeleteFile() 0 10 6
1
<?php
2
3
namespace LaravelDownloadUtil\Console\Commands;
4
5
use Carbon\Carbon;
6
use Illuminate\Console\Command;
7
use Illuminate\Contracts\Filesystem\Filesystem;
8
use Illuminate\Support\Facades\Storage;
9
use Illuminate\Support\Str;
10
11
class PruneOutdatedFiles extends Command
12
{
13
    protected $signature = 'download-util:prune-outdated
14
    {disk? : Storage disk name}
15
    {--S|seconds= : Delete files older than this amount of seconds}
16
    {--E|extension= : Delete files older than this amount of seconds}
17
    ';
18
19
    protected $description = 'Delete outdated files';
20
21
    protected Filesystem $storage;
22
23
    protected string $filterExtension = '';
24
25
    protected int $filterSeconds = 0;
26
27
28 3
    public function handle(): int
29
    {
30 3
        $disk                  = $this->argument('disk') ?: config('download-util.storage.default');
31 3
        $this->storage         = Storage::disk($disk);
32 3
        $this->filterExtension = (string) $this->option('extension');
33 3
        $this->filterSeconds   = (int) $this->option('seconds');
34
35
        /** @var $file */
36 3
        foreach ($this->storage->allFiles() as $file) {
37 3
            if ($this->needDeleteFile($file) && $this->storage->delete($file)) {
38 2
                $this->info("Deleted: {$file}");
39
            }
40
        }
41
42 3
        return 0;
43
    }
44
45 3
    protected function needDeleteFile(string $file): bool
46
    {
47 3
        if ($this->filterSeconds && !$this->filterSeconds($file)) {
48 1
            return false;
49
        }
50 3
        if ($this->filterExtension && !$this->filterExtension($file)) {
51 1
            return false;
52
        }
53
54 3
        return $this->filterSeconds || $this->filterExtension;
55
    }
56
57 1
    protected function filterSeconds(string $file): bool
58
    {
59 1
        return Carbon::createFromTimestamp($this->storage->lastModified($file))->lessThan(Carbon::now()->subSeconds($this->filterSeconds));
60
    }
61
62 1
    protected function filterExtension(string $file): bool
63
    {
64 1
        return Str::endsWith($file, '.'.ltrim($this->filterExtension, '.'));
65
    }
66
}
67