Test Failed
Push — master ( 849d86...c80995 )
by Jay
12:00
created

Redis::set()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 13
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 18
ccs 12
cts 13
cp 0.9231
crap 4.0072
rs 9.2
1
<?php
2
namespace FMUP\Cache\Driver;
3
4
use FMUP\Cache\CacheInterface;
5
use FMUP\Cache\Exception;
6
7
/**
8
 * Class Redis
9
 * This driver needs Redis installed on server to work properly
10
 * @package FMUP\Cache\Driver
11
 */
12
class Redis implements CacheInterface
13
{
14
    const SETTINGS_REDIS = 'SETTINGS_REDIS';
15
16
    const SETTINGS_TTL_IN_SECOND = 'SETTINGS_TTL_IN_SECOND';
17
    const SETTINGS_CACHE_PREFIX = 'SETTINGS_CACHE_PREFIX';
18
19
    private $isAvailable = null;
20
    private $redisInstance = null;
21
    private $settings = array();
22
23
    /**
24
     * Check whether redis is available
25
     * @return bool
26
     */
27 2
    public function isAvailable()
28
    {
29 2
        if (!$this->isAvailable) {
30
            try {
31 2
                $this->getRedisInstance()->ping();
32 1
                $this->isAvailable = true;
33 1
            } catch (\Exception $e) {
34 1
                $this->isAvailable = false;
35
            }
36
        }
37 2
        return $this->isAvailable;
38
    }
39
40
    /**
41
     * constructor of redis
42
     * @param array $settings
43
     */
44 15
    public function __construct($settings = array())
45
    {
46 15
        if (isset($settings[self::SETTINGS_REDIS])) {
47 1
            $this->setRedisInstance($settings[self::SETTINGS_REDIS]);
48
        }
49 15
        $this->settings = $settings;
50 15
    }
51
52
    /**
53
     * Get the redis instance
54
     * @return \Predis\Client
55
     * @throws Exception
56
     */
57 4
    public function getRedisInstance()
58
    {
59 4
        if (!$this->redisInstance) {
60 1
            $this->redisInstance = $this->createRedis();
61
        }
62 4
        return $this->redisInstance;
63
    }
64
65
    /**
66
     * @return \Predis\Client|null
67
     * @throws Exception
68
     * @codeCoverageIgnore
69
     */
70
    private function createRedis()
71
    {
72
        try {
73
            $instance = new \Predis\Client($this->settings);
74
        } catch (\Exception $e) {
75
            throw new Exception('Redis is not available', $e->getCode(), $e);
76
        }
77
        return $instance;
78
    }
79
80
    /**
81
     * Define a Predis instance
82
     * @param \Predis\Client $redisInstance
83
     * @return $this
84
     */
85 3
    public function setRedisInstance(\Predis\Client $redisInstance)
86
    {
87 3
        $this->redisInstance = $redisInstance;
88 3
        return $this;
89
    }
90
91
    /**
92
     * @param string $key
93
     * @return string
94
     */
95 4
    protected function getCacheKey($key)
96
    {
97 4
        $prefix = (string)$this->getSetting(self::SETTINGS_CACHE_PREFIX);
98 4
        return $prefix . $key;
99
    }
100
101
102
    /**
103
     * Check whether a key exists
104
     * @param string $key
105
     * @return bool
106
     * @throws Exception
107
     */
108 2
    public function has($key)
109
    {
110 2
        if (!$this->isAvailable()) {
111 1
            throw new Exception('Redis is not available');
112
        }
113 1
        return $this->getRedisInstance()->exists($this->getCacheKey($key));
114
    }
115
116
    /**
117
     * @param string $key
118
     * @return mixed
119
     * @throws Exception
120
     */
121 2
    public function get($key)
122
    {
123 2
        if (!$this->isAvailable()) {
124 1
            throw new Exception('Redis is not available');
125
        }
126 1
        return unserialize($this->getRedisInstance()->get($this->getCacheKey($key)));
127
    }
128
129
    /**
130
     * Define a value for a given key in redis
131
     * @param string $key
132
     * @param mixed $value
133
     * @return $this
134
     * @throws Exception
135
     */
136 3
    public function set($key, $value)
137
    {
138 3
        if (!$this->isAvailable()) {
139 1
            throw new Exception('Redis is not available');
140
        }
141 2
        $ttl = (int)$this->getSetting(self::SETTINGS_TTL_IN_SECOND);
142 2
        $key = $this->getCacheKey($key);
143 2
        $redis = $this->getRedisInstance();
144 2
        $return = $redis->set($key, serialize($value));
145 2
        if ($ttl) {
146 2
            $redis->expireAt($key, time() + $ttl);
147 1
            $redis->ttl($key);
148
        }
149 1
        if (!$return) {
150
            throw new Exception('Error while inserting value in redis');
151
        }
152 1
        return $this;
153
    }
154
155
    /**
156
     * Delete a value in redis
157
     * @param string $key
158
     * @return $this
159
     * @throws Exception
160
     */
161 3 View Code Duplication
    public function remove($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163 3
        if (!$this->isAvailable()) {
164 1
            throw new Exception('Redis is not available');
165
        }
166 2
        $key = $this->getCacheKey($key);
167 2
        if (!$this->getRedisInstance()->del(array($key))) {
168 1
            throw new Exception('Error while deleting key in redis');
169
        }
170 1
        return $this;
171
    }
172
173
    /**
174
     * Define a setting
175
     * @param string $setting
176
     * @param mixed $value
177
     * @return $this
178
     */
179 1
    public function setSetting($setting, $value)
180
    {
181 1
        $this->settings[(string)$setting] = $value;
182 1
        return $this;
183
    }
184
185
    /**
186
     * Retrieve a defined setting
187
     * @param string $setting
188
     * @return mixed|null
189
     */
190 5
    public function getSetting($setting)
191
    {
192 5
        $setting = (string) $setting;
193 5
        return isset($this->settings[$setting]) ? $this->settings[$setting] : null;
194
    }
195
}
196