1 | <?php |
||
10 | class DirectoryCleaner |
||
11 | { |
||
12 | /** @var \Illuminate\Filesystem\Filesystem */ |
||
13 | protected $filesystem; |
||
14 | |||
15 | /** @var string */ |
||
16 | protected $directory; |
||
17 | |||
18 | /** @var Carbon */ |
||
19 | protected $timeInPast; |
||
20 | |||
21 | public function __construct(Filesystem $filesystem) |
||
25 | |||
26 | public function setDirectory(string $directory) |
||
32 | |||
33 | public function setMinutes($minutes) |
||
39 | |||
40 | public function deleteFilesOlderThanMinutes($amountOfFilesDeleted = 0, $directory = null): int |
||
41 | { |
||
42 | $workingDir = $directory ?: realpath($this->directory); |
||
43 | $directories = collect($this->filesystem->directories($workingDir)); |
||
44 | if ($directory === null) { |
||
45 | $directories = $directories->add($workingDir); |
||
46 | } |
||
47 | |||
48 | foreach ($directories as $subDirectory) { |
||
49 | $amountOfFilesDeleted = $this->deleteFilesOlderThanMinutes($amountOfFilesDeleted, $subDirectory); |
||
50 | } |
||
51 | |||
52 | $files = collect($this->filesystem->files($workingDir, true)) |
||
53 | ->filter(function ($file) { |
||
54 | return Carbon::createFromTimestamp(filemtime($file)) |
||
55 | ->lt($this->timeInPast); |
||
56 | }) |
||
57 | ->filter(function ($file) { |
||
58 | return $this->policy()->shouldDelete($file); |
||
59 | }) |
||
60 | ->each(function ($file) { |
||
61 | $this->filesystem->delete($file); |
||
62 | }); |
||
63 | |||
64 | return $amountOfFilesDeleted + $files->count(); |
||
65 | } |
||
66 | |||
67 | public function deleteEmptySubdirectories(): Collection |
||
77 | |||
78 | protected function policy(): CleanupPolicy |
||
85 | } |
||
86 |