Issues (1)

src/FileCache.php (1 issue)

Labels
Severity
1
<?php
2
namespace PiedWeb\FileCache;
3
4
class FileCache
5
{
6
    /**
7
     * Prefix your cache files
8
     * @var string
9
     */
10
    protected $prefix;
11
12
    /**
13
     * Folder where your cache files are stored
14
     * @var string
15
     */
16
    protected $folder;
17
18
    /**
19
     * Constructor
20
     *
21
     * @param string $folder Folder containing cache files. Default /tmp
22
     * @param string $prefix Prefix for the cache files. Default empty.
23
     */
24 12
    public function __construct(string $folder = '/tmp', string $prefix = '')
25
    {
26 12
        $this->setCacheFolder($folder);
27 12
        $this->setPrefix($prefix);
28 12
    }
29
30
    /**
31
     * Instanciator
32
     *
33
     * @param string $folder Folder containing cache files. Default /tmp
34
     * @param string $prefix Prefix for the cache files. Default empty.
35
     *
36
     * return self
37
     */
38 9
    public static function instance(string $folder = '/tmp', string $prefix = '')
39
    {
40 9
        $class = get_called_class();
41 9
        return new  $class($folder, $prefix);
42
    }
43
44
    /**
45
     * Chainable prefix setter
46
     *
47
     * @param string $prefix
48
     *
49
     * @return self
50
     */
51 12
    protected function setPrefix(string $prefix)
52
    {
53 12
        $this->prefix = $prefix;
54
55 12
        return $this;
56
    }
57
58
    /**
59
     * Set the cache folder (chainable folder setter)
60
     *
61
     * @param string $folder
62
     *
63
     * @return self
64
     */
65 12
    protected function setCacheFolder(string $folder)
66
    {
67 12
        $this->folder = $folder;
68
69 12
        return $this;
70
    }
71
72
    /**
73
     * Get cache file path
74
     *
75
     * @param mixed $key
76
     *
77
     * @return string
78
     */
79 12
    public function getCacheFilePath($key)
80
    {
81 12
        return $this->folder.'/'.$this->prefix.sha1($key);
82
    }
83
84
    /**
85
     * Return your cache data else create and return data
86
     *
87
     * @param string $key    String wich permit to identify your cache file
88
     * @param int    $maxAge Time the cache is valid. Default 86400 (1 day).
89
     * @param mixed  $data   It can be a function wich generate data to cache or a variable wich will be directly stored
90
     *
91
     * @return mixed Return your $data or the esponse from your function (or it cache)
92
     */
93 9
    public function getElseCreate($key, int $maxAge, $data)
94
    {
95 9
        $cachedData = $this->get($key, $maxAge);
96
97 9
        if ($cachedData === false) {
98 9
            $cachedData = is_callable($data) ? call_user_func($data) : $data;
99 9
            $this->set($key, $cachedData);
100
        }
101
102 9
        return $cachedData;
103
    }
104
105
    /**
106
     * Get your cached data if exist else return false
107
     *
108
     * @param string $key    String wich permit to identify your cache file
109
     * @param int    $maxAge Time the cache is valid. Default 86400 (1 day). 0 = always valid
110
     *
111
     * @return mixed Return FALSE if cache not found or not valid (BUT WHAT IF WE STORE A BOOL EQUAL TO FALSE ?!)
112
     */
113 12
    public function get($key, int $maxAge = 86400)
114
    {
115 12
        $cacheFile = $this->getCacheFilePath($key);
116 12
        if ($this->isCacheFileValid($cacheFile, $maxAge)) {
117 3
            return unserialize(file_get_contents($this->getCacheFilePath($key)));
118
        }
119
120 9
        return false;
121
    }
122
123
    /**
124
     * Set your data in cache
125
     *
126
     * @param string $key  String wich permit to identify your cache file
127
     * @param mixed  $data Variable wich will be directly stored
128
     *
129
     * @return self
130
     */
131 12
    public function set($key, $data)
132
    {
133 12
        file_put_contents($this->getCacheFilePath($key), serialize($data));
134
135 12
        return $this;
136
    }
137
138
    /**
139
     * Cache is valid ?
140
     *
141
     * @param string $key    String wich permit to identify your cache file
142
     * @param int    $maxAge Time the cache is valid. Default 86400 (1 day).
143
     *
144
     * @return bool
145
     */
146 3
    public function isCacheValid($key, int $maxAge)
147
    {
148 3
        $cacheFile = $this->getCacheFilePath($key);
149
150 3
        return $this->isCacheFileValid($cacheFile, $maxAge);
151
    }
152
153
    /**
154
     * Cache File is valid ?
155
     *
156
     * @param string $cacheFile Cache file path
157
     * @param int    $maxAge    Time the cache is valid. Default 86400 (1 day).
158
     *
159
     * @return bool
160
     */
161 12
    protected function isCacheFileValid($cacheFile, $maxAge)
162
    {
163 12
        $expire = time() - $maxAge;
164
165 12
        return !file_exists($cacheFile) || (filemtime($cacheFile) <= $expire && $maxAge !== 0)  ? false : true;
166
    }
167
168
    /**
169
     * @return bool (same as unlink php function)
170
     */
171 9
    public function deleteCacheFile($key)
172
    {
173 9
        return unlink($this->getCacheFilePath($key));
174
    }
175
176
    /**
177
     * Delete all cache files with the $prefix
178
     *
179
     * @return int Number of deleted files
180
     *
181
     * @throw \Exception If the prefix is empty
182
     */
183 3
    public function deleteCacheFilesByPrefix()
184
    {
185 3
        if (empty($this->prefix)) {
186
            throw new Exception('FileCache::Prefix is empty : Can\'t delete cache files by prefix.');
0 ignored issues
show
The type PiedWeb\FileCache\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
187
        }
188
189 3
        $deletedFilesCounter = 0;
190 3
        $files = glob($this->folder.'/'.$this->prefix.'*', GLOB_NOSORT);
191 3
        foreach ($files as $file) {
192 3
            unlink($file);
193 3
            ++$deletedFilesCounter;
194
        }
195
196 3
        return $deletedFilesCounter;
197
    }
198
}
199