Completed
Push — master ( fb58ff...f5adf6 )
by Michal
02:16
created

RedisDataManager::tables()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 0
cts 21
cp 0
rs 9.0168
c 0
b 0
f 0
cc 5
nc 5
nop 1
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 tables(array $sorting = [])
45
    {
46
        $tables = [
47
            RedisDriver::TYPE_KEY => [
48
                'list_of_all_keys' => [
49
                    'key' => 'Show all keys',
50
                    'number_of_keys' => 0,
51
                ]
52
            ],
53
            RedisDriver::TYPE_HASH => [],
54
            RedisDriver::TYPE_SET => [],
55
        ];
56
        foreach ($this->connection->keys('*') as $key) {
57
            $type = $this->connection->type($key);
58
            if ($type === RedisProxy::TYPE_STRING) {
59
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
60
            } elseif ($type === RedisProxy::TYPE_HASH) {
61
                $result = $this->connection->hlen($key);
62
                $tables[RedisDriver::TYPE_HASH][$key] = [
63
                    'key' => $key,
64
                    'number_of_fields' => $result,
65
                ];
66
            } elseif ($type === RedisProxy::TYPE_SET) {
67
                $result = $this->connection->scard($key);
68
                $tables[RedisDriver::TYPE_SET][$key] = [
69
                    'key' => $key,
70
                    'number_of_members' => $result,
71
                ];
72
            }
73
            // TODO list and sorted set
74
        }
75
        return [
76
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
77
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
78
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
79
        ];
80
    }
81
82
    public function itemsCount($type, $table, array $filter = [])
83
    {
84
        if ($this->itemsCountCache !== false) {
85
            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...
86
        }
87
        if ($type == RedisDriver::TYPE_HASH) {
88
            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...
89
                $this->itemsCountCache = $this->connection->hlen($table);
90
                return $this->itemsCountCache;
91
            } else {
92
                $totalItems = 0;
93
                foreach ($filter as $filterParts) {
94
                    if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
95
                        $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
96
                        if ($res) {
97
                            $item = [
98
                                'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
99
                                'length' => strlen($res),
100
                                'value' => $res,
101
                            ];
102
                            if (Filter::apply($item, $filter)) {
103
                                $totalItems++;
104
                            }
105
                        }
106
                        $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...
107
                        return $this->itemsCountCache;
108
                    }
109
                }
110
                $iterator = '';
111
                do {
112
                    $pattern = null;
113
                    $res = $this->connection->hscan($table, $iterator, $pattern, 1000);
114
                    $res = $res ?: [];
115 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...
116
                        $item = [
117
                            'key' => $key,
118
                            'length' => strlen($value),
119
                            'value' => $value,
120
                        ];
121
                        if (Filter::apply($item, $filter)) {
122
                            $totalItems++;
123
                        }
124
                    }
125
                } 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...
126
                $this->itemsCountCache = $totalItems;
127
                return $this->itemsCountCache;
128
            }
129
        }
130
        if ($type == RedisDriver::TYPE_KEY) {
131
            $totalItems = 0;
132
            foreach ($this->connection->keys('*') as $key) {
133
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
134
                    continue;
135
                }
136
                $result = $this->connection->get($key);
137
                $item = [
138
                    'key' => $key,
139
                    'value' => $result,
140
                    'length' => strlen($result),
141
                ];
142
143
                if (Filter::apply($item, $filter)) {
144
                    $totalItems++;
145
                }
146
            }
147
            return $totalItems;
148
        }
149
        if ($type == RedisDriver::TYPE_SET) {
150
            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...
151
                return $this->connection->scard($table);
152
            }
153
            $iterator = '';
154
            $totalItems = 0;
155
            do {
156
                $res = $this->connection->sscan($table, $iterator, null, 1000);
157
                $res = $res ?: [];
158 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...
159
                    $item = [
160
                        'member' => $member,
161
                        'length' => strlen($member),
162
                    ];
163
                    if (Filter::apply($item, $filter)) {
164
                        $totalItems++;
165
                    }
166
                }
167
            } 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...
168
            return $totalItems;
169
        }
170
        return 0;
171
    }
172
173
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
174
    {
175
        $items = [];
176
        $offset = ($page - 1) * $onPage;
177
        $skipped = 0;
178
        if ($type == RedisDriver::TYPE_HASH) {
179
            foreach ($filter as $filterParts) {
180
                if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
181
                    $items = [];
182
                    $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
183
                    if ($res) {
184
                        $item = [
185
                            'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
186
                            'length' => strlen($res),
187
                            'value' => $res,
188
                        ];
189
                        if (Filter::apply($item, $filter)) {
190
                            $items[$item['key']] = $item;
191
                        }
192
                    }
193
                    return $items;
194
                }
195
            }
196
197
198
            $iterator = '';
199
            do {
200
                $pattern = null;
201
                $res = $this->connection->hscan($table, $iterator, $pattern, $onPage * 10);
202
                $res = $res ?: [];
203
                foreach ($res as $key => $value) {
204
                    $item = [
205
                        'key' => $key,
206
                        'length' => strlen($value),
207
                        'value' => $value,
208
                    ];
209 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...
210
                        if ($skipped < $offset) {
211
                            $skipped++;
212
                        } else {
213
                            $items[$key] = $item;
214
                            if (count($items) === $onPage) {
215
                                break;
216
                            }
217
                        }
218
                    }
219
                }
220
            } 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...
221
        } elseif ($type == RedisDriver::TYPE_KEY) {
222
            foreach ($this->connection->keys('*') as $key) {
223
                if ($this->connection->type($key) !== RedisProxy::TYPE_STRING) {
224
                    continue;
225
                }
226
                $result = $this->connection->get($key);
227
228
                $item = [
229
                    'key' => $key,
230
                    'value' => $result,
231
                    'length' => strlen($result),
232
                ];
233
234 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...
235
                    if ($skipped < $offset) {
236
                        $skipped++;
237
                    } else {
238
                        $items[$key] = $item;
239
                        if (count($items) === $onPage) {
240
                            break;
241
                        }
242
                    }
243
                }
244
            }
245
        } elseif ($type == RedisDriver::TYPE_SET) {
246
            $iterator = '';
247
            do {
248
                $pattern = null;
249
                $res = $this->connection->sscan($table, $iterator, $pattern, $onPage * 10);
250
                $res = $res ?: [];
251
                foreach ($res as $member) {
252
                    $item = [
253
                        'member' => $member,
254
                        'length' => strlen($member),
255
                    ];
256
                    if (Filter::apply($item, $filter)) {
257
                        $items[$member] = $item;
258
                        if (count($items) === $onPage) {
259
                            break;
260
                        }
261
                    }
262
                }
263
            } 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...
264
        }
265
266
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
267
            $items = Multisort::sort($items, $sorting);
268
        } 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...
269
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
270
        }
271
272
        return $items;
273
    }
274
275
    public function deleteItem($type, $table, $item)
276
    {
277
        if ($type == RedisDriver::TYPE_HASH) {
278
            return $this->connection->hdel($table, $item);
279
        }
280
        if ($type == RedisDriver::TYPE_KEY) {
281
            return $this->connection->del($item);
282
        }
283
        if ($type == RedisDriver::TYPE_SET) {
284
            return $this->connection->srem($table, $item);
285
        }
286
        return parent::deleteItem($type, $table, $item);
287
    }
288
289
    public function deleteTable($type, $table)
290
    {
291
        return $this->connection->del($table);
292
    }
293
294
    public function selectDatabase($database)
295
    {
296
        $this->connection->select($database);
297
    }
298
299
    public function execute($commands)
300
    {
301
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
302
            return $command;
303
        });
304
305
        $results = [];
306
        foreach ($listOfCommands as $command) {
307
            $commandParts = explode(' ', $command);
308
            $function = array_shift($commandParts);
309
            $function = strtolower($function);
310
            $results[$command]['headers'] = $this->headers($function);
311
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
312
            $items = $this->getItems($function, $rows);
313
            $results[$command]['items'] = $items;
314
            $results[$command]['count'] = count($items);
315
        }
316
        return $results;
317
    }
318
319
    private function headers($function)
320
    {
321
        if ($function === 'get' || $function === 'hget') {
322
            return ['value'];
323
        }
324
        if ($function === 'keys') {
325
            return ['key'];
326
        }
327
        if ($function === 'hgetall') {
328
            return ['key', 'value'];
329
        }
330
        if ($function === 'hlen') {
331
            return ['items_count'];
332
        }
333
        return [];
334
    }
335
336
    private function getItems($function, $rows)
337
    {
338
        $items = [];
339
        if ($function === 'keys') {
340
            foreach ($rows as $key) {
341
                $items[] = [$key];
342
            }
343
        } elseif ($function === 'hgetall') {
344
            foreach ($rows as $key => $value) {
345
                $items[] = [$key, $value];
346
            }
347
        } else {
348
            return [[$rows]];
349
        }
350
        return $items;
351
    }
352
}
353