Completed
Pull Request — master (#30)
by Alexander
01:23
created

FileCache::existsAndNotExpired()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
namespace Yiisoft\Cache;
4
5
use DateInterval;
6
use DateTime;
7
use Exception;
8
use Psr\SimpleCache\CacheInterface;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Cache\CacheInterface. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
use Yiisoft\Cache\Exception\CacheException;
10
use Yiisoft\Cache\Serializer\PhpSerializer;
11
use Yiisoft\Cache\Serializer\SerializerInterface;
12
13
/**
14
 * FileCache implements a cache handler using files.
15
 *
16
 * For each data value being cached, FileCache will store it in a separate file.
17
 * The cache files are placed under {@see FileCache::$cachePath}. FileCache will perform garbage collection
18
 * automatically to remove expired cache files.
19
 *
20
 * Please refer to {@see \Psr\SimpleCache\CacheInterface} for common cache operations that are supported by FileCache.
21
 */
22
final class FileCache implements CacheInterface
23
{
24
    private const TTL_INFINITY = 31536000; // 1 year
25
    private const EXPIRATION_EXPIRED = -1;
26
27
    /**
28
     * @var string the directory to store cache files. You may use [path alias](guide:concept-aliases) here.
29
     */
30
    private $cachePath;
31
    /**
32
     * @var string cache file suffix. Defaults to '.bin'.
33
     */
34
    private $cacheFileSuffix = '.bin';
35
    /**
36
     * @var int the level of sub-directories to store cache files. Defaults to 1.
37
     * If the system has huge number of cache files (e.g. one million), you may use a bigger value
38
     * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
39
     * is not over burdened with a single directory having too many files.
40
     */
41
    private $directoryLevel = 1;
42
43
    /**
44
     * @var int the probability (parts per million) that garbage collection (GC) should be performed
45
     * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
46
     * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
47
     */
48
    private $gcProbability = 10;
49
    /**
50
     * @var int the permission to be set for newly created cache files.
51
     * This value will be used by PHP chmod() function. No umask will be applied.
52
     * If not set, the permission will be determined by the current environment.
53
     */
54
    private $fileMode;
55
    /**
56
     * @var int the permission to be set for newly created directories.
57
     * This value will be used by PHP chmod() function. No umask will be applied.
58
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
59 20
     * but read-only for other users.
60
     */
61 20
    private $dirMode = 0775;
62 20
63 20
    /**
64
     * @var SerializerInterface the serializer to be used for serializing and unserializing of the cached data.
65
     */
66
    private $serializer;
67
68
    public function __construct(string $cachePath, ?SerializerInterface $serializer = null)
69
    {
70 20
        $this->cachePath = $cachePath;
71
        $this->serializer = $serializer ?? new PhpSerializer();
72 20
        $this->initCacheDirectory();
73
    }
74 20
75
    public function get($key, $default = null)
76
    {
77
        if ($this->existsAndNotExpired($key)) {
78
            $fp = @fopen($this->getCacheFile($key), 'rb');
79 4
            if ($fp !== false) {
80
                @flock($fp, LOCK_SH);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

80
                /** @scrutinizer ignore-unhandled */ @flock($fp, LOCK_SH);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
81 4
                $cacheValue = @stream_get_contents($fp);
82
                @flock($fp, LOCK_UN);
83 4
                @fclose($fp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

83
                /** @scrutinizer ignore-unhandled */ @fclose($fp);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
84
                $cacheValue = $this->serializer->unserialize($cacheValue);
85
                return $cacheValue;
86
            }
87
        }
88
89
        return $default;
90
    }
91
92
    public function set($key, $value, $ttl = null)
93
    {
94
        $this->gc();
95
96
        $expiration = $this->ttlToExpiration($ttl);
97
        if ($expiration < 0) {
98
            return $this->delete($key);
99
        }
100
101
        $cacheFile = $this->getCacheFile($key);
102
        if ($this->directoryLevel > 0) {
103
            $directoryName = \dirname($cacheFile);
104
            if (!$this->createDirectory($directoryName, $this->dirMode)) {
105
                return false;
106
            }
107
        }
108
        // If ownership differs the touch call will fail, so we try to
109
        // rebuild the file from scratch by deleting it first
110
        // https://github.com/yiisoft/yii2/pull/16120
111
        if (\function_exists('posix_geteuid') && is_file($cacheFile) && fileowner($cacheFile) !== posix_geteuid()) {
112
            @unlink($cacheFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

112
            /** @scrutinizer ignore-unhandled */ @unlink($cacheFile);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
113
        }
114
115
        $value = $this->serializer->serialize($value);
116
117
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
118
            if ($this->fileMode !== null) {
119
                @chmod($cacheFile, $this->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

119
                /** @scrutinizer ignore-unhandled */ @chmod($cacheFile, $this->fileMode);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
120
            }
121
            return @touch($cacheFile, $expiration);
122
        }
123
124
        return false;
125 19
    }
126
127 19
    public function delete($key)
128
    {
129 19
        return @unlink($this->getCacheFile($key));
130 17
    }
131 17
132 17
    public function clear()
133 17
    {
134 17
        $this->removeCacheFiles($this->cachePath, false);
135 17
        return true;
136 17
    }
137
138
    public function getMultiple($keys, $default = null)
139
    {
140 12
        $results = [];
141
        foreach ($keys as $key) {
142
            $value = $this->get($key, $default);
143 19
            $results[$key] = $value;
144
        }
145 19
        return $results;
146 19
    }
147 19
148 19
    public function setMultiple($values, $ttl = null)
149 19
    {
150
        foreach ($values as $key => $value) {
151
            $this->set($key, $value, $ttl);
152
        }
153
        return true;
154
    }
155
156
    public function deleteMultiple($keys)
157 19
    {
158 1
        foreach ($keys as $key) {
159
            $this->delete($key);
160
        }
161 19
        return true;
162 19
    }
163
164
    public function has($key)
165 19
    {
166 19
        return $this->existsAndNotExpired($key);
167
    }
168
169
    /**
170
     * Converts TTL to expiration
171
     * @param $ttl
172
     * @return int
173
     */
174 2
    private function ttlToExpiration($ttl): int
175
    {
176 2
        $ttl = $this->normalizeTtl($ttl);
177 2
178
        if ($ttl === null) {
179
            $expiration = static::TTL_INFINITY + time();
180
        } elseif ($ttl <= 0) {
181
            $expiration = static::EXPIRATION_EXPIRED;
182
        } else {
183
            $expiration = $ttl + time();
184
        }
185 20
186
        return $expiration;
187 20
    }
188 20
189 20
    /**
190 20
     * Normalizes cache TTL handling `null` value and {@see DateInterval} objects.
191 20
     * @param int|DateInterval|null $ttl raw TTL.
192
     * @return int|null TTL value as UNIX timestamp or null meaning infinity
193
     */
194
    private function normalizeTtl($ttl): ?int
195 20
    {
196
        if ($ttl instanceof DateInterval) {
197
            try {
198
                return (new DateTime('@0'))->add($ttl)->getTimestamp();
199
            } catch (Exception $e) {
200
                return null;
201 20
            }
202
        }
203 20
204 20
        return $ttl;
205
    }
206
207
    /**
208
     * Ensures that cache directory exists.
209
     */
210
    private function initCacheDirectory(): void
211 19
    {
212
        if (!$this->createDirectory($this->cachePath, $this->dirMode)) {
213 19
            throw new CacheException('Failed to create cache directory "' . $this->cachePath . '"');
214
        }
215
    }
216
217
    private function createDirectory(string $path, int $mode): bool
218
    {
219
        return is_dir($path) || (mkdir($path, $mode, true) && is_dir($path));
220
    }
221
222
    /**
223
     * Returns the cache file path given the cache key.
224
     * @param string $key cache key
225 20
     * @return string the cache file path
226
     */
227 20
    private function getCacheFile(string $key): string
228 20
    {
229 20
        if ($this->directoryLevel > 0) {
230 20
            $base = $this->cachePath;
231
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
232 17
                if (($prefix = substr($key, $i + $i, 2)) !== false) {
233 17
                    $base .= DIRECTORY_SEPARATOR . $prefix;
234 17
                }
235 17
            }
236
237 17
            return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
238
        }
239 17
240 17
        return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
241
    }
242
243
    /**
244
     * Removes expired cache files
245
     * @throws \Exception
246 20
     */
247
    public function gc(): void
248
    {
249
        if (\random_int(0, 1000000) < $this->gcProbability) {
250 20
            $this->removeCacheFiles($this->cachePath, true);
251
        }
252 20
    }
253
254
    /**
255
     * Recursively removing expired cache files under a directory.
256
     * This method is mainly used by {@see gc()}.
257
     * @param string $path the directory under which expired cache files are removed.
258
     * @param bool $expiredOnly whether to only remove expired cache files. If false, all files
259
     * under `$path` will be removed.
260
     */
261
    private function removeCacheFiles(string $path, bool $expiredOnly): void
262
    {
263
        if (($handle = opendir($path)) !== false) {
264
            while (($file = readdir($handle)) !== false) {
265
                if (strncmp($file, '.', 1) === 0) {
266
                    continue;
267
                }
268
                $fullPath = $path . DIRECTORY_SEPARATOR . $file;
269
                if (is_dir($fullPath)) {
270
                    $this->removeCacheFiles($fullPath, $expiredOnly);
271
                    if (!$expiredOnly && !@rmdir($fullPath)) {
272
                        $error = error_get_last();
273
                        throw new CacheException("Unable to remove directory '{$fullPath}': {$error['message']}");
274
                    }
275
                } elseif (!$expiredOnly || ($expiredOnly && @filemtime($fullPath) < time())) {
276
                    if (!@unlink($fullPath)) {
277
                        $error = error_get_last();
278
                        throw new CacheException("Unable to remove file '{$fullPath}': {$error['message']}");
279
                    }
280
                }
281
            }
282
            closedir($handle);
283
        }
284
    }
285
286
    /**
287
     * @param string $cacheFileSuffix cache file suffix. Defaults to '.bin'.
288
     */
289
    public function setCacheFileSuffix(string $cacheFileSuffix): void
290
    {
291
        $this->cacheFileSuffix = $cacheFileSuffix;
292
    }
293
294
    /**
295
     * @param int $gcProbability the probability (parts per million) that garbage collection (GC) should be performed
296
     * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
297
     * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
298
     */
299
    public function setGcProbability(int $gcProbability): void
300
    {
301
        $this->gcProbability = $gcProbability;
302
    }
303
304
    /**
305
     * @param int $fileMode the permission to be set for newly created cache files.
306
     * This value will be used by PHP chmod() function. No umask will be applied.
307
     * If not set, the permission will be determined by the current environment.
308
     */
309
    public function setFileMode(int $fileMode): void
310
    {
311
        $this->fileMode = $fileMode;
312
    }
313
314
    /**
315
     * @param int $dirMode the permission to be set for newly created directories.
316
     * This value will be used by PHP chmod() function. No umask will be applied.
317
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
318
     * but read-only for other users.
319
     */
320
    public function setDirMode(int $dirMode): void
321
    {
322
        $this->dirMode = $dirMode;
323
    }
324
325
    /**
326
     * @param int $directoryLevel the level of sub-directories to store cache files. Defaults to 1.
327
     * If the system has huge number of cache files (e.g. one million), you may use a bigger value
328
     * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
329
     * is not over burdened with a single directory having too many files.
330
     *
331
     */
332
    public function setDirectoryLevel(int $directoryLevel): void
333
    {
334
        $this->directoryLevel = $directoryLevel;
335
    }
336
337
    private function existsAndNotExpired(string $key)
338
    {
339
        return @filemtime($this->getCacheFile($key)) > time();
340
    }
341
}
342