Test Failed
Pull Request — master (#20371)
by Alexander
18:51 queued 10:32
created

FileCache::exists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

81
        if (!is_dir(/** @scrutinizer ignore-type */ $this->cachePath)) {
Loading history...
82 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

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

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

119
                /** @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...
120 33
                return $cacheValue;
121
            }
122
        }
123
124 121
        return false;
125
    }
126
127
    /**
128
     * Stores a value identified by a key in cache.
129
     * This is the implementation of the method declared in the parent class.
130
     *
131
     * @param string $key the key identifying the value to be cached
132
     * @param string $value the value to be cached. Other types (If you have disabled [[serializer]]) unable to get is
133
     * correct in [[getValue()]].
134
     * @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.
135
     * @return bool true if the value is successfully stored into cache, false otherwise
136
     */
137 45
    protected function setValue($key, $value, $duration)
138
    {
139 45
        $this->gc();
140 45
        $cacheFile = $this->getCacheFile($key);
141 45
        if ($this->directoryLevel > 0) {
142 45
            @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

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

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

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

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