Completed
Pull Request — master (#3)
by
unknown
12:32
created

DirectoryCleaner   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 72
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setDirectory() 0 6 1
A deleteFilesOlderThanMinutes() 0 13 1
A files() 0 15 2
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