Completed
Pull Request — master (#30)
by Michal
06:38 queued 01:51
created

RedisDataManager::tablesCount()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 0
cts 24
cp 0
rs 8.4746
c 0
b 0
f 0
cc 7
nc 7
nop 0
crap 56
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:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
73
                    $tables[RedisDriver::TYPE_SORTED_SET]++;
74
                default:
75
                    break;
76
            }
77
        }
78
        return $tables;
79
    }
80
81
    public function tables(array $sorting = [])
82
    {
83
        $tables = [
84
            RedisDriver::TYPE_KEY => [
85
                'list_of_all_keys' => [
86
                    'key' => 'Show all keys',
87
                    'number_of_keys' => 0,
88
                ]
89
            ],
90
            RedisDriver::TYPE_HASH => [],
91
            RedisDriver::TYPE_SET => [],
92
            RedisDriver::TYPE_LIST => [],
93
            RedisDriver::TYPE_SORTED_SET => [],
94
        ];
95
        foreach ($this->connection->keys('*') as $key) {
96
            $type = $this->connection->type($key);
97
            if ($type === RedisProxy::TYPE_STRING) {
98
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
99 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...
100
                $result = $this->connection->hlen($key);
101
                $ttl = $this->connection->ttl($key);
102
                $tables[RedisDriver::TYPE_HASH][$key] = [
103
                    'key' => $key,
104
                    'number_of_fields' => $result,
105
                    'ttl' => $ttl > 0 ? $ttl : null,
106
                ];
107
            } elseif ($type === RedisProxy::TYPE_SET) {
108
                $result = $this->connection->scard($key);
109
                $ttl = $this->connection->ttl($key);
110
                $tables[RedisDriver::TYPE_SET][$key] = [
111
                    'key' => $key,
112
                    'number_of_members' => $result,
113
                    'ttl' => $ttl > 0 ? $ttl : null,
114
                ];
115 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...
116
                $result = $this->connection->llen($key);
117
                $ttl = $this->connection->ttl($key);
118
                $tables[RedisDriver::TYPE_LIST][$key] = [
119
                    'key' => $key,
120
                    'number_of_elements' => $result,
121
                    'ttl' => $ttl > 0 ? $ttl : null,
122
                ];
123
            } elseif ($type === RedisProxy::TYPE_SORTED_SET) {
124
                $result = $this->connection->zcard($key);
125
                $ttl = $this->connection->ttl($key);
126
                $tables[RedisDriver::TYPE_SORTED_SET][$key] = [
127
                    'key' => $key,
128
                    'number_of_members' => $result,
129
                    'ttl' => $ttl > 0 ? $ttl : null,
130
                ];
131
            }
132
        }
133
        return [
134
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
135
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
136
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
137
            RedisDriver::TYPE_LIST => Multisort::sort($tables[RedisDriver::TYPE_LIST], $sorting),
138
            RedisDriver::TYPE_SORTED_SET => Multisort::sort($tables[RedisDriver::TYPE_SORTED_SET], $sorting),
139
        ];
140
    }
141
142
    public function itemsCount($type, $table, array $filter = [])
143
    {
144
        if ($this->itemsCountCache !== false) {
145
            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...
146
        }
147
        $itemsCount = 0;
148
        if ($type === RedisDriver::TYPE_KEY) {
149
            $manager = new RedisKeyDataManager($this->connection);
150
            $itemsCount = $manager->itemsCount($filter);
151 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...
152
            $manager = new RedisHashDataManager($this->connection);
153
            $itemsCount = $manager->itemsCount($table, $filter);
154
        } elseif ($type === RedisDriver::TYPE_SET) {
155
            $manager = new RedisSetDataManager($this->connection);
156
            $itemsCount = $manager->itemsCount($table, $filter);
157 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...
158
            $manager = new RedisListDataManager($this->connection);
159
            $itemsCount = $manager->itemsCount($table, $filter);
160
        } elseif ($type === RedisDriver::TYPE_SORTED_SET) {
161
            $manager = new RedisSortedSetDataManager($this->connection);
162
            $itemsCount = $manager->itemsCount($table, $filter);
163
        }
164
        $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...
165
        return $itemsCount;
166
    }
167
168
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
169
    {
170
        $items = [];
171
        if ($type === RedisDriver::TYPE_KEY) {
172
            $manager = new RedisKeyDataManager($this->connection);
173
            $items = $manager->items($page, $onPage, $filter);
174 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...
175
            $manager = new RedisHashDataManager($this->connection);
176
            $items = $manager->items($table, $page, $onPage, $filter);
177
        } elseif ($type === RedisDriver::TYPE_SET) {
178
            $manager = new RedisSetDataManager($this->connection);
179
            $items = $manager->items($table, $page, $onPage, $filter);
180 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...
181
            $manager = new RedisListDataManager($this->connection);
182
            $items = $manager->items($table, $page, $onPage, $filter);
183
        } elseif ($type === RedisDriver::TYPE_SORTED_SET) {
184
            $manager = new RedisSortedSetDataManager($this->connection);
185
            $items = $manager->items($table, $page, $onPage, $filter);
186
        }
187
188
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
189
            $items = Multisort::sort($items, $sorting);
190
        } 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...
191
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
192
        }
193
194
        return $items;
195
    }
196
197
    public function deleteItem($type, $table, $item)
198
    {
199
        if ($type === RedisDriver::TYPE_HASH) {
200
            return $this->connection->hdel($table, $item);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->hdel($table, $item); (integer) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...erInterface::deleteItem of type boolean|null.

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...
201
        }
202
        if ($type === RedisDriver::TYPE_KEY) {
203
            return $this->connection->del($item);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->del($item); (integer) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...erInterface::deleteItem of type boolean|null.

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...
204
        }
205
        if ($type === RedisDriver::TYPE_SET) {
206
            return $this->connection->srem($table, $item);
207
        }
208
        if ($type === RedisDriver::TYPE_LIST) {
209
            $value = md5(uniqid());
210
            $this->connection->lset($table, $item, $value);
211
            return $this->connection->lrem($table, $value);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->lrem($table, $value); (integer) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...erInterface::deleteItem of type boolean|null.

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...
212
        }
213
        if ($type === RedisDriver::TYPE_SORTED_SET) {
214
            return $this->connection->zrem($table, $item);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->zrem($table, $item); (integer) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...erInterface::deleteItem of type boolean|null.

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...
215
        }
216
        return parent::deleteItem($type, $table, $item);
217
    }
218
219
    public function deleteTable($type, $table)
220
    {
221
        return $this->connection->del($table);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->del($table); (integer) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...rInterface::deleteTable of type boolean|null.

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...
222
    }
223
224
    public function selectDatabase($database)
225
    {
226
        $this->connection->select($database);
227
    }
228
229
    public function execute($commands)
230
    {
231
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
232
            return $command;
233
        });
234
235
        $results = [];
236
        foreach ($listOfCommands as $command) {
237
            $commandParts = explode(' ', $command);
238
            $function = array_shift($commandParts);
239
            $function = strtolower($function);
240
            $results[$command]['headers'] = $this->headers($function);
241
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
242
            $items = $this->getItems($function, $rows);
243
            $results[$command]['items'] = $items;
244
            $results[$command]['count'] = count($items);
245
        }
246
        return $results;
247
    }
248
249
    private function headers($function)
250
    {
251
        if ($function === 'get' || $function === 'hget') {
252
            return ['value'];
253
        }
254
        if ($function === 'keys') {
255
            return ['key'];
256
        }
257
        if ($function === 'hgetall') {
258
            return ['key', 'value'];
259
        }
260
        if ($function === 'hlen') {
261
            return ['items_count'];
262
        }
263
        return [];
264
    }
265
266
    private function getItems($function, $rows)
267
    {
268
        $items = [];
269
        if ($function === 'keys') {
270
            foreach ($rows as $key) {
271
                $items[] = [$key];
272
            }
273
        } elseif ($function === 'hgetall') {
274
            foreach ($rows as $key => $value) {
275
                $items[] = [$key, $value];
276
            }
277
        } else {
278
            return [[$rows]];
279
        }
280
        return $items;
281
    }
282
}
283