|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\DirectoryCleanup; |
|
4
|
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
|
6
|
|
|
use Illuminate\Support\Collection; |
|
7
|
|
|
use Illuminate\Filesystem\Filesystem; |
|
8
|
|
|
use Spatie\DirectoryCleanup\Policies\CleanupPolicy; |
|
9
|
|
|
|
|
10
|
|
|
class DirectoryCleaner |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var \Illuminate\Filesystem\Filesystem */ |
|
13
|
|
|
protected $filesystem; |
|
14
|
|
|
|
|
15
|
|
|
/** @var string */ |
|
16
|
|
|
protected $directory; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(Filesystem $filesystem) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->filesystem = $filesystem; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public function setDirectory(string $directory) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->directory = $directory; |
|
26
|
|
|
|
|
27
|
|
|
return $this; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function deleteFilesOlderThanMinutes(int $minutes) : Collection |
|
31
|
|
|
{ |
|
32
|
|
|
$timeInPast = Carbon::now()->subMinutes($minutes); |
|
33
|
|
|
|
|
34
|
|
|
return collect($this->filesystem->allFiles($this->directory)) |
|
35
|
|
|
->filter(function ($file) use ($timeInPast) { |
|
36
|
|
|
return Carbon::createFromTimestamp(filemtime($file)) |
|
37
|
|
|
->lt($timeInPast); |
|
38
|
|
|
}) |
|
39
|
|
|
->filter(function ($file) { |
|
40
|
|
|
return $this->policy()->shouldDelete($file); |
|
41
|
|
|
}) |
|
42
|
|
|
->each(function ($file) { |
|
43
|
|
|
$this->filesystem->delete($file); |
|
44
|
|
|
}); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function deleteEmptySubdirectories() : Collection |
|
48
|
|
|
{ |
|
49
|
|
|
return collect($this->filesystem->directories($this->directory)) |
|
50
|
|
|
->filter(function ($directory) { |
|
51
|
|
|
return ! $this->filesystem->allFiles($directory); |
|
52
|
|
|
}) |
|
53
|
|
|
->each(function ($directory) { |
|
54
|
|
|
$this->filesystem->deleteDirectory($directory); |
|
55
|
|
|
}); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
protected function policy() : CleanupPolicy |
|
59
|
|
|
{ |
|
60
|
|
|
return resolve(config( |
|
61
|
|
|
'laravel-directory-cleanup.cleanup_policy', |
|
62
|
|
|
\Spatie\DirectoryCleanup\Policies\DeleteEverything::class |
|
63
|
|
|
)); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|