Completed
Push — 6.0 ( a70fce...4a259b )
by liu
02:48
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\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
    public function get(string $key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function get()
Loading history...
137
    {
138
        return $this->init()->get($key);
139
    }
140
141
    public function set(string $name, $value, $expire = null)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function set()
Loading history...
142
    {
143
        return $this->init()->set($name, $value, $expire);
144
    }
145
146
    public function delete(string $key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function delete()
Loading history...
147
    {
148
        return $this->init()->rm($key);
149
    }
150
151
    public function has(string $key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function has()
Loading history...
152
    {
153
        return $this->init()->has($key);
154
    }
155
156
    /**
157
     * 缓存标签
158
     * @access public
159
     * @param  string|array $name 标签名
160
     * @return Driver
161
     */
162
    public function tag($name)
163
    {
164
        return $this->init()->tag($name);
165
    }
166
167
    /**
168
     * 返回「键」对应的一个缓存项。
169
     * @access public
170
     * @param  string $key 缓存标识
171
     * @return CacheItemInterface
172
     * @throws InvalidArgumentException
173
     */
174
    public function getItem($key): CacheItem
175
    {
176
        if (isset($this->data[$key])) {
177
            return $this->data[$key];
178
        }
179
180
        $cacheItem = new CacheItem($key);
181
182
        if ($this->has($key)) {
183
            $cacheItem->set($this->get($key));
184
        }
185
186
        $this->data[$key] = $cacheItem;
187
188
        return $cacheItem;
189
    }
190
191
    /**
192
     * 返回一个可供遍历的缓存项集合。
193
     * @access public
194
     * @param  array $keys
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
195
     * @return array|\Traversable
196
     * @throws InvalidArgumentException
197
     */
198
    public function getItems(array $keys = []): array
199
    {
200
        $result = [];
201
        foreach ($keys as $key) {
202
            $result[] = $this->getItem($key);
203
        }
204
205
        return $result;
206
    }
207
208
    /**
209
     * 检查缓存系统中是否有「键」对应的缓存项。
210
     * @access public
211
     * @param  string $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
212
     * @return bool
213
     * @throws InvalidArgumentException
214
     */
215
    public function hasItem($key): bool
216
    {
217
        return $this->has($key);
218
    }
219
220
    /**
221
     * 清空缓冲池
222
     * @access public
223
     * @return bool
224
     */
225
    public function clear(): bool
226
    {
227
        return $this->init()->clear();
228
    }
229
230
    /**
231
     * 从缓冲池里移除某个缓存项
232
     * @access public
233
     * @param  string $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
234
     * @return bool
235
     * @throws InvalidArgumentException
236
     */
237
    public function deleteItem($key): bool
238
    {
239
        return $this->delete($key);
240
    }
241
242
    /**
243
     * 从缓冲池里移除多个缓存项
244
     * @access public
245
     * @param  array $keys
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
246
     * @return bool
247
     * @throws InvalidArgumentException
248
     */
249
    public function deleteItems(array $keys): bool
250
    {
251
        foreach ($keys as $key) {
252
            $this->delete($key);
253
        }
254
255
        return true;
256
    }
257
258
    /**
259
     * 立刻为「CacheItemInterface」对象做数据持久化。
260
     * @access public
261
     * @param  CacheItemInterface $item
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
262
     * @return bool
263
     */
264
    public function save(CacheItemInterface $item): bool
265
    {
266
        if ($item->getKey()) {
267
            return $this->set($item->getKey(), $item->get(), $item->getExpire());
268
        }
269
270
        return false;
271
    }
272
273
    /**
274
     * 稍后为「CacheItemInterface」对象做数据持久化。
275
     * @access public
276
     * @param  CacheItemInterface $item
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
277
     * @return bool
278
     */
279
    public function saveDeferred(CacheItemInterface $item): bool
280
    {
281
        $this->deferred[$item->getKey()] = $item;
282
        return true;
283
    }
284
285
    /**
286
     * 提交所有的正在队列里等待的请求到数据持久层,配合 `saveDeferred()` 使用
287
     * @access public
288
     * @return bool
289
     */
290
    public function commit(): bool
291
    {
292
        foreach ($this->deferred as $key => $item) {
293
            $result = $this->save($item);
294
            unset($this->deferred[$key]);
295
296
            if (false === $result) {
297
                return false;
298
            }
299
        }
300
        return true;
301
    }
302
303
    public function __call($method, $args)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __call()
Loading history...
304
    {
305
        return call_user_func_array([$this->init(), $method], $args);
306
    }
307
308
    public function __destruct()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __destruct()
Loading history...
309
    {
310
        if (!empty($this->deferred)) {
311
            $this->commit();
312
        }
313
    }
314
315
}
316