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

RedisDataManager::tablesCount()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 21
cp 0
rs 9.2088
c 0
b 0
f 0
cc 5
nc 5
nop 0
crap 30
1
<?php
2
3
namespace UniMan\Drivers\Redis;
4
5
use Redis;
6
use RedisProxy\RedisProxy;
7
use UniMan\Core\DataManager\AbstractDataManager;
8
use UniMan\Core\Utils\Filter;
9
use UniMan\Core\Utils\Multisort;
10
use UniMan\Drivers\Redis\RedisDatabaseAliasStorage;
11
12
class RedisDataManager extends AbstractDataManager
13
{
14
    private $connection;
15
16
    private $databaseAliasStorage;
17
18
    private $itemsCountCache = false;
19
20 2
    public function __construct(RedisProxy $connection, RedisDatabaseAliasStorage $databaseAliasStorage)
21
    {
22 2
        $this->connection = $connection;
23 2
        $this->databaseAliasStorage = $databaseAliasStorage;
24 2
    }
25
26
    public function databases(array $sorting = [])
27
    {
28
        $keyspace = $this->connection->info('keyspace');
29
        $aliases = $this->databaseAliasStorage->loadAll();
30
        $databases = [];
31
        foreach ($keyspace as $db => $info) {
32
            $db = str_replace('db', '', $db);
33
            $alias = isset($aliases[$db]) ? ' (' . $aliases[$db] . ')' : '';
34
            $info['database'] = $db . $alias;
35
            $databases[$db] = $info;
36
        }
37
        return Multisort::sort($databases, $sorting);
38
    }
39
40
    protected function getDatabaseNameColumn()
41
    {
42
        return 'database';
43
    }
44
45
    public function tablesCount()
46
    {
47
        $tables = [
48
            RedisDriver::TYPE_KEY => 0,
49
            RedisDriver::TYPE_HASH => 0,
50
            RedisDriver::TYPE_SET => 0,
51
        ];
52
        foreach ($this->connection->keys('*') as $key) {
53
            $type = $this->connection->type($key);
54
            switch ($type) {
55
                case RedisProxy::TYPE_STRING:
56
                    $tables[RedisDriver::TYPE_KEY]++;
57
                    break;
58
                case RedisProxy::TYPE_HASH:
59
                    $tables[RedisDriver::TYPE_HASH]++;
60
                    break;
61
                case RedisProxy::TYPE_SET:
62
                    $tables[RedisDriver::TYPE_SET]++;
63
                    break;
64
                default:
65
                    break;
66
            }
67
        }
68
        return $tables;
69
    }
70
71
    public function tables(array $sorting = [])
72
    {
73
        $tables = [
74
            RedisDriver::TYPE_KEY => [
75
                'list_of_all_keys' => [
76
                    'key' => 'Show all keys',
77
                    'number_of_keys' => 0,
78
                ]
79
            ],
80
            RedisDriver::TYPE_HASH => [],
81
            RedisDriver::TYPE_SET => [],
82
        ];
83
        foreach ($this->connection->keys('*') as $key) {
84
            $type = $this->connection->type($key);
85
            if ($type === RedisProxy::TYPE_STRING) {
86
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
87
            } elseif ($type === RedisProxy::TYPE_HASH) {
88
                $result = $this->connection->hlen($key);
89
                $tables[RedisDriver::TYPE_HASH][$key] = [
90
                    'key' => $key,
91
                    'number_of_fields' => $result,
92
                ];
93
            } elseif ($type === RedisProxy::TYPE_SET) {
94
                $result = $this->connection->scard($key);
95
                $tables[RedisDriver::TYPE_SET][$key] = [
96
                    'key' => $key,
97
                    'number_of_members' => $result,
98
                ];
99
            }
100
            // TODO list and sorted set
101
        }
102
        return [
103
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
104
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
105
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
106
        ];
107
    }
108
109
    public function itemsCount($type, $table, array $filter = [])
110
    {
111
        if ($this->itemsCountCache !== false) {
112
            return $this->itemsCountCache;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->itemsCountCache; (boolean) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...erInterface::itemsCount of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
113
        }
114
        if ($type == RedisDriver::TYPE_HASH) {
115
            if (!$filter) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $filter of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
116
                $this->itemsCountCache = $this->connection->hlen($table);
117
                return $this->itemsCountCache;
118
            } else {
119
                $totalItems = 0;
120
                foreach ($filter as $filterParts) {
121
                    if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
122
                        $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
123
                        if ($res) {
124
                            $item = [
125
                                'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
126
                                'length' => strlen($res),
127
                                'value' => $res,
128
                            ];
129
                            if (Filter::apply($item, $filter)) {
130
                                $totalItems++;
131
                            }
132
                        }
133
                        $this->itemsCountCache = $totalItems;
0 ignored issues
show
Documentation Bug introduced by
The property $itemsCountCache was declared of type boolean, but $totalItems is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
134
                        return $this->itemsCountCache;
135
                    }
136
                }
137
                $iterator = '';
138
                do {
139
                    $pattern = null;
140
                    $res = $this->connection->hscan($table, $iterator, $pattern, 1000);
141
                    $res = $res ?: [];
142 View Code Duplication
                    foreach ($res as $key => $value) {
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...
143
                        $item = [
144
                            'key' => $key,
145
                            'length' => strlen($value),
146
                            'value' => $value,
147
                        ];
148
                        if (Filter::apply($item, $filter)) {
149
                            $totalItems++;
150
                        }
151
                    }
152
                } while ($iterator !== 0);
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $iterator (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
153
                $this->itemsCountCache = $totalItems;
154
                return $this->itemsCountCache;
155
            }
156
        }
157
        if ($type == RedisDriver::TYPE_KEY) {
158
            $totalItems = 0;
159
            foreach ($this->connection->keys('*') as $key) {
160
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
161
                    continue;
162
                }
163
                $result = $this->connection->get($key);
164
                $item = [
165
                    'key' => $key,
166
                    'value' => $result,
167
                    'length' => strlen($result),
168
                ];
169
170
                if (Filter::apply($item, $filter)) {
171
                    $totalItems++;
172
                }
173
            }
174
            return $totalItems;
175
        }
176
        if ($type == RedisDriver::TYPE_SET) {
177
            if (!$filter) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $filter of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
178
                return $this->connection->scard($table);
179
            }
180
            $iterator = '';
181
            $totalItems = 0;
182
            do {
183
                $res = $this->connection->sscan($table, $iterator, null, 1000);
184
                $res = $res ?: [];
185 View Code Duplication
                foreach ($res as $member) {
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...
186
                    $item = [
187
                        'member' => $member,
188
                        'length' => strlen($member),
189
                    ];
190
                    if (Filter::apply($item, $filter)) {
191
                        $totalItems++;
192
                    }
193
                }
194
            } while ($iterator !== 0);
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $iterator (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
195
            return $totalItems;
196
        }
197
        return 0;
198
    }
199
200
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
201
    {
202
        $items = [];
203
        $offset = ($page - 1) * $onPage;
204
        $skipped = 0;
205
        if ($type == RedisDriver::TYPE_HASH) {
206
            foreach ($filter as $filterParts) {
207
                if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
208
                    $items = [];
209
                    $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
210
                    if ($res) {
211
                        $item = [
212
                            'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
213
                            'length' => strlen($res),
214
                            'value' => $res,
215
                        ];
216
                        if (Filter::apply($item, $filter)) {
217
                            $items[$item['key']] = $item;
218
                        }
219
                    }
220
                    return $items;
221
                }
222
            }
223
224
225
            $iterator = '';
226
            do {
227
                $pattern = null;
228
                $res = $this->connection->hscan($table, $iterator, $pattern, $onPage * 10);
229
                $res = $res ?: [];
230
                foreach ($res as $key => $value) {
231
                    $item = [
232
                        'key' => $key,
233
                        'length' => strlen($value),
234
                        'value' => $value,
235
                    ];
236 View Code Duplication
                    if (Filter::apply($item, $filter)) {
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...
237
                        if ($skipped < $offset) {
238
                            $skipped++;
239
                        } else {
240
                            $items[$key] = $item;
241
                            if (count($items) === $onPage) {
242
                                break;
243
                            }
244
                        }
245
                    }
246
                }
247
            } while ($iterator !== 0 && count($items) < $onPage);
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $iterator (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
248
        } elseif ($type == RedisDriver::TYPE_KEY) {
249
            foreach ($this->connection->keys('*') as $key) {
250
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
251
                    continue;
252
                }
253
                $result = $this->connection->get($key);
254
255
                $item = [
256
                    'key' => $key,
257
                    'value' => $result,
258
                    'length' => strlen($result),
259
                ];
260
261 View Code Duplication
                if (Filter::apply($item, $filter)) {
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...
262
                    if ($skipped < $offset) {
263
                        $skipped++;
264
                    } else {
265
                        $items[$key] = $item;
266
                        if (count($items) === $onPage) {
267
                            break;
268
                        }
269
                    }
270
                }
271
            }
272
        } elseif ($type == RedisDriver::TYPE_SET) {
273
            $iterator = '';
274
            do {
275
                $pattern = null;
276
                $res = $this->connection->sscan($table, $iterator, $pattern, $onPage * 10);
277
                $res = $res ?: [];
278
                foreach ($res as $member) {
279
                    $item = [
280
                        'member' => $member,
281
                        'length' => strlen($member),
282
                    ];
283
                    if (Filter::apply($item, $filter)) {
284
                        $items[$member] = $item;
285
                        if (count($items) === $onPage) {
286
                            break;
287
                        }
288
                    }
289
                }
290
            } while ($iterator !== 0 && count($items) < $onPage);
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $iterator (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
291
        }
292
293
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
294
            $items = Multisort::sort($items, $sorting);
295
        } elseif ($sorting) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sorting of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
296
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
297
        }
298
299
        return $items;
300
    }
301
302
    public function deleteItem($type, $table, $item)
303
    {
304
        if ($type == RedisDriver::TYPE_HASH) {
305
            return $this->connection->hdel($table, $item);
306
        }
307
        if ($type == RedisDriver::TYPE_KEY) {
308
            return $this->connection->del($item);
309
        }
310
        if ($type == RedisDriver::TYPE_SET) {
311
            return $this->connection->srem($table, $item);
312
        }
313
        return parent::deleteItem($type, $table, $item);
314
    }
315
316
    public function deleteTable($type, $table)
317
    {
318
        return $this->connection->del($table);
319
    }
320
321
    public function selectDatabase($database)
322
    {
323
        $this->connection->select($database);
324
    }
325
326
    public function execute($commands)
327
    {
328
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
329
            return $command;
330
        });
331
332
        $results = [];
333
        foreach ($listOfCommands as $command) {
334
            $commandParts = explode(' ', $command);
335
            $function = array_shift($commandParts);
336
            $function = strtolower($function);
337
            $results[$command]['headers'] = $this->headers($function);
338
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
339
            $items = $this->getItems($function, $rows);
340
            $results[$command]['items'] = $items;
341
            $results[$command]['count'] = count($items);
342
        }
343
        return $results;
344
    }
345
346
    private function headers($function)
347
    {
348
        if ($function === 'get' || $function === 'hget') {
349
            return ['value'];
350
        }
351
        if ($function === 'keys') {
352
            return ['key'];
353
        }
354
        if ($function === 'hgetall') {
355
            return ['key', 'value'];
356
        }
357
        if ($function === 'hlen') {
358
            return ['items_count'];
359
        }
360
        return [];
361
    }
362
363
    private function getItems($function, $rows)
364
    {
365
        $items = [];
366
        if ($function === 'keys') {
367
            foreach ($rows as $key) {
368
                $items[] = [$key];
369
            }
370
        } elseif ($function === 'hgetall') {
371
            foreach ($rows as $key => $value) {
372
                $items[] = [$key, $value];
373
            }
374
        } else {
375
            return [[$rows]];
376
        }
377
        return $items;
378
    }
379
}
380