Passed
Push — 8.0 ( 280e48...6f1c01 )
by yun
02:09
created

Redis::handler()   B

Complexity

Conditions 10
Paths 14

Size

Total Lines 41
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 24
c 1
b 0
f 0
nc 14
nop 0
dl 0
loc 41
ccs 0
cts 23
cp 0
crap 110
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 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\cache\driver;
14
15
use DateInterval;
16
use DateTimeInterface;
17
use think\cache\Driver;
18
19
class Redis extends Driver
20
{
21
    /** @var \Predis\Client|\Redis */
0 ignored issues
show
Bug introduced by
The type Predis\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
    protected $handler;
23
24
    /**
25
     * 配置参数
26
     * @var array
27
     */
28
    protected $options = [
29
        'host'       => '127.0.0.1',
30
        'port'       => 6379,
31
        'password'   => '',
32
        'select'     => 0,
33
        'timeout'    => 0,
34
        'expire'     => 0,
35
        'persistent' => false,
36
        'prefix'     => '',
37
        'tag_prefix' => 'tag:',
38
        'serialize'  => [],
39
    ];
40
41
    /**
42
     * 架构函数
43
     * @access public
44
     * @param array $options 缓存参数
45
     */
46
    public function __construct(array $options = [])
47
    {
48
        if (!empty($options)) {
49
            $this->options = array_merge($this->options, $options);
50
        }
51
    }
52
53
    public function handler()
54
    {
55
        if (!$this->handler) {
56
            if (extension_loaded('redis')) {
57
                $this->handler = new \Redis;
58
59
                if ($this->options['persistent']) {
60
                    $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
61
                } else {
62
                    $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
63
                }
64
65
                if ('' != $this->options['password']) {
66
                    $this->handler->auth($this->options['password']);
67
                }
68
            } elseif (class_exists('\Predis\Client')) {
69
                $params = [];
70
                foreach ($this->options as $key => $val) {
71
                    if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
72
                        $params[$key] = $val;
73
                        unset($this->options[$key]);
74
                    }
75
                }
76
77
                if ('' == $this->options['password']) {
78
                    unset($this->options['password']);
79
                }
80
81
                $this->handler = new \Predis\Client($this->options, $params);
82
83
                $this->options['prefix'] = '';
84
            } else {
85
                throw new \BadFunctionCallException('not support: redis');
86
            }
87
88
            if (0 != $this->options['select']) {
89
                $this->handler->select((int) $this->options['select']);
90
            }
91
        }
92
93
        return $this->handler;
94
    }
95
96
    /**
97
     * 判断缓存
98
     * @access public
99
     * @param string $name 缓存变量名
100
     * @return bool
101
     */
102
    public function has($name): bool
103
    {
104
        return $this->handler()->exists($this->getCacheKey($name)) ? true : false;
105
    }
106
107
    /**
108
     * 读取缓存
109
     * @access public
110
     * @param string $name    缓存变量名
111
     * @param mixed  $default 默认值
112
     * @return mixed
113
     */
114
    public function get($name, $default = null): mixed
115
    {
116
        $key   = $this->getCacheKey($name);
117
        $value = $this->handler()->get($key);
118
119
        if (false === $value || is_null($value)) {
120
            return $default;
121
        }
122
123
        return $this->unserialize($value);
124
    }
125
126
    /**
127
     * 写入缓存
128
     * @access public
129
     * @param string                                 $name   缓存变量名
130
     * @param mixed                                  $value  存储数据
131
     * @param integer|DateInterval|DateTimeInterface $expire 有效时间(秒)
132
     * @return bool
133
     */
134
    public function set($name, $value, $expire = null): bool
135
    {
136
        if (is_null($expire)) {
137
            $expire = $this->options['expire'];
138
        }
139
140
        $key    = $this->getCacheKey($name);
141
        $expire = $this->getExpireTime($expire);
142
        $value  = $this->serialize($value);
143
144
        if ($expire) {
145
            $this->handler()->setex($key, $expire, $value);
146
        } else {
147
            $this->handler()->set($key, $value);
148
        }
149
150
        return true;
151
    }
152
153
    /**
154
     * 自增缓存(针对数值缓存)
155
     * @access public
156
     * @param string $name 缓存变量名
157
     * @param int    $step 步长
158
     * @return false|int
159
     */
160
    public function inc($name, $step = 1)
161
    {
162
        $key = $this->getCacheKey($name);
163
164
        return $this->handler()->incrby($key, $step);
165
    }
166
167
    /**
168
     * 自减缓存(针对数值缓存)
169
     * @access public
170
     * @param string $name 缓存变量名
171
     * @param int    $step 步长
172
     * @return false|int
173
     */
174
    public function dec($name, $step = 1)
175
    {
176
        $key = $this->getCacheKey($name);
177
178
        return $this->handler()->decrby($key, $step);
179
    }
180
181
    /**
182
     * 删除缓存
183
     * @access public
184
     * @param string $name 缓存变量名
185
     * @return bool
186
     */
187
    public function delete($name): bool
188
    {
189
        $key    = $this->getCacheKey($name);
190
        $result = $this->handler()->del($key);
191
        return $result > 0;
192
    }
193
194
    /**
195
     * 清除缓存
196
     * @access public
197
     * @return bool
198
     */
199
    public function clear(): bool
200
    {
201
        $this->handler()->flushDB();
202
        return true;
203
    }
204
205
    /**
206
     * 删除缓存标签
207
     * @access public
208
     * @param array $keys 缓存标识列表
209
     * @return void
210
     */
211
    public function clearTag($keys): void
212
    {
213
        // 指定标签清除
214
        $this->handler()->del($keys);
215
    }
216
217
    /**
218
     * 追加TagSet数据
219
     * @access public
220
     * @param string $name  缓存标识
221
     * @param mixed  $value 数据
222
     * @return void
223
     */
224
    public function append($name, $value): void
225
    {
226
        $key = $this->getCacheKey($name);
227
        $this->handler()->sAdd($key, $value);
228
    }
229
230
    /**
231
     * 获取标签包含的缓存标识
232
     * @access public
233
     * @param string $tag 缓存标签
234
     * @return array
235
     */
236
    public function getTagItems($tag): array
237
    {
238
        $name = $this->getTagKey($tag);
239
        $key  = $this->getCacheKey($name);
240
        return $this->handler()->sMembers($key);
241
    }
242
}
243