Completed
Pull Request — master (#19)
by
unknown
01:21
created

DirectoryCleaner::deleteFilesOlderThanMinutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\DirectoryCleanup;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Facades\Storage;
8
9
class DirectoryCleaner
10
{
11
    /** @var \Illuminate\Contracts\Filesystem\Filesystem */
12
    protected $filesystem;
13
14
    /** @var string */
15
    protected $directory;
16
17
    /**
18
     * DirectoryCleaner constructor.
19
     */
20
    public function __construct()
21
    {
22
        // use our default storage by default
23
        $this->filesystem = Storage::disk();
24
    }
25
26
    /**
27
     * @param string $directory
28
     *
29
     * @return $this
30
     */
31
    public function setDirectory(string $directory)
32
    {
33
        $this->directory = $directory;
34
35
        return $this;
36
    }
37
38
    /**
39
     * @param string $driver
40
     *
41
     * @return $this
42
     */
43
    public function setFileSystemDriver(string $driver)
44
    {
45
        $this->filesystem = Storage::disk($driver);
46
47
        return $this;
48
    }
49
    
50
    /**
51
     * @param int $minutes
52
     *
53
     * @return \Illuminate\Support\Collection
54
     */
55
    public function deleteFilesOlderThanMinutes(int $minutes): Collection
56
    {
57
        $timeInPast = Carbon::now()->subMinutes($minutes);
58
59
        return collect($this->filesystem->allFiles($this->directory))
60
            ->filter(function ($file) use ($timeInPast) {
61
                return Carbon
62
                    ::createFromTimestamp($this->filesystem->lastModified($file))
63
                    ->lt($timeInPast);
64
            })
65
            ->each(function ($file) {
66
                $this->filesystem->delete($file);
67
            });
68
    }
69
}
70