Completed
Push — 2.1 ( 28b26f...4d9204 )
by Alexander
10:53
created

FileCache::clear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
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 116
    public function init()
88
    {
89 116
        parent::init();
90 116
        $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 116
        if (!is_dir($this->cachePath)) {
92 1
            FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
93
        }
94 116
    }
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 22
    protected function getValue($key)
110
    {
111 22
        $cacheFile = $this->getCacheFile($key);
112
113 22
        if (@filemtime($cacheFile) > time()) {
114 15
            $fp = @fopen($cacheFile, 'r');
115 15
            if ($fp !== false) {
116 15
                @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 15
                $cacheValue = @stream_get_contents($fp);
118 15
                @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 15
                @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 15
                return $cacheValue;
121
            }
122
        }
123
124 16
        return false;
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130 21
    protected function setValue($key, $value, $ttl)
131
    {
132 21
        $this->gc();
133 21
        $cacheFile = $this->getCacheFile($key);
134 21
        if ($this->directoryLevel > 0) {
135 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 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 21
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
138 21
            if ($this->fileMode !== null) {
139
                @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...
140
            }
141 21
            if ($ttl <= 0) {
142 18
                $ttl = 31536000; // 1 year
143
            }
144
145 21
            return @touch($cacheFile, $ttl + time());
146
        }
147
148
        $error = error_get_last();
149
        Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
150
        return false;
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 87
    protected function deleteValue($key)
157
    {
158 87
        $cacheFile = $this->getCacheFile($key);
159 87
        return @unlink($cacheFile);
160
    }
161
162
    /**
163
     * Returns the cache file path given the cache key.
164
     * @param string $key cache key
165
     * @return string the cache file path
166
     */
167 105
    protected function getCacheFile($key)
168
    {
169 105
        if ($this->directoryLevel > 0) {
170 105
            $base = $this->cachePath;
171 105
            for ($i = 0; $i < $this->directoryLevel; ++$i) {
172 105
                if (($prefix = substr($key, $i + $i, 2)) !== false) {
173 105
                    $base .= DIRECTORY_SEPARATOR . $prefix;
174
                }
175
            }
176
177 105
            return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
178
        }
179
180
        return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186 11
    public function clear()
187
    {
188 11
        $this->gc(true, false);
189 11
        return true;
190
    }
191
192
    /**
193
     * Removes expired cache files.
194
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
195
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
196
     * @param bool $expiredOnly whether to removed expired cache files only.
197
     * If false, all cache files under [[cachePath]] will be removed.
198
     */
199 21
    public function gc($force = false, $expiredOnly = true)
200
    {
201 21
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
202 11
            $this->gcRecursive($this->cachePath, $expiredOnly);
203
        }
204 21
    }
205
206
    /**
207
     * Recursively removing expired cache files under a directory.
208
     * This method is mainly used by [[gc()]].
209
     * @param string $path the directory under which expired cache files are removed.
210
     * @param bool $expiredOnly whether to only remove expired cache files. If false, all files
211
     * under `$path` will be removed.
212
     */
213 11
    protected function gcRecursive($path, $expiredOnly)
214
    {
215 11
        if (($handle = opendir($path)) !== false) {
216 11
            while (($file = readdir($handle)) !== false) {
217 11
                if ($file[0] === '.') {
218 11
                    continue;
219
                }
220 10
                $fullPath = $path . DIRECTORY_SEPARATOR . $file;
221 10
                if (is_dir($fullPath)) {
222 10
                    $this->gcRecursive($fullPath, $expiredOnly);
223 10
                    if (!$expiredOnly) {
224 10
                        if (!@rmdir($fullPath)) {
225
                            $error = error_get_last();
226 10
                            Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
227
                        }
228
                    }
229 10
                } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
230 10
                    if (!@unlink($fullPath)) {
231
                        $error = error_get_last();
232
                        Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
233
                    }
234
                }
235
            }
236 11
            closedir($handle);
237
        }
238 11
    }
239
}
240