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

RedisProxy::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 boolean flushAll() Remove all keys from all databases
15
 * @method boolean flushDb() Remove all keys from the current database
16
 */
17
class RedisProxy
18
{
19
    const DRIVER_REDIS = 'redis';
20
21
    const DRIVER_PREDIS = 'predis';
22
23
    private $driver;
24
25
    private $host;
26
27
    private $port;
28
29
    private $database = 0;
30
31
    private $timeout;
32
33
    private $supportedDrivers = [
34
        self::DRIVER_REDIS,
35
        self::DRIVER_PREDIS,
36
    ];
37
38
    private $driversOrder = [];
39
40 28
    public function __construct($host, $port, $timeout = null)
41
    {
42 28
        $this->host = $host;
43 28
        $this->port = $port;
44 28
        $this->timeout = $timeout;
45 28
        $this->driversOrder = $this->supportedDrivers;
46 28
    }
47
48 28
    public function setDriversOrder(array $driversOrder)
49
    {
50 28
        if (empty($driversOrder)) {
51
            throw new InvalidArgumentException('You need to set at least one driver');
52
        }
53 28
        foreach ($driversOrder as $driver) {
54 28
            if (!in_array($driver, $this->supportedDrivers)) {
55 14
                throw new InvalidArgumentException('Driver "' . $driver . '" is not supported');
56
            }
57 14
        }
58 28
        $this->driversOrder = $driversOrder;
59 28
        return $this;
60
    }
61
62 28
    private function init()
63
    {
64 28
        $this->prepareDriver();
65 28
        $this->select($this->database);
66 28
    }
67
68 28
    private function prepareDriver()
69
    {
70 28
        if ($this->driver !== null) {
71 28
            return;
72
        }
73
74 28
        foreach ($this->driversOrder as $preferredDriver) {
75 28
            if ($preferredDriver === self::DRIVER_REDIS && extension_loaded('redis')) {
76 14
                $this->driver = new Redis();
77 14
                return;
78
            }
79 14
            if ($preferredDriver === self::DRIVER_PREDIS && class_exists('Predis\Client')) {
80 14
                $this->driver = new Client();
81 14
                return;
82
            }
83
        }
84
        throw new RedisProxyException('No redis library loaded (ext-redis or predis)');
85
    }
86
87 28
    private function connect($host, $port, $timeout = null)
88
    {
89 28
        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...
90
    }
91
92 28
    private function isConnected()
93
    {
94 28
        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...
95
    }
96
97 28
    public function __call($name, $arguments)
98
    {
99 28
        $this->init();
100 28
        $result = call_user_func_array([$this->driver, $name], $arguments);
101 28
        if ($this->driver instanceof Client && $result instanceof Status) {
102 14
            $result = $result->getPayload() === 'OK';
103 7
        }
104 28
        return $result;
105
    }
106
107
    /**
108
     * @param integer $database
109
     * @return boolean true on success
110
     * @throws RedisProxyException on failure
111
     */
112 28
    public function select($database)
113
    {
114 28
        $this->prepareDriver();
115 28
        if (!$this->isConnected()) {
116 28
            $this->connect($this->host, $this->port, $this->timeout);
117 14
        }
118
        try {
119 28
            $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...
120 15
        } catch (Exception $e) {
121 2
            throw new RedisProxyException('Invalid DB index');
122
        }
123 28
        if ($this->driver instanceof Client) {
124 14
            $result = $result->getPayload() === 'OK';
125 7
        }
126 28
        if ($result === false) {
127 2
            throw new RedisProxyException('Invalid DB index');
128
        }
129 28
        $this->database = $database;
130 28
        return $result;
131
    }
132
133
    /**
134
     * @param string|null $section
135
     * @return array
136
     * @todo need refactoring
137
     */
138 4
    public function info($section = null)
139
    {
140 4
        $this->init();
141 4
        if ($section === null) {
142 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...
143 2
        } else {
144 4
            $section = strtolower($section);
145 4
            $result = $this->driver->info($section);
146
        }
147
148 4
        $groupedResult = [];
149 4
        $groupedResult['keyspace'] = [];
150 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...
151 4
            $groupedResult['keyspace']["db$db"] = [
152 2
                'keys' => 0,
153 2
                'expires' => null,
154 2
                'avg_ttl' => null,
155
            ];
156 2
        }
157 4
        if ($this->driver instanceof Client) {
158 2
            $result = array_change_key_case($result, CASE_LOWER);
159 2
            $groupedResult['keyspace'] = array_merge($groupedResult['keyspace'], $result['keyspace']);
160 2
            unset($result['keyspace']);
161 2
            $groupedResult = array_merge($groupedResult, $result);
162 1
        } else {
163
            $keyStartToSectionMap = [
164 2
                'redis_' => 'server',
165 1
                'uptime_' => 'server',
166 1
                'client_' => 'clients',
167 1
                'used_memory' => 'memory',
168 1
                'mem_' => 'memory',
169 1
                'rdb_' => 'persistence',
170 1
                'aof_' => 'persistence',
171 1
                'total_' => 'stats',
172 1
                'keyspace_' => 'stats',
173 1
                'repl_backlog_' => 'replication',
174 1
                'used_cpu_' => 'cpu',
175 1
                'db' => 'keyspace',
176 1
            ];
177
            $keyToSectionMap = [
178 2
                'connected_clients' => 'clients',
179 1
            ];
180 2
            foreach ($result as $key => $value) {
181 2
                foreach ($keyStartToSectionMap as $keyStart => $targetSection) {
182 2
                    if (strpos($key, $keyStart) === 0) {
183 2
                        if ($keyStart === 'db') {
184 2
                            $dbKeyspace = explode(',', $value);
185 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...
186 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...
187 2
                            $info['avg_ttl'] = explode('=', $dbKeyspace[2])[1];
188 2
                            $value = $info;
189 1
                        }
190 2
                        $groupedResult[$targetSection][$key] = $value;
191 2
                        continue;
192
                    }
193 1
                }
194 2
                if (isset($keyToSectionMap[$key])) {
195 2
                    $groupedResult[$keyToSectionMap[$key]][$key] = $value;
196 1
                }
197 1
            }
198
        }
199
200 4
        if ($section !== null) {
201 4
            if (isset($groupedResult[$section])) {
202 4
                return $groupedResult[$section];
203
            }
204
        }
205 4
        return $groupedResult;
206
    }
207
208
    /**
209
     * @param string $key
210
     * @return string
211
     */
212 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...
213
    {
214 12
        $this->init();
215 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...
216 12
        if ($this->driver instanceof Client) {
217 6
            $result = $result === null ? false : $result;
218 3
        }
219 12
        return $result;
220
    }
221
222 8
    public function del(...$key)
223
    {
224 8
        $this->init();
225 8
        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...
226
    }
227
228 8
    public function delete(...$key)
229
    {
230 8
        return $this->del(...$key);
231
    }
232
233 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...
234
    {
235
        $this->init();
236
        if ($this->driver instanceof Client) {
237
            $returned = $this->driver->scan($iterator, ['match' => $pattern, 'count' => $count]);
238
            $iterator = $returned[0];
239
            return $returned[1];
240
        }
241
        return $this->driver->scan($iterator, $pattern, $count);
242
    }
243
244 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...
245
    {
246 4
        $this->init();
247 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...
248 4
        if ($this->driver instanceof Client) {
249 2
            $result = $result === null ? false : $result;
250 1
        }
251 4
        return $result;
252
    }
253
254 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...
255
    {
256
        $this->init();
257
        if ($this->driver instanceof Client) {
258
            $returned = $this->driver->hscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
259
            $iterator = $returned[0];
260
            return $returned[1];
261
        }
262
        return $this->driver->hscan($key, $iterator, $pattern, $count);
263
    }
264
265 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...
266
    {
267
        $this->init();
268
        if ($this->driver instanceof Client) {
269
            $returned = $this->driver->zscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
270
            $iterator = $returned[0];
271
            return $returned[1];
272
        }
273
        return $this->driver->zscan($key, $iterator, $pattern, $count);
274
    }
275
276 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...
277
    {
278
        $this->init();
279
        if ($this->driver instanceof Client) {
280
            $returned = $this->driver->sscan($key, $iterator, ['match' => $pattern, 'count' => $count]);
281
            $iterator = $returned[0];
282
            return $returned[1];
283
        }
284
        return $this->driver->sscan($key, $iterator, $pattern, $count);
285
    }
286
}
287