Completed
Push — master ( f5adf6...a90a41 )
by Michal
02:09
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 RedisProxy\RedisProxy;
6
use UniMan\Core\DataManager\AbstractDataManager;
7
use UniMan\Core\Utils\Filter;
8
use UniMan\Core\Utils\Multisort;
9
use UniMan\Drivers\Redis\RedisDatabaseAliasStorage;
10
11
class RedisDataManager extends AbstractDataManager
12
{
13
    private $connection;
14
15
    private $databaseAliasStorage;
16
17
    private $itemsCountCache = false;
18
19 2
    public function __construct(RedisProxy $connection, RedisDatabaseAliasStorage $databaseAliasStorage)
20
    {
21 2
        $this->connection = $connection;
22 2
        $this->databaseAliasStorage = $databaseAliasStorage;
23 2
    }
24
25
    public function databases(array $sorting = [])
26
    {
27
        $keyspace = $this->connection->info('keyspace');
28
        $aliases = $this->databaseAliasStorage->loadAll();
29
        $databases = [];
30
        foreach ($keyspace as $db => $info) {
31
            $db = str_replace('db', '', $db);
32
            $alias = isset($aliases[$db]) ? ' (' . $aliases[$db] . ')' : '';
33
            $info['database'] = $db . $alias;
34
            $databases[$db] = $info;
35
        }
36
        return Multisort::sort($databases, $sorting);
37
    }
38
39
    protected function getDatabaseNameColumn()
40
    {
41
        return 'database';
42
    }
43
44
    public function tablesCount()
45
    {
46
        $tables = [
47
            RedisDriver::TYPE_KEY => 0,
48
            RedisDriver::TYPE_HASH => 0,
49
            RedisDriver::TYPE_SET => 0,
50
        ];
51
        foreach ($this->connection->keys('*') as $key) {
52
            $type = $this->connection->type($key);
53
            switch ($type) {
54
                case RedisProxy::TYPE_STRING:
55
                    $tables[RedisDriver::TYPE_KEY]++;
56
                    break;
57
                case RedisProxy::TYPE_HASH:
58
                    $tables[RedisDriver::TYPE_HASH]++;
59
                    break;
60
                case RedisProxy::TYPE_SET:
61
                    $tables[RedisDriver::TYPE_SET]++;
62
                    break;
63
                default:
64
                    break;
65
            }
66
        }
67
        return $tables;
68
    }
69
70
    public function tables(array $sorting = [])
71
    {
72
        $tables = [
73
            RedisDriver::TYPE_KEY => [
74
                'list_of_all_keys' => [
75
                    'key' => 'Show all keys',
76
                    'number_of_keys' => 0,
77
                ]
78
            ],
79
            RedisDriver::TYPE_HASH => [],
80
            RedisDriver::TYPE_SET => [],
81
        ];
82
        foreach ($this->connection->keys('*') as $key) {
83
            $type = $this->connection->type($key);
84
            if ($type === RedisProxy::TYPE_STRING) {
85
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
86
            } elseif ($type === RedisProxy::TYPE_HASH) {
87
                $result = $this->connection->hlen($key);
88
                $tables[RedisDriver::TYPE_HASH][$key] = [
89
                    'key' => $key,
90
                    'number_of_fields' => $result,
91
                ];
92
            } elseif ($type === RedisProxy::TYPE_SET) {
93
                $result = $this->connection->scard($key);
94
                $tables[RedisDriver::TYPE_SET][$key] = [
95
                    'key' => $key,
96
                    'number_of_members' => $result,
97
                ];
98
            }
99
            // TODO list and sorted set
100
        }
101
        return [
102
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
103
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
104
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
105
        ];
106
    }
107
108
    public function itemsCount($type, $table, array $filter = [])
109
    {
110
        if ($this->itemsCountCache !== false) {
111
            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...
112
        }
113
        if ($type == RedisDriver::TYPE_HASH) {
114
            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...
115
                $this->itemsCountCache = $this->connection->hlen($table);
116
                return $this->itemsCountCache;
117
            } else {
118
                $totalItems = 0;
119
                foreach ($filter as $filterParts) {
120
                    if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
121
                        $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
122
                        if ($res) {
123
                            $item = [
124
                                'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
125
                                'length' => strlen($res),
126
                                'value' => $res,
127
                            ];
128
                            if (Filter::apply($item, $filter)) {
129
                                $totalItems++;
130
                            }
131
                        }
132
                        $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...
133
                        return $this->itemsCountCache;
134
                    }
135
                }
136
                $iterator = '';
137
                do {
138
                    $pattern = null;
139
                    $res = $this->connection->hscan($table, $iterator, $pattern, 1000);
140
                    $res = $res ?: [];
141 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...
142
                        $item = [
143
                            'key' => $key,
144
                            'length' => strlen($value),
145
                            'value' => $value,
146
                        ];
147
                        if (Filter::apply($item, $filter)) {
148
                            $totalItems++;
149
                        }
150
                    }
151
                } 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...
152
                $this->itemsCountCache = $totalItems;
153
                return $this->itemsCountCache;
154
            }
155
        }
156
        if ($type == RedisDriver::TYPE_KEY) {
157
            $totalItems = 0;
158
            foreach ($this->connection->keys('*') as $key) {
159
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
160
                    continue;
161
                }
162
                $result = $this->connection->get($key);
163
                $item = [
164
                    'key' => $key,
165
                    'value' => $result,
166
                    'length' => strlen($result),
167
                ];
168
169
                if (Filter::apply($item, $filter)) {
170
                    $totalItems++;
171
                }
172
            }
173
            return $totalItems;
174
        }
175
        if ($type == RedisDriver::TYPE_SET) {
176
            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...
177
                return $this->connection->scard($table);
178
            }
179
            $iterator = '';
180
            $totalItems = 0;
181
            do {
182
                $res = $this->connection->sscan($table, $iterator, null, 1000);
183
                $res = $res ?: [];
184 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...
185
                    $item = [
186
                        'member' => $member,
187
                        'length' => strlen($member),
188
                    ];
189
                    if (Filter::apply($item, $filter)) {
190
                        $totalItems++;
191
                    }
192
                }
193
            } 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...
194
            return $totalItems;
195
        }
196
        return 0;
197
    }
198
199
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
200
    {
201
        $items = [];
202
        $offset = ($page - 1) * $onPage;
203
        $skipped = 0;
204
        if ($type == RedisDriver::TYPE_HASH) {
205
            foreach ($filter as $filterParts) {
206
                if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
207
                    $items = [];
208
                    $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
209
                    if ($res) {
210
                        $item = [
211
                            'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
212
                            'length' => strlen($res),
213
                            'value' => $res,
214
                        ];
215
                        if (Filter::apply($item, $filter)) {
216
                            $items[$item['key']] = $item;
217
                        }
218
                    }
219
                    return $items;
220
                }
221
            }
222
223
224
            $iterator = '';
225
            do {
226
                $pattern = null;
227
                $res = $this->connection->hscan($table, $iterator, $pattern, $onPage * 10);
228
                $res = $res ?: [];
229
                foreach ($res as $key => $value) {
230
                    $item = [
231
                        'key' => $key,
232
                        'length' => strlen($value),
233
                        'value' => $value,
234
                    ];
235 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...
236
                        if ($skipped < $offset) {
237
                            $skipped++;
238
                        } else {
239
                            $items[$key] = $item;
240
                            if (count($items) === $onPage) {
241
                                break;
242
                            }
243
                        }
244
                    }
245
                }
246
            } 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...
247
        } elseif ($type == RedisDriver::TYPE_KEY) {
248
            foreach ($this->connection->keys('*') as $key) {
249
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
250
                    continue;
251
                }
252
                $result = $this->connection->get($key);
253
254
                $item = [
255
                    'key' => $key,
256
                    'value' => $result,
257
                    'length' => strlen($result),
258
                ];
259
260 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...
261
                    if ($skipped < $offset) {
262
                        $skipped++;
263
                    } else {
264
                        $items[$key] = $item;
265
                        if (count($items) === $onPage) {
266
                            break;
267
                        }
268
                    }
269
                }
270
            }
271
        } elseif ($type == RedisDriver::TYPE_SET) {
272
            $iterator = '';
273
            do {
274
                $pattern = null;
275
                $res = $this->connection->sscan($table, $iterator, $pattern, $onPage * 10);
276
                $res = $res ?: [];
277
                foreach ($res as $member) {
278
                    $item = [
279
                        'member' => $member,
280
                        'length' => strlen($member),
281
                    ];
282
                    if (Filter::apply($item, $filter)) {
283
                        $items[$member] = $item;
284
                        if (count($items) === $onPage) {
285
                            break;
286
                        }
287
                    }
288
                }
289
            } 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...
290
        }
291
292
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
293
            $items = Multisort::sort($items, $sorting);
294
        } 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...
295
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
296
        }
297
298
        return $items;
299
    }
300
301
    public function deleteItem($type, $table, $item)
302
    {
303
        if ($type == RedisDriver::TYPE_HASH) {
304
            return $this->connection->hdel($table, $item);
305
        }
306
        if ($type == RedisDriver::TYPE_KEY) {
307
            return $this->connection->del($item);
308
        }
309
        if ($type == RedisDriver::TYPE_SET) {
310
            return $this->connection->srem($table, $item);
311
        }
312
        return parent::deleteItem($type, $table, $item);
313
    }
314
315
    public function deleteTable($type, $table)
316
    {
317
        return $this->connection->del($table);
318
    }
319
320
    public function selectDatabase($database)
321
    {
322
        $this->connection->select($database);
323
    }
324
325
    public function execute($commands)
326
    {
327
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
328
            return $command;
329
        });
330
331
        $results = [];
332
        foreach ($listOfCommands as $command) {
333
            $commandParts = explode(' ', $command);
334
            $function = array_shift($commandParts);
335
            $function = strtolower($function);
336
            $results[$command]['headers'] = $this->headers($function);
337
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
338
            $items = $this->getItems($function, $rows);
339
            $results[$command]['items'] = $items;
340
            $results[$command]['count'] = count($items);
341
        }
342
        return $results;
343
    }
344
345
    private function headers($function)
346
    {
347
        if ($function === 'get' || $function === 'hget') {
348
            return ['value'];
349
        }
350
        if ($function === 'keys') {
351
            return ['key'];
352
        }
353
        if ($function === 'hgetall') {
354
            return ['key', 'value'];
355
        }
356
        if ($function === 'hlen') {
357
            return ['items_count'];
358
        }
359
        return [];
360
    }
361
362
    private function getItems($function, $rows)
363
    {
364
        $items = [];
365
        if ($function === 'keys') {
366
            foreach ($rows as $key) {
367
                $items[] = [$key];
368
            }
369
        } elseif ($function === 'hgetall') {
370
            foreach ($rows as $key => $value) {
371
                $items[] = [$key, $value];
372
            }
373
        } else {
374
            return [[$rows]];
375
        }
376
        return $items;
377
    }
378
}
379