Passed
Pull Request — 2.2 (#20357)
by Wilmer
12:59 queued 04:29
created

FileCache::gcRecursive()   C

Complexity

Conditions 14
Paths 19

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 16.6456

Importance

Changes 0
Metric Value
cc 14
eloc 20
c 0
b 0
f 0
nc 19
nop 2
dl 0
loc 30
ccs 16
cts 21
cp 0.7619
crap 16.6456
rs 6.2666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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