Completed
Push — 2.1-merge ( 246828 )
by Dmitry
15:31 queued 08:02
created

FileCache::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
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 handler 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
 * Application configuration example:
21
 *
22
 * ```php
23
 * return [
24
 *     'components' => [
25
 *         'cache' => [
26
 *             '__class' => yii\caching\Cache::class,
27
 *             'handler' => [
28
 *                 '__class' => yii\caching\FileCache::class,
29
 *                 // 'cachePath' => '@runtime/cache',
30
 *             ],
31
 *         ],
32
 *         // ...
33
 *     ],
34
 *     // ...
35
 * ];
36
 * ```
37
 *
38
 * Please refer to [[\Psr\SimpleCache\CacheInterface]] for common cache operations that are supported by FileCache.
39
 *
40
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
41
 *
42
 * @author Qiang Xue <[email protected]>
43
 * @since 2.0
44
 */
45
class FileCache extends SimpleCache
46
{
47
    /**
48
     * @var string the directory to store cache files. You may use [path alias](guide:concept-aliases) here.
49
     * If not set, it will use the "cache" subdirectory under the application runtime path.
50
     */
51
    public $cachePath = '@runtime/cache';
52
    /**
53
     * @var string cache file suffix. Defaults to '.bin'.
54
     */
55
    public $cacheFileSuffix = '.bin';
56
    /**
57
     * @var int the level of sub-directories to store cache files. Defaults to 1.
58
     * If the system has huge number of cache files (e.g. one million), you may use a bigger value
59
     * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
60
     * is not over burdened with a single directory having too many files.
61
     */
62
    public $directoryLevel = 1;
63
    /**
64
     * @var int the probability (parts per million) that garbage collection (GC) should be performed
65
     * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
66
     * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
67
     */
68
    public $gcProbability = 10;
69
    /**
70
     * @var int the permission to be set for newly created cache files.
71
     * This value will be used by PHP chmod() function. No umask will be applied.
72
     * If not set, the permission will be determined by the current environment.
73
     */
74
    public $fileMode;
75
    /**
76
     * @var int the permission to be set for newly created directories.
77
     * This value will be used by PHP chmod() function. No umask will be applied.
78
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
79
     * but read-only for other users.
80
     */
81
    public $dirMode = 0775;
82
83
84
    /**
85
     * Initializes this component by ensuring the existence of the cache path.
86
     */
87 129
    public function init()
88
    {
89 129
        parent::init();
90 129
        $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...
91 129
        if (!is_dir($this->cachePath)) {
92 1
            FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
93
        }
94 129
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 3
    public function has($key)
100
    {
101 3
        $cacheFile = $this->getCacheFile($this->normalizeKey($key));
102
103 3
        return @filemtime($cacheFile) > time();
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 29
    protected function getValue($key)
110
    {
111 29
        $cacheFile = $this->getCacheFile($key);
112
113 29
        if (@filemtime($cacheFile) > time()) {
114 16
            $fp = @fopen($cacheFile, 'r');
115 16
            if ($fp !== false) {
116 16
                @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 16
                $cacheValue = @stream_get_contents($fp);
118 16
                @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 16
                @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 16
                return $cacheValue;
121
            }
122
        }
123
124 22
        return false;
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130 28
    protected function setValue($key, $value, $ttl)
131
    {
132 28
        $this->gc();
133 28
        $cacheFile = $this->getCacheFile($key);
134 28
        if ($this->directoryLevel > 0) {
135 28
            @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...
136
        }
137
        // If ownership differs the touch call will fail, so we try to
138
        // rebuild the file from scratch by deleting it first
139
        // https://github.com/yiisoft/yii2/pull/16120
140 28
        if (is_file($cacheFile) && function_exists('posix_geteuid') && fileowner($cacheFile) !== posix_geteuid()) {
141 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...
142
        }
143 28
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
144 28
            if ($this->fileMode !== null) {
145
                @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...
146
            }
147 28
            if ($ttl <= 0) {
148 24
                $ttl = 31536000; // 1 year
149
            }
150
151 28
            return @touch($cacheFile, $ttl + time());
152
        }
153
154
        $error = error_get_last();
155
        Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
156
        return false;
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162 99
    protected function deleteValue($key)
163
    {
164 99
        $cacheFile = $this->getCacheFile($key);
165 99
        return @unlink($cacheFile);
166
    }
167
168
    /**
169
     * Returns the cache file path given the cache key.
170
     * @param string $key cache key
171
     * @return string the cache file path
172
     */
173 118
    protected function getCacheFile($key)
174
    {
175 118
        if ($this->directoryLevel > 0) {
176 118
            $base = $this->cachePath;
177 118
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
178 118
                if (($prefix = substr($key, $i + $i, 2)) !== false) {
179 118
                    $base .= DIRECTORY_SEPARATOR . $prefix;
180
                }
181
            }
182
183 118
            return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
184
        }
185
186
        return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
187
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192 11
    public function clear()
193
    {
194 11
        $this->gc(true, false);
195 11
        return true;
196
    }
197
198
    /**
199
     * Removes expired cache files.
200
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
201
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
202
     * @param bool $expiredOnly whether to removed expired cache files only.
203
     * If false, all cache files under [[cachePath]] will be removed.
204
     */
205 28
    public function gc($force = false, $expiredOnly = true)
206
    {
207 28
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
208 11
            $this->gcRecursive($this->cachePath, $expiredOnly);
209
        }
210 28
    }
211
212
    /**
213
     * Recursively removing expired cache files under a directory.
214
     * This method is mainly used by [[gc()]].
215
     * @param string $path the directory under which expired cache files are removed.
216
     * @param bool $expiredOnly whether to only remove expired cache files. If false, all files
217
     * under `$path` will be removed.
218
     */
219 11
    protected function gcRecursive($path, $expiredOnly)
220
    {
221 11
        if (($handle = opendir($path)) !== false) {
222 11
            while (($file = readdir($handle)) !== false) {
223 11
                if ($file[0] === '.') {
224 11
                    continue;
225
                }
226 10
                $fullPath = $path . DIRECTORY_SEPARATOR . $file;
227 10
                if (is_dir($fullPath)) {
228 10
                    $this->gcRecursive($fullPath, $expiredOnly);
229 10
                    if (!$expiredOnly) {
230 10
                        if (!@rmdir($fullPath)) {
231
                            $error = error_get_last();
232 10
                            Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
233
                        }
234
                    }
235 10
                } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
236 10
                    if (!@unlink($fullPath)) {
237
                        $error = error_get_last();
238
                        Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
239
                    }
240
                }
241
            }
242 11
            closedir($handle);
243
        }
244 11
    }
245
}
246