Completed
Push — master ( 921d57...18f6a2 )
by Michal
02:03
created

RedisDataManager::deleteItem()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 14
cp 0
rs 8.9617
c 0
b 0
f 0
cc 6
nc 6
nop 3
crap 42
1
<?php
2
3
namespace UniMan\Drivers\Redis;
4
5
use RedisProxy\RedisProxy;
6
use UniMan\Core\DataManager\AbstractDataManager;
7
use UniMan\Core\Utils\Multisort;
8
use UniMan\Drivers\Redis\DataManager\RedisHashDataManager;
9
use UniMan\Drivers\Redis\DataManager\RedisKeyDataManager;
10
use UniMan\Drivers\Redis\DataManager\RedisListDataManager;
11
use UniMan\Drivers\Redis\DataManager\RedisSetDataManager;
12
use UniMan\Drivers\Redis\DataManager\RedisSortedSetDataManager;
13
use UniMan\Drivers\Redis\RedisDatabaseAliasStorage;
14
15
class RedisDataManager extends AbstractDataManager
16
{
17
    private $connection;
18
19
    private $databaseAliasStorage;
20
21
    private $itemsCountCache = false;
22
23 2
    public function __construct(RedisProxy $connection, RedisDatabaseAliasStorage $databaseAliasStorage)
24
    {
25 2
        $this->connection = $connection;
26 2
        $this->databaseAliasStorage = $databaseAliasStorage;
27 2
    }
28
29
    public function databases(array $sorting = [])
30
    {
31
        $keyspace = $this->connection->info('keyspace');
32
        $aliases = $this->databaseAliasStorage->loadAll();
33
        $databases = [];
34
        foreach ($keyspace as $db => $info) {
35
            $db = str_replace('db', '', $db);
36
            $alias = isset($aliases[$db]) ? ' (' . $aliases[$db] . ')' : '';
37
            $info['database'] = $db . $alias;
38
            $databases[$db] = $info;
39
        }
40
        return Multisort::sort($databases, $sorting);
41
    }
42
43
    protected function getDatabaseNameColumn()
44
    {
45
        return 'database';
46
    }
47
48
    public function tablesCount()
49
    {
50
        $tables = [
51
            RedisDriver::TYPE_KEY => 0,
52
            RedisDriver::TYPE_HASH => 0,
53
            RedisDriver::TYPE_SET => 0,
54
            RedisDriver::TYPE_LIST => 0,
55
            RedisDriver::TYPE_SORTED_SET => 0,
56
        ];
57
        foreach ($this->connection->keys('*') as $key) {
58
            $type = $this->connection->type($key);
59
            switch ($type) {
60
                case RedisProxy::TYPE_STRING:
61
                    $tables[RedisDriver::TYPE_KEY]++;
62
                    break;
63
                case RedisProxy::TYPE_HASH:
64
                    $tables[RedisDriver::TYPE_HASH]++;
65
                    break;
66
                case RedisProxy::TYPE_SET:
67
                    $tables[RedisDriver::TYPE_SET]++;
68
                    break;
69
                case RedisProxy::TYPE_LIST:
70
                    $tables[RedisDriver::TYPE_LIST]++;
71
                    break;
72
                case RedisProxy::TYPE_SORTED_SET:
73
                    $tables[RedisDriver::TYPE_SORTED_SET]++;
74
                    break;
75
                default:
76
                    break;
77
            }
78
        }
79
        return $tables;
80
    }
81
82
    public function tables(array $sorting = [])
83
    {
84
        $tables = [
85
            RedisDriver::TYPE_KEY => [
86
                'list_of_all_keys' => [
87
                    'key' => 'Show all keys',
88
                    'number_of_keys' => 0,
89
                ]
90
            ],
91
            RedisDriver::TYPE_HASH => [],
92
            RedisDriver::TYPE_SET => [],
93
            RedisDriver::TYPE_LIST => [],
94
            RedisDriver::TYPE_SORTED_SET => [],
95
        ];
96
        foreach ($this->connection->keys('*') as $key) {
97
            $type = $this->connection->type($key);
98
            if ($type === RedisProxy::TYPE_STRING) {
99
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
100 View Code Duplication
            } elseif ($type === RedisProxy::TYPE_HASH) {
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...
101
                $result = $this->connection->hlen($key);
102
                $ttl = $this->connection->ttl($key);
103
                $tables[RedisDriver::TYPE_HASH][$key] = [
104
                    'key' => $key,
105
                    'number_of_fields' => $result,
106
                    'ttl' => $ttl > 0 ? $ttl : null,
107
                ];
108
            } elseif ($type === RedisProxy::TYPE_SET) {
109
                $result = $this->connection->scard($key);
110
                $ttl = $this->connection->ttl($key);
111
                $tables[RedisDriver::TYPE_SET][$key] = [
112
                    'key' => $key,
113
                    'number_of_members' => $result,
114
                    'ttl' => $ttl > 0 ? $ttl : null,
115
                ];
116 View Code Duplication
            } elseif ($type === RedisProxy::TYPE_LIST) {
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...
117
                $result = $this->connection->llen($key);
118
                $ttl = $this->connection->ttl($key);
119
                $tables[RedisDriver::TYPE_LIST][$key] = [
120
                    'key' => $key,
121
                    'number_of_elements' => $result,
122
                    'ttl' => $ttl > 0 ? $ttl : null,
123
                ];
124
            } elseif ($type === RedisProxy::TYPE_SORTED_SET) {
125
                $result = $this->connection->zcard($key);
126
                $ttl = $this->connection->ttl($key);
127
                $tables[RedisDriver::TYPE_SORTED_SET][$key] = [
128
                    'key' => $key,
129
                    'number_of_members' => $result,
130
                    'ttl' => $ttl > 0 ? $ttl : null,
131
                ];
132
            }
133
        }
134
        return [
135
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
136
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
137
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
138
            RedisDriver::TYPE_LIST => Multisort::sort($tables[RedisDriver::TYPE_LIST], $sorting),
139
            RedisDriver::TYPE_SORTED_SET => Multisort::sort($tables[RedisDriver::TYPE_SORTED_SET], $sorting),
140
        ];
141
    }
142
143
    public function itemsCount($type, $table, array $filter = [])
144
    {
145
        if ($this->itemsCountCache !== false) {
146
            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...
147
        }
148
        $itemsCount = 0;
149
        if ($type === RedisDriver::TYPE_KEY) {
150
            $manager = new RedisKeyDataManager($this->connection);
151
            $itemsCount = $manager->itemsCount($filter);
152 View Code Duplication
        } elseif ($type === RedisDriver::TYPE_HASH) {
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...
153
            $manager = new RedisHashDataManager($this->connection);
154
            $itemsCount = $manager->itemsCount($table, $filter);
155
        } elseif ($type === RedisDriver::TYPE_SET) {
156
            $manager = new RedisSetDataManager($this->connection);
157
            $itemsCount = $manager->itemsCount($table, $filter);
158 View Code Duplication
        } elseif ($type === RedisDriver::TYPE_LIST) {
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
            $manager = new RedisListDataManager($this->connection);
160
            $itemsCount = $manager->itemsCount($table, $filter);
161
        } elseif ($type === RedisDriver::TYPE_SORTED_SET) {
162
            $manager = new RedisSortedSetDataManager($this->connection);
163
            $itemsCount = $manager->itemsCount($table, $filter);
164
        }
165
        $this->itemsCountCache = $itemsCount;
0 ignored issues
show
Documentation Bug introduced by
The property $itemsCountCache was declared of type boolean, but $itemsCount 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...
166
        return $itemsCount;
167
    }
168
169
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
170
    {
171
        $items = [];
172
        if ($type === RedisDriver::TYPE_KEY) {
173
            $manager = new RedisKeyDataManager($this->connection);
174
            $items = $manager->items($page, $onPage, $filter);
175 View Code Duplication
        } elseif ($type === RedisDriver::TYPE_HASH) {
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...
176
            $manager = new RedisHashDataManager($this->connection);
177
            $items = $manager->items($table, $page, $onPage, $filter);
178
        } elseif ($type === RedisDriver::TYPE_SET) {
179
            $manager = new RedisSetDataManager($this->connection);
180
            $items = $manager->items($table, $page, $onPage, $filter);
181 View Code Duplication
        } elseif ($type === RedisDriver::TYPE_LIST) {
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...
182
            $manager = new RedisListDataManager($this->connection);
183
            $items = $manager->items($table, $page, $onPage, $filter);
184
        } elseif ($type === RedisDriver::TYPE_SORTED_SET) {
185
            $manager = new RedisSortedSetDataManager($this->connection);
186
            $items = $manager->items($table, $page, $onPage, $filter);
187
        }
188
189
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
190
            $items = Multisort::sort($items, $sorting);
191
        } 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...
192
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
193
        }
194
195
        return $items;
196
    }
197
198
    public function deleteItem($type, $table, $item)
199
    {
200
        if ($type === RedisDriver::TYPE_HASH) {
201
            return $this->connection->hdel($table, $item);
202
        }
203
        if ($type === RedisDriver::TYPE_KEY) {
204
            return $this->connection->del($item);
205
        }
206
        if ($type === RedisDriver::TYPE_SET) {
207
            return $this->connection->srem($table, $item);
208
        }
209
        if ($type === RedisDriver::TYPE_LIST) {
210
            $value = md5(uniqid());
211
            $this->connection->lset($table, $item, $value);
212
            return $this->connection->lrem($table, $value);
213
        }
214
        if ($type === RedisDriver::TYPE_SORTED_SET) {
215
            return $this->connection->zrem($table, $item);
216
        }
217
        return parent::deleteItem($type, $table, $item);
218
    }
219
220
    public function deleteTable($type, $table)
221
    {
222
        return $this->connection->del($table);
223
    }
224
225
    public function selectDatabase($database)
226
    {
227
        $this->connection->select($database);
228
    }
229
230
    public function execute($commands)
231
    {
232
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
233
            return $command;
234
        });
235
236
        $results = [];
237
        foreach ($listOfCommands as $command) {
238
            $commandParts = explode(' ', $command);
239
            $function = array_shift($commandParts);
240
            $function = strtolower($function);
241
            $results[$command]['headers'] = $this->headers($function);
242
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
243
            $items = $this->getItems($function, $rows);
244
            $results[$command]['items'] = $items;
245
            $results[$command]['count'] = count($items);
246
        }
247
        return $results;
248
    }
249
250
    private function headers($function)
251
    {
252
        if ($function === 'get' || $function === 'hget') {
253
            return ['value'];
254
        }
255
        if ($function === 'keys') {
256
            return ['key'];
257
        }
258
        if ($function === 'hgetall') {
259
            return ['key', 'value'];
260
        }
261
        if ($function === 'hlen') {
262
            return ['items_count'];
263
        }
264
        return [];
265
    }
266
267
    private function getItems($function, $rows)
268
    {
269
        $items = [];
270
        if ($function === 'keys') {
271
            foreach ($rows as $key) {
272
                $items[] = [$key];
273
            }
274
        } elseif ($function === 'hgetall') {
275
            foreach ($rows as $key => $value) {
276
                $items[] = [$key, $value];
277
            }
278
        } else {
279
            return [[$rows]];
280
        }
281
        return $items;
282
    }
283
}
284