Passed
Pull Request — 2.2 (#20357)
by Wilmer
08:37
created

FileCache::gcRecursive()   C

Complexity

Conditions 14
Paths 19

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 14.7716

Importance

Changes 0
Metric Value
cc 14
eloc 18
c 0
b 0
f 0
nc 19
nop 2
dl 0
loc 26
ccs 16
cts 19
cp 0.8421
crap 14.7716
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
        ($error = error_get_last()) and $message .= ": {$error['message']}";
164
165
        Yii::warning($message, __METHOD__);
166
167
        return false;
168
    }
169
170
    /**
171
     * Stores a value identified by a key into cache if the cache does not contain this key.
172
     * This is the implementation of the method declared in the parent class.
173
     *
174
     * @param string $key the key identifying the value to be cached
175
     * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) unable to get is
176
     * correct in [[getValue()]].
177
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
178
     * @return bool true if the value is successfully stored into cache, false otherwise
179
     */
180 3
    protected function addValue($key, $value, $duration)
181
    {
182 3
        $cacheFile = $this->getCacheFile($key);
183 3
        if (@filemtime($cacheFile) > time()) {
184 2
            return false;
185
        }
186
187 3
        return $this->setValue($key, $value, $duration);
188
    }
189
190
    /**
191
     * Deletes a value with the specified key from cache
192
     * This is the implementation of the method declared in the parent class.
193
     * @param string $key the key of the value to be deleted
194
     * @return bool if no error happens during deletion
195
     */
196 2
    protected function deleteValue($key)
197
    {
198 2
        $cacheFile = $this->getCacheFile($key);
199
200 2
        return @unlink($cacheFile);
201
    }
202
203
    /**
204
     * Returns the cache file path given the normalized cache key.
205
     * @param string $normalizedKey normalized cache key by [[buildKey]] method
206
     * @return string the cache file path
207
     */
208 24
    protected function getCacheFile($normalizedKey)
209
    {
210 24
        $cacheKey = $normalizedKey;
211
212 24
        if ($this->keyPrefix !== '') {
213
            // Remove key prefix to avoid generating constant directory levels
214 1
            $lenKeyPrefix = strlen($this->keyPrefix);
215 1
            $cacheKey = substr_replace($normalizedKey, '', 0, $lenKeyPrefix);
216
        }
217
218 24
        $cachePath = $this->cachePath;
219
220 24
        if ($this->directoryLevel > 0) {
221 24
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
222 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

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