Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

FileCache::addValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\caching;
10
11
use Yii;
12
use yii\helpers\FileHelper;
13
14
/**
15
 * FileCache implements a cache component using files.
16
 *
17
 * For each data value being cached, FileCache will store it in a separate file.
18
 * The cache files are placed under [[cachePath]]. FileCache will perform garbage collection
19
 * automatically to remove expired cache files.
20
 *
21
 * Please refer to [[Cache]] for common cache operations that are supported by FileCache.
22
 *
23
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
24
 *
25
 * @author Qiang Xue <[email protected]>
26
 * @since 2.0
27
 */
28
class FileCache extends Cache
29
{
30
    /**
31
     * @var string a string prefixed to every cache key. This is needed when you store
32
     * cache data under the same [[cachePath]] for different applications to avoid
33
     * conflict.
34
     *
35
     * To ensure interoperability, only alphanumeric characters should be used.
36
     */
37
    public $keyPrefix = '';
38
    /**
39
     * @var string the directory to store cache files. You may use [path alias](guide:concept-aliases) here.
40
     * If not set, it will use the "cache" subdirectory under the application runtime path.
41
     */
42
    public $cachePath = '@runtime/cache';
43
    /**
44
     * @var string cache file suffix. Defaults to '.bin'.
45
     */
46
    public $cacheFileSuffix = '.bin';
47
    /**
48
     * @var int the level of sub-directories to store cache files. Defaults to 1.
49
     * If the system has huge number of cache files (e.g. one million), you may use a bigger value
50
     * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
51
     * is not over burdened with a single directory having too many files.
52
     */
53
    public $directoryLevel = 1;
54
    /**
55
     * @var int the probability (parts per million) that garbage collection (GC) should be performed
56
     * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
57
     * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
58
     */
59
    public $gcProbability = 10;
60
    /**
61
     * @var int|null the permission to be set for newly created cache files.
62
     * This value will be used by PHP chmod() function. No umask will be applied.
63
     * If not set, the permission will be determined by the current environment.
64
     */
65
    public $fileMode;
66
    /**
67
     * @var int the permission to be set for newly created directories.
68
     * This value will be used by PHP chmod() function. No umask will be applied.
69
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
70
     * but read-only for other users.
71
     */
72
    public $dirMode = 0775;
73
74
75
    /**
76
     * Initializes this component by ensuring the existence of the cache path.
77
     */
78 27
    public function init()
79
    {
80 27
        parent::init();
81 27
        $this->cachePath = Yii::getAlias($this->cachePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::getAlias($this->cachePath) can also be of type false. However, the property $cachePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
82 27
        if (!is_dir($this->cachePath)) {
0 ignored issues
show
Bug introduced by
It seems like $this->cachePath can also be of type false; however, parameter $filename of is_dir() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

82
        if (!is_dir(/** @scrutinizer ignore-type */ $this->cachePath)) {
Loading history...
83 1
            FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
0 ignored issues
show
Bug introduced by
It seems like $this->cachePath can also be of type false; however, parameter $path of yii\helpers\BaseFileHelper::createDirectory() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

83
            FileHelper::createDirectory(/** @scrutinizer ignore-type */ $this->cachePath, $this->dirMode, true);
Loading history...
84
        }
85
    }
86
87
    /**
88
     * Checks whether a specified key exists in the cache.
89
     * This can be faster than getting the value from the cache if the data is big.
90
     * Note that this method does not check whether the dependency associated
91
     * with the cached data, if there is any, has changed. So a call to [[get]]
92
     * may return false while exists returns true.
93
     * @param mixed $key a key identifying the cached value. This can be a simple string or
94
     * a complex data structure consisting of factors representing the key.
95
     * @return bool true if a value exists in cache, false if the value is not in the cache or expired.
96
     */
97 5
    public function exists($key)
98
    {
99 5
        $cacheFile = $this->getCacheFile($this->buildKey($key));
100
101 5
        return @filemtime($cacheFile) > time();
102
    }
103
104
    /**
105
     * Retrieves a value from cache with a specified key.
106
     * This is the implementation of the method declared in the parent class.
107
     * @param string $key a unique key identifying the cached value
108
     * @return string|false the value stored in cache, false if the value is not in the cache or expired.
109
     */
110 24
    protected function getValue($key)
111
    {
112 24
        $cacheFile = $this->getCacheFile($key);
113
114 24
        if (@filemtime($cacheFile) > time()) {
115 20
            $fp = @fopen($cacheFile, 'r');
116 20
            if ($fp !== false) {
117 20
                @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

117
                /** @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...
118 20
                $cacheValue = @stream_get_contents($fp);
119 20
                @flock($fp, LOCK_UN);
120 20
                @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

120
                /** @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...
121 20
                return $cacheValue;
122
            }
123
        }
124
125 16
        return false;
126
    }
127
128
    /**
129
     * Stores a value identified by a key in cache.
130
     * This is the implementation of the method declared in the parent class.
131
     *
132
     * @param string $key the key identifying the value to be cached
133
     * @param string $value the value to be cached. Other types (If you have disabled [[serializer]]) unable to get is
134
     * correct in [[getValue()]].
135
     * @param int $duration the number of seconds in which the cached value will expire. Fewer than or equal to 0 means 1 year expiration time.
136
     * @return bool true if the value is successfully stored into cache, false otherwise
137
     */
138 22
    protected function setValue($key, $value, $duration)
139
    {
140 22
        $this->gc();
141 22
        $cacheFile = $this->getCacheFile($key);
142 22
        if ($this->directoryLevel > 0) {
143 22
            @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for createDirectory(). 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

143
            /** @scrutinizer ignore-unhandled */ @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);

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...
144
        }
145
        // If ownership differs the touch call will fail, so we try to
146
        // rebuild the file from scratch by deleting it first
147
        // https://github.com/yiisoft/yii2/pull/16120
148 22
        if (is_file($cacheFile) && function_exists('posix_geteuid') && fileowner($cacheFile) !== posix_geteuid()) {
149
            @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

149
            /** @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...
150
        }
151 22
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
152 22
            if ($this->fileMode !== null) {
153
                @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

153
                /** @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...
154
            }
155 22
            if ($duration <= 0) {
156 15
                $duration = 31536000; // 1 year
157
            }
158
159 22
            if (@touch($cacheFile, $duration + time())) {
160 22
                clearstatcache();
161 22
                return true;
162
            }
163
164
            return false;
165
        }
166
167
        $message = "Unable to write cache file '{$cacheFile}'";
168
169
        if ($error = error_get_last()) {
170
            $message .= ": {$error['message']}";
171
        }
172
173
        Yii::warning($message, __METHOD__);
174
175
        return false;
176
    }
177
178
    /**
179
     * Stores a value identified by a key into cache if the cache does not contain this key.
180
     * This is the implementation of the method declared in the parent class.
181
     *
182
     * @param string $key the key identifying the value to be cached
183
     * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) unable to get is
184
     * correct in [[getValue()]].
185
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
186
     * @return bool true if the value is successfully stored into cache, false otherwise
187
     */
188 3
    protected function addValue($key, $value, $duration)
189
    {
190 3
        $cacheFile = $this->getCacheFile($key);
191 3
        if (@filemtime($cacheFile) > time()) {
192 2
            return false;
193
        }
194
195 3
        return $this->setValue($key, $value, $duration);
196
    }
197
198
    /**
199
     * Deletes a value with the specified key from cache
200
     * This is the implementation of the method declared in the parent class.
201
     * @param string $key the key of the value to be deleted
202
     * @return bool if no error happens during deletion
203
     */
204 2
    protected function deleteValue($key)
205
    {
206 2
        $cacheFile = $this->getCacheFile($key);
207
208 2
        return @unlink($cacheFile);
209
    }
210
211
    /**
212
     * Returns the cache file path given the normalized cache key.
213
     * @param string $normalizedKey normalized cache key by [[buildKey]] method
214
     * @return string the cache file path
215
     */
216 25
    protected function getCacheFile($normalizedKey)
217
    {
218 25
        $cacheKey = $normalizedKey;
219
220 25
        if ($this->keyPrefix !== '') {
221
            // Remove key prefix to avoid generating constant directory levels
222 1
            $lenKeyPrefix = strlen($this->keyPrefix);
223 1
            $cacheKey = substr_replace($normalizedKey, '', 0, $lenKeyPrefix);
224
        }
225
226 25
        $cachePath = $this->cachePath;
227
228 25
        if ($this->directoryLevel > 0) {
229 25
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
230 25
                if (($subDirectory = substr($cacheKey, $i + $i, 2)) !== false) {
0 ignored issues
show
Bug introduced by
It seems like $cacheKey can also be of type array; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

230
                if (($subDirectory = substr(/** @scrutinizer ignore-type */ $cacheKey, $i + $i, 2)) !== false) {
Loading history...
231 25
                    $cachePath .= DIRECTORY_SEPARATOR . $subDirectory;
232
                }
233
            }
234
        }
235
236 25
        return $cachePath . DIRECTORY_SEPARATOR . $normalizedKey . $this->cacheFileSuffix;
237
    }
238
239
    /**
240
     * Deletes all values from cache.
241
     * This is the implementation of the method declared in the parent class.
242
     * @return bool whether the flush operation was successful.
243
     */
244 12
    protected function flushValues()
245
    {
246 12
        $this->gc(true, false);
247
248 12
        return true;
249
    }
250
251
    /**
252
     * Removes expired cache files.
253
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
254
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
255
     * @param bool $expiredOnly whether to removed expired cache files only.
256
     * If false, all cache files under [[cachePath]] will be removed.
257
     */
258 22
    public function gc($force = false, $expiredOnly = true)
259
    {
260 22
        if ($force || random_int(0, 1000000) < $this->gcProbability) {
261 12
            $this->gcRecursive($this->cachePath, $expiredOnly);
262
        }
263
    }
264
265
    /**
266
     * Recursively removing expired cache files under a directory.
267
     * This method is mainly used by [[gc()]].
268
     * @param string $path the directory under which expired cache files are removed.
269
     * @param bool $expiredOnly whether to only remove expired cache files. If false, all files
270
     * under `$path` will be removed.
271
     */
272 12
    protected function gcRecursive($path, $expiredOnly)
273
    {
274 12
        if (($handle = opendir($path)) !== false) {
275 12
            while (($file = readdir($handle)) !== false) {
276 12
                if (strncmp($file, '.', 1) === 0) {
277 12
                    continue;
278
                }
279 11
                $fullPath = $path . DIRECTORY_SEPARATOR . $file;
280 11
                $message = null;
281 11
                if (is_dir($fullPath)) {
282 11
                    $this->gcRecursive($fullPath, $expiredOnly);
283 11
                    if (!$expiredOnly) {
284 11
                        if (!@rmdir($fullPath)) {
285
                            $message = "Unable to remove directory '$fullPath'";
286
                            if ($error = error_get_last()) {
287 11
                                $message .= ": {$error['message']}";
288
                            }
289
                        }
290
                    }
291 11
                } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
292 11
                    if (!@unlink($fullPath)) {
293
                        $message = "Unable to remove file '$fullPath'";
294
                        if ($error = error_get_last()) {
295
                            $message .= ": {$error['message']}";
296
                        }
297
                    }
298
                }
299 11
                $message and Yii::warning($message, __METHOD__);
300
            }
301 12
            closedir($handle);
302
        }
303
    }
304
}
305