Completed
Push — master ( 009682...4f41d1 )
by Dmitry
14:15
created

FileCache   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 253
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 89.61%

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 3
dl 0
loc 253
ccs 69
cts 77
cp 0.8961
rs 8.8
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A exists() 0 6 1
A init() 0 8 2
A getValue() 0 17 3
A addValue() 0 9 2
A deleteValue() 0 6 1
A getCacheFile() 0 15 4
A flushValues() 0 6 1
A gc() 0 6 3
C gcRecursive() 0 26 11
C setValue() 0 28 8
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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 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 130
    public function init()
78
    {
79 130
        parent::init();
80 130
        $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 boolean. 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 130
        if (!is_dir($this->cachePath)) {
82 1
            FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
83
        }
84 130
    }
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 42
    protected function getValue($key)
110
    {
111 42
        $cacheFile = $this->getCacheFile($key);
112
113 42
        if (@filemtime($cacheFile) > time()) {
114 29
            $fp = @fopen($cacheFile, 'r');
115 29
            if ($fp !== false) {
116 29
                @flock($fp, LOCK_SH);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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 29
                $cacheValue = @stream_get_contents($fp);
118 29
                @flock($fp, LOCK_UN);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
119 29
                @fclose($fp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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 29
                return $cacheValue;
121
            }
122
        }
123
124 33
        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. 0 means never expire.
135
     * @return bool true if the value is successfully stored into cache, false otherwise
136
     */
137 41
    protected function setValue($key, $value, $duration)
138
    {
139 41
        $this->gc();
140 41
        $cacheFile = $this->getCacheFile($key);
141 41
        if ($this->directoryLevel > 0) {
142 41
            @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 here. This can introduce security issues, and is generally not recommended.

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 41
        if (is_file($cacheFile) && function_exists('posix_geteuid') && fileowner($cacheFile) !== posix_geteuid()) {
148 1
            @unlink($cacheFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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 41
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
151 41
            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 here. This can introduce security issues, and is generally not recommended.

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 41
            if ($duration <= 0) {
155 27
                $duration = 31536000; // 1 year
156
            }
157
158 41
            return @touch($cacheFile, $duration + time());
159
        }
160
161
        $error = error_get_last();
162
        Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
163
        return false;
164
    }
165
166
    /**
167
     * Stores a value identified by a key into cache if the cache does not contain this key.
168
     * This is the implementation of the method declared in the parent class.
169
     *
170
     * @param string $key the key identifying the value to be cached
171
     * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) unable to get is
172
     * correct in [[getValue()]].
173
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
174
     * @return bool true if the value is successfully stored into cache, false otherwise
175
     */
176 3
    protected function addValue($key, $value, $duration)
177
    {
178 3
        $cacheFile = $this->getCacheFile($key);
179 3
        if (@filemtime($cacheFile) > time()) {
180 2
            return false;
181
        }
182
183 3
        return $this->setValue($key, $value, $duration);
184
    }
185
186
    /**
187
     * Deletes a value with the specified key from cache
188
     * This is the implementation of the method declared in the parent class.
189
     * @param string $key the key of the value to be deleted
190
     * @return bool if no error happens during deletion
191
     */
192 105
    protected function deleteValue($key)
193
    {
194 105
        $cacheFile = $this->getCacheFile($key);
195
196 105
        return @unlink($cacheFile);
197
    }
198
199
    /**
200
     * Returns the cache file path given the cache key.
201
     * @param string $key cache key
202
     * @return string the cache file path
203
     */
204 131
    protected function getCacheFile($key)
205
    {
206 131
        if ($this->directoryLevel > 0) {
207 131
            $base = $this->cachePath;
208 131
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
209 131
                if (($prefix = substr($key, $i + $i, 2)) !== false) {
210 131
                    $base .= DIRECTORY_SEPARATOR . $prefix;
211
                }
212
            }
213
214 131
            return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
215
        }
216
217
        return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
218
    }
219
220
    /**
221
     * Deletes all values from cache.
222
     * This is the implementation of the method declared in the parent class.
223
     * @return bool whether the flush operation was successful.
224
     */
225 11
    protected function flushValues()
226
    {
227 11
        $this->gc(true, false);
228
229 11
        return true;
230
    }
231
232
    /**
233
     * Removes expired cache files.
234
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
235
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
236
     * @param bool $expiredOnly whether to removed expired cache files only.
237
     * If false, all cache files under [[cachePath]] will be removed.
238
     */
239 41
    public function gc($force = false, $expiredOnly = true)
240
    {
241 41
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
242 11
            $this->gcRecursive($this->cachePath, $expiredOnly);
243
        }
244 41
    }
245
246
    /**
247
     * Recursively removing expired cache files under a directory.
248
     * This method is mainly used by [[gc()]].
249
     * @param string $path the directory under which expired cache files are removed.
250
     * @param bool $expiredOnly whether to only remove expired cache files. If false, all files
251
     * under `$path` will be removed.
252
     */
253 11
    protected function gcRecursive($path, $expiredOnly)
254
    {
255 11
        if (($handle = opendir($path)) !== false) {
256 11
            while (($file = readdir($handle)) !== false) {
257 11
                if ($file[0] === '.') {
258 11
                    continue;
259
                }
260 10
                $fullPath = $path . DIRECTORY_SEPARATOR . $file;
261 10
                if (is_dir($fullPath)) {
262 10
                    $this->gcRecursive($fullPath, $expiredOnly);
263 10
                    if (!$expiredOnly) {
264 10
                        if (!@rmdir($fullPath)) {
265
                            $error = error_get_last();
266 10
                            Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
267
                        }
268
                    }
269 10
                } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
270 10
                    if (!@unlink($fullPath)) {
271
                        $error = error_get_last();
272
                        Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
273
                    }
274
                }
275
            }
276 11
            closedir($handle);
277
        }
278 11
    }
279
}
280