Redis::set()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 10
c 2
b 1
f 0
dl 0
loc 16
rs 9.6111
cc 5
nc 6
nop 2
1
<?php
2
3
namespace Dongdavid\Notify\utils;
4
5
class Redis
6
{
7
    const PREFIX = 'cr-';
8
    private static $redis;
9
    private static $redisConfig = [
10
        'host' => '127.0.0.1',
11
        'port' => '6379',
12
        'password' => '',
13
        'select' => 6,
14
        'timeout' => 3,
15
    ];
16
17
    // 覆盖redis连接配置
18
    public static function setConfig($config)
19
    {
20
        foreach (self::$redisConfig as $k => $v) {
21
            if (isset($config[$k])) {
22
                self::$redisConfig[$k] = $config[$k];
23
            }
24
        }
25
    }
26
27
    public static function connect($config = [])
28
    {
29
        // if (!extension_loaded('redis')) {
30
31
        // }
32
        if (self::$redis) {
33
            return self::$redis;
34
        }
35
        if (empty($config)) {
36
            $config = self::$redisConfig;
37
        }
38
        self::$redis = new \Redis();
39
        self::$redis->connect($config['host'], $config['port'], $config['timeout']);
40
        if (isset($config['password']) && !empty($config['password'])) {
41
            self::$redis->auth($config['password']);
42
        }
43
        if (isset($config['select'])) {
44
            self::$redis->select($config['select']);
45
        }
46
47
        return self::$redis;
48
    }
49
50
    public static function set($key, $value)
51
    {
52
        if (!is_string($key)) {
53
            throw new \Exception('require key type is String');
54
        }
55
        if (!is_string($value)) {
56
            if (is_array($value)) {
57
                $value = json_encode($value);
58
            } else {
59
                throw new \Exception('require value type is String or Array');
60
            }
61
        }
62
        if (!self::$redis) {
63
            self::connect();
64
        }
65
        self::$redis->set(self::PREFIX.$key, $value);
66
    }
67
68
    public static function get($key)
69
    {
70
        if (!is_string($key)) {
71
            throw new \Exception('require key type is String');
72
        }
73
        if (!self::$redis) {
74
            self::connect();
75
        }
76
77
        $value = self::$redis->get(self::PREFIX.$key);
78
        $json = json_decode($value, true);
79
80
        return $json ? $json : $value;
81
    }
82
}
83