Completed
Pull Request — master (#1)
by Michal
01:53
created

RedisProxy   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 292
Duplicated Lines 19.86 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 81.55%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 52
c 2
b 0
f 0
lcom 1
cbo 3
dl 58
loc 292
ccs 137
cts 168
cp 0.8155
rs 7.9487

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A setDriversOrder() 0 13 4
A init() 0 5 1
B prepareDriver() 0 18 7
A connect() 0 4 1
A isConnected() 0 4 1
A __call() 0 9 3
B select() 0 20 5
C info() 0 69 11
A get() 9 9 3
A del() 0 5 1
A delete() 0 4 1
A scan() 10 10 2
A hget() 9 9 3
A hdel() 0 9 2
A hscan() 10 10 2
A zscan() 10 10 2
A sscan() 10 10 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RedisProxy often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RedisProxy, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace RedisProxy;
4
5
use Exception;
6
use InvalidArgumentException;
7
use Predis\Client;
8
use Predis\Response\Status;
9
use Redis;
10
11
/**
12
 * @method boolean set(string $key, string $value) Set the string value of a key
13
 * @method array mget(array $keys) Multi get - Returns the values of all specified keys. For every key that does not hold a string value or does not exist, FALSE is returned.
14
 * @method integer hset(string $key, string $field, string $value) Set the string value of a hash field
15
 * @method array hgetall(string $key) Get all fields and values in hash
16
 * @method array hGetAll(string $key) Get all fields and values in hash
17
 * @method integer hlen(string $key) Get the number of fields in hash
18
 * @method integer hLen(string $key) Get the number of fields in hash
19
 * @method boolean flushall() Remove all keys from all databases
20
 * @method boolean flushAll() Remove all keys from all databases
21
 * @method boolean flushdb() Remove all keys from the current database
22
 * @method boolean flushDb() Remove all keys from the current database
23
 */
24
class RedisProxy
25
{
26
    const DRIVER_REDIS = 'redis';
27
28
    const DRIVER_PREDIS = 'predis';
29
30
    private $driver;
31
32
    private $host;
33
34
    private $port;
35
36
    private $database = 0;
37
38
    private $timeout;
39
40
    private $supportedDrivers = [
41
        self::DRIVER_REDIS,
42
        self::DRIVER_PREDIS,
43
    ];
44
45
    private $driversOrder = [];
46
47 44
    public function __construct($host, $port, $timeout = null)
48
    {
49 44
        $this->host = $host;
50 44
        $this->port = $port;
51 44
        $this->timeout = $timeout;
52 44
        $this->driversOrder = $this->supportedDrivers;
53 44
    }
54
55 44
    public function setDriversOrder(array $driversOrder)
56
    {
57 44
        if (empty($driversOrder)) {
58 2
            throw new InvalidArgumentException('You need to set at least one driver');
59
        }
60 42
        foreach ($driversOrder as $driver) {
61 42
            if (!in_array($driver, $this->supportedDrivers)) {
62 22
                throw new InvalidArgumentException('Driver "' . $driver . '" is not supported');
63
            }
64 20
        }
65 40
        $this->driversOrder = $driversOrder;
66 40
        return $this;
67
    }
68
69 40
    private function init()
70
    {
71 40
        $this->prepareDriver();
72 40
        $this->select($this->database);
73 40
    }
74
75 40
    private function prepareDriver()
76
    {
77 40
        if ($this->driver !== null) {
78 40
            return;
79
        }
80
81 40
        foreach ($this->driversOrder as $preferredDriver) {
82 40
            if ($preferredDriver === self::DRIVER_REDIS && extension_loaded('redis')) {
83 20
                $this->driver = new Redis();
84 20
                return;
85
            }
86 20
            if ($preferredDriver === self::DRIVER_PREDIS && class_exists('Predis\Client')) {
87 20
                $this->driver = new Client();
88 20
                return;
89
            }
90
        }
91
        throw new RedisProxyException('No redis library loaded (ext-redis or predis)');
92
    }
93
94 40
    private function connect($host, $port, $timeout = null)
95
    {
96 40
        return $this->driver->connect($host, $port, $timeout);
1 ignored issue
show
Unused Code introduced by
The call to Client::connect() has too many arguments starting with $host.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
97
    }
98
99 40
    private function isConnected()
100
    {
101 40
        return $this->driver->isConnected();
1 ignored issue
show
Bug introduced by
The method isConnected does only exist in Predis\Client, but not in Redis.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
102
    }
103
104 40
    public function __call($name, $arguments)
105
    {
106 40
        $this->init();
107 40
        $result = call_user_func_array([$this->driver, $name], $arguments);
108 40
        if ($this->driver instanceof Client && $result instanceof Status) {
109 20
            $result = $result->getPayload() === 'OK';
110 10
        }
111 40
        return $result;
112
    }
113
114
    /**
115
     * @param integer $database
116
     * @return boolean true on success
117
     * @throws RedisProxyException on failure
118
     */
119 40
    public function select($database)
120
    {
121 40
        $this->prepareDriver();
122 40
        if (!$this->isConnected()) {
123 40
            $this->connect($this->host, $this->port, $this->timeout);
124 20
        }
125
        try {
126 40
            $result = $this->driver->select($database);
1 ignored issue
show
Bug introduced by
The method select does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
127 21
        } catch (Exception $e) {
128 2
            throw new RedisProxyException('Invalid DB index');
129
        }
130 40
        if ($this->driver instanceof Client) {
131 20
            $result = $result->getPayload() === 'OK';
132 10
        }
133 40
        if ($result === false) {
134 2
            throw new RedisProxyException('Invalid DB index');
135
        }
136 40
        $this->database = $database;
137 40
        return $result;
138
    }
139
140
    /**
141
     * @param string|null $section
142
     * @return array
143
     * @todo need refactoring
144
     */
145 4
    public function info($section = null)
146
    {
147 4
        $this->init();
148 4
        if ($section === null) {
149 4
            $result = $this->driver->info();
1 ignored issue
show
Bug introduced by
The method info does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
150 2
        } else {
151 4
            $section = strtolower($section);
152 4
            $result = $this->driver->info($section);
153
        }
154
155 4
        $groupedResult = [];
156 4
        $groupedResult['keyspace'] = [];
157 4
        for ($db = 0; $db < $this->config('get', 'databases')['databases']; ++$db) {
0 ignored issues
show
Documentation Bug introduced by
The method config does not exist on object<RedisProxy\RedisProxy>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
158 4
            $groupedResult['keyspace']["db$db"] = [
159 2
                'keys' => 0,
160 2
                'expires' => null,
161 2
                'avg_ttl' => null,
162
            ];
163 2
        }
164 4
        if ($this->driver instanceof Client) {
165 2
            $result = array_change_key_case($result, CASE_LOWER);
166 2
            $groupedResult['keyspace'] = array_merge($groupedResult['keyspace'], $result['keyspace']);
167 2
            unset($result['keyspace']);
168 2
            $groupedResult = array_merge($groupedResult, $result);
169 1
        } else {
170
            $keyStartToSectionMap = [
171 2
                'redis_' => 'server',
172 1
                'uptime_' => 'server',
173 1
                'client_' => 'clients',
174 1
                'used_memory' => 'memory',
175 1
                'mem_' => 'memory',
176 1
                'rdb_' => 'persistence',
177 1
                'aof_' => 'persistence',
178 1
                'total_' => 'stats',
179 1
                'keyspace_' => 'stats',
180 1
                'repl_backlog_' => 'replication',
181 1
                'used_cpu_' => 'cpu',
182 1
                'db' => 'keyspace',
183 1
            ];
184
            $keyToSectionMap = [
185 2
                'connected_clients' => 'clients',
186 1
            ];
187 2
            foreach ($result as $key => $value) {
188 2
                foreach ($keyStartToSectionMap as $keyStart => $targetSection) {
189 2
                    if (strpos($key, $keyStart) === 0) {
190 2
                        if ($keyStart === 'db') {
191 2
                            $dbKeyspace = explode(',', $value);
192 2
                            $info['keys'] = explode('=', $dbKeyspace[0])[1];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
193 2
                            $info['expires'] = explode('=', $dbKeyspace[1])[1];
0 ignored issues
show
Bug introduced by
The variable $info does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
194 2
                            $info['avg_ttl'] = explode('=', $dbKeyspace[2])[1];
195 2
                            $value = $info;
196 1
                        }
197 2
                        $groupedResult[$targetSection][$key] = $value;
198 2
                        continue;
199
                    }
200 1
                }
201 2
                if (isset($keyToSectionMap[$key])) {
202 2
                    $groupedResult[$keyToSectionMap[$key]][$key] = $value;
203 1
                }
204 1
            }
205
        }
206
207 4
        if ($section !== null) {
208 4
            if (isset($groupedResult[$section])) {
209 4
                return $groupedResult[$section];
210
            }
211
        }
212 4
        return $groupedResult;
213
    }
214
215
    /**
216
     * @param string $key
217
     * @return string
218
     */
219 12 View Code Duplication
    public function get($key)
1 ignored issue
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...
220
    {
221 12
        $this->init();
222 12
        $result = $this->driver->get($key);
1 ignored issue
show
Bug introduced by
The method get does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
223 12
        if ($this->driver instanceof Client) {
224 6
            $result = $result === null ? false : $result;
225 3
        }
226 12
        return $result;
227
    }
228
229 12
    public function del(...$key)
230
    {
231 12
        $this->init();
232 12
        return $this->driver->del(...$key);
1 ignored issue
show
Bug introduced by
The method del does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
233
    }
234
235 8
    public function delete(...$key)
236
    {
237 8
        return $this->del(...$key);
238
    }
239
240 View Code Duplication
    public function scan(&$iterator, $pattern = null, $count = null)
1 ignored issue
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...
241
    {
242
        $this->init();
243
        if ($this->driver instanceof Client) {
244
            $returned = $this->driver->scan($iterator, ['match' => $pattern, 'count' => $count]);
245
            $iterator = $returned[0];
246
            return $returned[1];
247
        }
248
        return $this->driver->scan($iterator, $pattern, $count);
249
    }
250
251
    /**
252
     * Get the value of a hash field
253
     * @param string $key
254
     * @param string $field
255
     * @return string|boolean false if hash field is not set
256
     */
257 4 View Code Duplication
    public function hget($key, $field)
1 ignored issue
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...
258
    {
259 4
        $this->init();
260 4
        $result = $this->driver->hget($key, $field);
1 ignored issue
show
Bug introduced by
The method hget does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
261 4
        if ($this->driver instanceof Client) {
262 2
            $result = $result === null ? false : $result;
263 1
        }
264 4
        return $result;
265
    }
266
267
    /**
268
     * Delete one or more hash fields, returns number of deleted fields
269
     * @param string $key
270
     * @param array $fields
271
     * @return integer
272
     */
273 8
    public function hdel($key, ...$fields)
274
    {
275 8
        if (is_array($fields[0])) {
276 4
            $fields = $fields[0];
277 2
        }
278 8
        $res = $this->driver->hdel($key, ...$fields);
1 ignored issue
show
Bug introduced by
The method hdel does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
279
280 8
        return $res;
281
    }
282
283 View Code Duplication
    public function hscan($key, &$iterator, $pattern = null, $count = null)
1 ignored issue
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...
284
    {
285
        $this->init();
286
        if ($this->driver instanceof Client) {
287
            $returned = $this->driver->hscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
288
            $iterator = $returned[0];
289
            return $returned[1];
290
        }
291
        return $this->driver->hscan($key, $iterator, $pattern, $count);
292
    }
293
294 View Code Duplication
    public function zscan($key, &$iterator, $pattern = null, $count = null)
1 ignored issue
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...
295
    {
296
        $this->init();
297
        if ($this->driver instanceof Client) {
298
            $returned = $this->driver->zscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
299
            $iterator = $returned[0];
300
            return $returned[1];
301
        }
302
        return $this->driver->zscan($key, $iterator, $pattern, $count);
303
    }
304
305 View Code Duplication
    public function sscan($key, &$iterator, $pattern = null, $count = null)
1 ignored issue
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...
306
    {
307
        $this->init();
308
        if ($this->driver instanceof Client) {
309
            $returned = $this->driver->sscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
310
            $iterator = $returned[0];
311
            return $returned[1];
312
        }
313
        return $this->driver->sscan($key, $iterator, $pattern, $count);
314
    }
315
}
316