Completed
Push — 6.0 ( 06cef6...9ae69a )
by liu
04:12
created

Cache::connect()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 2
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 20
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\cache\TagSet;
20
use think\exception\InvalidArgumentException;
21
22
/**
23
 * 缓存管理类
24
 */
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...
25
class Cache implements CacheItemPoolInterface
26
{
27
    /**
28
     * 缓存队列
29
     * @var array
30
     */
31
    protected $data = [];
32
33
    /**
34
     * 延期保存的缓存队列
35
     * @var array
36
     */
37
    protected $deferred = [];
38
39
    /**
40
     * 缓存实例
41
     * @var array
42
     */
43
    protected $instance = [];
44
45
    /**
46
     * 配置参数
47
     * @var array
48
     */
49
    protected $config = [];
50
51
    /**
52
     * 操作句柄
53
     * @var object
54
     */
55
    protected $handler;
56
57
    public function __construct(array $config = [])
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
58
    {
59
        $this->config = $config;
60
    }
61
62
    public static function __make(Config $config)
2 ignored issues
show
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...
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
63
    {
64
        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

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

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