Completed
Push — 6.0 ( 9dcf40...bc5730 )
by liu
19:01 queued 05:06
created

Cache::commit()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 11
ccs 0
cts 7
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use Psr\Cache\CacheItemInterface;
16
use Psr\Cache\CacheItemPoolInterface;
17
use think\cache\CacheItem;
18
use think\cache\Driver;
19
use think\exception\InvalidArgumentException;
20
21
/**
22
 * 缓存管理类
23
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
24
class Cache implements CacheItemPoolInterface
25
{
26
    /**
27
     * 缓存队列
28
     * @var array
29
     */
30
    protected $data = [];
31
32
    /**
33
     * 延期保存的缓存队列
34
     * @var array
35
     */
36
    protected $deferred = [];
37
38
    /**
39
     * 缓存实例
40
     * @var array
41
     */
42
    protected $instance = [];
43
44
    /**
45
     * 配置参数
46
     * @var array
47
     */
48
    protected $config = [];
49
50
    /**
51
     * 操作句柄
52
     * @var object
53
     */
54
    protected $handler;
55
56
    public function __construct(array $config = [])
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
57
    {
58
        $this->config = $config;
59
    }
60
61
    public static function __make(Config $config)
2 ignored issues
show
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
Coding Style introduced by
Method name "Cache::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Public method name "Cache::__make" must not be prefixed with an underscore
Loading history...
62
    {
63
        return new static($config->get('cache'));
0 ignored issues
show
Bug introduced by
It seems like $config->get('cache') can also be of type null; however, parameter $config of think\Cache::__construct() does only seem to accept array, 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

63
        return new static(/** @scrutinizer ignore-type */ $config->get('cache'));
Loading history...
64
    }
65
66
    /**
67
     * 连接缓存
68
     * @access public
69
     * @param  array $options  配置数组
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
70
     * @param  bool  $force 强制重新连接
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
71
     * @return Driver
72
     */
73
    public function connect(array $options = [], bool $force = false): Driver
74
    {
75
        $name = md5(serialize($options));
76
77
        if ($force || !isset($this->instance[$name])) {
78
            $type = !empty($options['type']) ? $options['type'] : 'File';
79
80
            $this->instance[$name] = App::factory($type, '\\think\\cache\\driver\\', $options);
81
        }
82
83
        return $this->instance[$name];
84
    }
85
86
    /**
87
     * 自动初始化缓存
88
     * @access protected
89
     * @param  array $options 配置数组
90
     * @param  bool  $force   强制更新
91
     * @return Driver
92
     */
93
    protected function init(array $options = [], bool $force = false): Driver
94
    {
95
        if (is_null($this->handler) || $force) {
96
            $options = !empty($options) ? $options : $this->config;
97
98
            if (isset($options['type']) && 'complex' == $options['type']) {
99
                $default = $options['default'];
100
                $options = $options[$default['type']] ?? $default;
101
            }
102
103
            $this->handler = $this->connect($options);
104
        }
105
106
        return $this->handler;
107
    }
108
109
    /**
110
     * 设置配置
111
     * @access public
112
     * @param  array $config 配置参数
113
     * @return void
114
     */
115
    public function config(array $config): void
116
    {
117
        $this->config = array_merge($this->config, $config);
118
    }
119
120
    /**
121
     * 切换缓存类型 需要配置 cache.type 为 complex
122
     * @access public
123
     * @param  string $name  缓存标识
124
     * @param  bool   $force 强制更新
125
     * @return Driver
126
     */
127
    public function store(string $name = '', bool $force = false): Driver
128
    {
129
        if ('' !== $name && 'complex' == $this->config['type']) {
130
            return $this->connect($this->config[$name], $force);
131
        }
132
133
        return $this->init([], $force);
134
    }
135
136
    /**
137
     * 读取缓存
138
     * @access public
139
     * @param  string $key 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
140
     * @param  mixed  $default 默认值
141
     * @return mixed
142
     */
143
    public function get(string $key, $default = false)
144
    {
145
        return $this->init()->get($key, $default);
146
    }
147
148
    /**
149
     * 写入缓存
150
     * @access public
151
     * @param  string        $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
152
     * @param  mixed         $value  存储数据
153
     * @param  int|\DateTime $expire  有效时间 0为永久
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
154
     * @return bool
155
     */
156
    public function set(string $name, $value, $expire = null): bool
157
    {
158
        return $this->init()->set($name, $value, $expire);
0 ignored issues
show
Bug introduced by
It seems like $expire can also be of type DateTime; however, parameter $expire of think\cache\SimpleCache::set() does only seem to accept DateInterval|integer|null, 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

158
        return $this->init()->set($name, $value, /** @scrutinizer ignore-type */ $expire);
Loading history...
159
    }
160
161
    /**
162
     * 追加缓存
163
     * @access public
164
     * @param  string        $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
165
     * @param  mixed         $value  存储数据
166
     * @param  int|\DateTime $expire  有效时间 0为永久
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
167
     * @return array
168
     */
169
    public function push(string $name, $value, $expire = null): array
170
    {
171
        return $this->init()->push($name, $value, $expire);
172
    }
173
174
    /**
175
     * 读取并删除缓存
176
     * @access public
177
     * @param  string $name 缓存变量名
178
     * @return mixed
179
     */
180
    public function pull(string $name)
181
    {
182
        return $this->init()->pull($name);
183
    }
184
185
    /**
186
     * 如果不存在则写入缓存
187
     * @access public
188
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
189
     * @param  mixed  $value  存储数据
190
     * @param  int    $expire  有效时间 0为永久
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
191
     * @return mixed
192
     */
193
    public function remember(string $name, $value, $expire = null)
194
    {
195
        return $this->init()->remember($name, $value, $expire);
196
    }
197
198
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $key should have a doc-comment as per coding-style.
Loading history...
199
     * 删除缓存
200
     * @access public
201
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $name does not match actual variable name $key
Loading history...
202
     * @return bool
203
     */
204
    public function delete(string $key): bool
205
    {
206
        return $this->init()->rm($key);
207
    }
208
209
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $key should have a doc-comment as per coding-style.
Loading history...
210
     * 判断缓存是否存在
211
     * @access public
212
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $name does not match actual variable name $key
Loading history...
213
     * @return bool
214
     */
215
    public function has(string $key): bool
216
    {
217
        return $this->init()->has($key);
218
    }
219
220
    /**
221
     * 缓存标签
222
     * @access public
223
     * @param  string|array $name 标签名
224
     * @return Driver
225
     */
226
    public function tag($name)
227
    {
228
        return $this->init()->tag($name);
229
    }
230
231
    /**
232
     * 返回句柄对象,可执行其它高级方法
233
     *
234
     * @access public
235
     * @return object
236
     */
237
    public function handler()
238
    {
239
        return $this->init()->handler();
240
    }
241
242
    /**
243
     * 返回「键」对应的一个缓存项。
244
     * @access public
245
     * @param  string $key 缓存标识
246
     * @return CacheItemInterface
247
     * @throws InvalidArgumentException
248
     */
249
    public function getItem($key): CacheItem
250
    {
251
        if (isset($this->data[$key])) {
252
            return $this->data[$key];
253
        }
254
255
        $cacheItem = new CacheItem($key);
256
257
        if ($this->has($key)) {
258
            $cacheItem->set($this->get($key));
259
        }
260
261
        $this->data[$key] = $cacheItem;
262
263
        return $cacheItem;
264
    }
265
266
    /**
267
     * 返回一个可供遍历的缓存项集合。
268
     * @access public
269
     * @param  array $keys
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
270
     * @return array|\Traversable
271
     * @throws InvalidArgumentException
272
     */
273
    public function getItems(array $keys = []): array
274
    {
275
        $result = [];
276
        foreach ($keys as $key) {
277
            $result[] = $this->getItem($key);
278
        }
279
280
        return $result;
281
    }
282
283
    /**
284
     * 检查缓存系统中是否有「键」对应的缓存项。
285
     * @access public
286
     * @param  string $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
287
     * @return bool
288
     * @throws InvalidArgumentException
289
     */
290
    public function hasItem($key): bool
291
    {
292
        return $this->has($key);
293
    }
294
295
    /**
296
     * 清空缓冲池
297
     * @access public
298
     * @return bool
299
     */
300
    public function clear(): bool
301
    {
302
        return $this->init()->clear();
303
    }
304
305
    /**
306
     * 从缓冲池里移除某个缓存项
307
     * @access public
308
     * @param  string $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
309
     * @return bool
310
     * @throws InvalidArgumentException
311
     */
312
    public function deleteItem($key): bool
313
    {
314
        return $this->delete($key);
315
    }
316
317
    /**
318
     * 从缓冲池里移除多个缓存项
319
     * @access public
320
     * @param  array $keys
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
321
     * @return bool
322
     * @throws InvalidArgumentException
323
     */
324
    public function deleteItems(array $keys): bool
325
    {
326
        foreach ($keys as $key) {
327
            $this->delete($key);
328
        }
329
330
        return true;
331
    }
332
333
    /**
334
     * 立刻为「CacheItemInterface」对象做数据持久化。
335
     * @access public
336
     * @param  CacheItemInterface $item
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
337
     * @return bool
338
     */
339
    public function save(CacheItemInterface $item): bool
340
    {
341
        if ($item->getKey()) {
342
            return $this->set($item->getKey(), $item->get(), $item->getExpire());
343
        }
344
345
        return false;
346
    }
347
348
    /**
349
     * 稍后为「CacheItemInterface」对象做数据持久化。
350
     * @access public
351
     * @param  CacheItemInterface $item
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
352
     * @return bool
353
     */
354
    public function saveDeferred(CacheItemInterface $item): bool
355
    {
356
        $this->deferred[$item->getKey()] = $item;
357
        return true;
358
    }
359
360
    /**
361
     * 提交所有的正在队列里等待的请求到数据持久层,配合 `saveDeferred()` 使用
362
     * @access public
363
     * @return bool
364
     */
365
    public function commit(): bool
366
    {
367
        foreach ($this->deferred as $key => $item) {
368
            $result = $this->save($item);
369
            unset($this->deferred[$key]);
370
371
            if (false === $result) {
372
                return false;
373
            }
374
        }
375
        return true;
376
    }
377
378
    public function __call($method, $args)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __call()
Loading history...
379
    {
380
        return call_user_func_array([$this->init(), $method], $args);
381
    }
382
383
    public function __destruct()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __destruct()
Loading history...
384
    {
385
        if (!empty($this->deferred)) {
386
            $this->commit();
387
        }
388
    }
389
390
}
391