1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\DirectoryCleanup; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
use Illuminate\Filesystem\Filesystem; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
|
9
|
|
|
class DirectoryCleaner |
10
|
|
|
{ |
11
|
|
|
/** @var \Illuminate\Filesystem\Filesystem */ |
12
|
|
|
protected $filesystem; |
13
|
|
|
|
14
|
|
|
/** @var string */ |
15
|
|
|
protected $directory; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param \Illuminate\Filesystem\Filesystem $filesystem |
19
|
|
|
*/ |
20
|
|
|
public function __construct(Filesystem $filesystem) |
21
|
|
|
{ |
22
|
|
|
$this->filesystem = $filesystem; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param string $directory |
27
|
|
|
* |
28
|
|
|
* @return $this |
29
|
|
|
*/ |
30
|
|
|
public function setDirectory(string $directory) |
31
|
|
|
{ |
32
|
|
|
$this->directory = $directory; |
33
|
|
|
|
34
|
|
|
return $this; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param int $minutes |
39
|
|
|
* @param string $prefix |
40
|
|
|
* |
41
|
|
|
* @return \Illuminate\Support\Collection |
42
|
|
|
*/ |
43
|
|
|
public function deleteFilesOlderThanMinutes(int $minutes, string $prefix = null) : Collection |
44
|
|
|
{ |
45
|
|
|
$timeInPast = Carbon::now()->subMinutes($minutes); |
46
|
|
|
|
47
|
|
|
return collect($this->files($this->directory, $prefix)) |
48
|
|
|
->filter(function ($file) use ($timeInPast) { |
49
|
|
|
return Carbon::createFromTimestamp(filemtime($file)) |
50
|
|
|
->lt($timeInPast); |
51
|
|
|
}) |
52
|
|
|
->each(function ($file) { |
53
|
|
|
$this->filesystem->delete($file); |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Find files with given prefix |
59
|
|
|
* |
60
|
|
|
* @param string $directory |
61
|
|
|
* @param string|null $prefix |
62
|
|
|
* |
63
|
|
|
* @return array |
64
|
|
|
*/ |
65
|
|
|
private function files(string $directory, string $prefix = null) |
66
|
|
|
{ |
67
|
|
|
$glob = glob(sprintf('%s/%s', $directory, $prefix . '*' ?? '*')); |
68
|
|
|
|
69
|
|
|
if ($glob === false) { |
70
|
|
|
return []; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
// To get the appropriate files, we'll simply glob the directory and filter |
74
|
|
|
// out any "files" that are not truly files so we do not end up with any |
75
|
|
|
// directories in our list, but only true files within the directory. |
76
|
|
|
return array_filter($glob, function ($file) { |
77
|
|
|
return filetype($file) == 'file'; |
78
|
|
|
}); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|