Predis   B
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 244
Duplicated Lines 14.34 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 4
dl 35
loc 244
rs 8.8
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 3
A increment() 0 4 1
A decrement() 0 4 1
A doLoad() 14 14 4
C doLoadMany() 21 36 8
A doLoadRaw() 0 6 2
A doSaveScalar() 0 15 3
B doRemoveByTags() 0 27 6
A doFlush() 0 21 4
A isStatusOk() 0 4 1
A doSave() 0 17 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * For the full copyright and license information, please view the LICENSE
4
 * file that was distributed with this source code.
5
 *
6
 * @author Nikita Vershinin <[email protected]>
7
 * @license MIT
8
 */
9
namespace Endeveit\Cache\Drivers;
10
11
use Endeveit\Cache\Abstracts\Common;
12
use Endeveit\Cache\Exception;
13
use Predis\Client;
14
use Predis\Connection\Aggregate\PredisCluster;
15
use Predis\Response\Status;
16
17
/**
18
 * Driver that stores data in Redis and uses Predis library
19
 * to work with it.
20
 */
21
class Predis extends Common
22
{
23
    /**
24
     * {@inheritdoc}
25
     *
26
     * Additional options:
27
     *  "client"   => the instance of \Predis\Client object
28
     *
29
     * @codeCoverageIgnore
30
     * @param  array                     $options
31
     * @throws \Endeveit\Cache\Exception
32
     */
33
    public function __construct(array $options = array())
34
    {
35
        if (!array_key_exists('client', $options) || !($options['client'] instanceof Client)) {
36
            throw new Exception('You must provide option "client" with \Predis\Client object');
37
        }
38
39
        parent::__construct($options);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     *
45
     * @param  string  $id
46
     * @param  integer $value
47
     * @return integer
48
     */
49
    public function increment($id, $value = 1)
50
    {
51
        return $this->getOption('client')->incrby($this->getPrefixedIdentifier($id), $value);
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     *
57
     * @param  string  $id
58
     * @param  integer $value
59
     * @return integer
60
     */
61
    public function decrement($id, $value = 1)
62
    {
63
        return $this->getOption('client')->decrby($this->getPrefixedIdentifier($id), $value);
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     *
69
     * @param  string      $id
70
     * @return mixed|false
71
     */
72 View Code Duplication
    protected function doLoad($id)
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...
73
    {
74
        $source = $this->getOption('client')->get($id);
75
76
        if (false !== $source) {
77
            if (is_string($source) && !is_numeric($source)) {
78
                $source = $this->getSerializer()->unserialize($source);
79
            }
80
81
            return $this->getProcessedLoadedValue($source);
82
        }
83
84
        return false;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     *
90
     * @param  array $identifiers
91
     * @return array
92
     */
93
    protected function doLoadMany(array $identifiers)
94
    {
95
        $result = array();
96
        $pipe   = $this->getOption('client')->pipeline();
97
        $now    = time();
98
99
        foreach ($identifiers as $id) {
100
            $pipe->get($id);
101
        }
102
103 View Code Duplication
        foreach ($pipe->execute() as $key => $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
104
            if (empty($row)) {
105
                continue;
106
            }
107
108
            $id = $this->getIdentifierWithoutPrefix($identifiers[$key]);
109
110
            if (is_string($row) && !is_numeric($row)) {
111
                $source = $this->getSerializer()->unserialize($row);
112
            } else {
113
                $source = array(
114
                    'data' => $row
115
                );
116
            }
117
118
            if (array_key_exists('expiresAt', $source) && ($source['expiresAt'] < $now)) {
119
                $result[$id] = false;
120
            } else {
121
                $result[$id] = $source['data'];
122
            }
123
        }
124
125
        $this->fillNotFoundKeys($result, $identifiers);
126
127
        return $result;
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     *
133
     * @param  string      $id
134
     * @return mixed|false
135
     */
136
    protected function doLoadRaw($id)
137
    {
138
        $result = $this->getOption('client')->get($id);
139
140
        return !empty($result) ? $this->getSerializer()->unserialize($result) : false;
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     *
146
     * @param  mixed   $data
147
     * @param  string  $id
148
     * @param  array   $tags
149
     * @return boolean
150
     */
151
    protected function doSave($data, $id, array $tags = array())
152
    {
153
        $pipe = $this->getOption('client')->pipeline();
154
155
        $pipe->set($id, $this->getSerializer()->serialize($data));
156
157
        // Store the tags
158
        if (!empty($tags)) {
159
            foreach (array_unique($tags) as $tag) {
160
                $pipe->sadd($tag, $id);
161
            }
162
        }
163
164
        $pipe->execute();
165
166
        return true;
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     *
172
     * @param  mixed           $data
173
     * @param  string          $id
174
     * @param  integer|boolean $lifetime
175
     * @return boolean
176
     */
177
    protected function doSaveScalar($data, $id, $lifetime = false)
178
    {
179
        $result = false;
180
181
        try {
182
            $result = $this->isStatusOk($this->getOption('client')->set($id, $this->getSerializer()->serialize($data)));
183
184
            if (false !== $lifetime) {
185
                $result = $this->isStatusOk($this->getOption('client')->expire($id, $lifetime));
186
            }
187
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
188
        }
189
190
        return $result;
191
    }
192
193
    /**
194
     * {@inheritdoc}
195
     *
196
     * @param  array   $tags
197
     * @return boolean
198
     */
199
    protected function doRemoveByTags(array $tags)
200
    {
201
        $pipe = $this->getOption('client')->pipeline();
202
203
        foreach (array_unique($tags) as $tag) {
204
            $tag         = $this->getPrefixedTag($tag);
205
            $identifiers = $this->getOption('client')->smembers($tag);
206
207
            if (is_array($identifiers)) {
208
                $identifiers = new \ArrayIterator($identifiers);
209
            }
210
211
            // Because with Predis we have a great chance to work in cluster
212
            // we must remove entries one by one
213
            if (is_object($identifiers) && ($identifiers instanceof \Iterator)) {
214
                foreach ($identifiers as $id) {
215
                    $this->remove($this->getIdentifierWithoutPrefix($id));
216
                }
217
            };
218
219
            $pipe->del($tag);
220
        }
221
222
        $pipe->execute();
223
224
        return true;
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     *
230
     * @return boolean
231
     */
232
    protected function doFlush()
233
    {
234
        $result = true;
235
236
        if ($this->getOption('client')->getConnection() instanceof PredisCluster) {
237
            /** @var \ArrayIterator $iterator */
238
            $iterator = $this->getOption('client')->getConnection()->getIterator();
239
240
            while ($iterator->valid()) {
241
                if (!$this->isStatusOk($this->getOption('client')->getClientFor($iterator->key())->flushdb())) {
242
                    $result = false;
243
                }
244
245
                $iterator->next();
246
            }
247
        } else {
248
            $result = $this->isStatusOk($this->getOption('client')->flushdb());
249
        }
250
251
        return $result;
252
    }
253
254
    /**
255
     * Checks that response status is «OK».
256
     *
257
     * @param  \Predis\Response\Status $status
258
     * @return boolean
259
     */
260
    private function isStatusOk(Status $status)
261
    {
262
        return 0 === strcasecmp($status->getPayload(), 'ok');
263
    }
264
}
265