Completed
Pull Request — master (#27)
by Michal
07:40
created

RedisDataManager   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 240
Duplicated Lines 12.5 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 2.63%

Importance

Changes 0
Metric Value
wmc 50
lcom 1
cbo 7
dl 30
loc 240
ccs 4
cts 152
cp 0.0263
rs 8.4
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A databases() 0 13 3
A getDatabaseNameColumn() 0 4 1
B tablesCount() 0 28 6
B tables() 14 45 6
B itemsCount() 8 22 6
B items() 8 25 7
A deleteItem() 0 18 5
A deleteTable() 0 4 1
A selectDatabase() 0 4 1
A execute() 0 19 2
A headers() 0 16 6
A getItems() 0 16 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RedisDataManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RedisDataManager, and based on these observations, apply Extract Interface, too.

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\RedisDatabaseAliasStorage;
13
14
class RedisDataManager extends AbstractDataManager
15
{
16
    private $connection;
17
18
    private $databaseAliasStorage;
19
20
    private $itemsCountCache = false;
21
22 2
    public function __construct(RedisProxy $connection, RedisDatabaseAliasStorage $databaseAliasStorage)
23
    {
24 2
        $this->connection = $connection;
25 2
        $this->databaseAliasStorage = $databaseAliasStorage;
26 2
    }
27
28
    public function databases(array $sorting = [])
29
    {
30
        $keyspace = $this->connection->info('keyspace');
31
        $aliases = $this->databaseAliasStorage->loadAll();
32
        $databases = [];
33
        foreach ($keyspace as $db => $info) {
34
            $db = str_replace('db', '', $db);
35
            $alias = isset($aliases[$db]) ? ' (' . $aliases[$db] . ')' : '';
36
            $info['database'] = $db . $alias;
37
            $databases[$db] = $info;
38
        }
39
        return Multisort::sort($databases, $sorting);
40
    }
41
42
    protected function getDatabaseNameColumn()
43
    {
44
        return 'database';
45
    }
46
47
    public function tablesCount()
48
    {
49
        $tables = [
50
            RedisDriver::TYPE_KEY => 0,
51
            RedisDriver::TYPE_HASH => 0,
52
            RedisDriver::TYPE_SET => 0,
53
            RedisDriver::TYPE_LIST => 0,
54
        ];
55
        foreach ($this->connection->keys('*') as $key) {
56
            $type = $this->connection->type($key);
57
            switch ($type) {
58
                case RedisProxy::TYPE_STRING:
59
                    $tables[RedisDriver::TYPE_KEY]++;
60
                    break;
61
                case RedisProxy::TYPE_HASH:
62
                    $tables[RedisDriver::TYPE_HASH]++;
63
                    break;
64
                case RedisProxy::TYPE_SET:
65
                    $tables[RedisDriver::TYPE_SET]++;
66
                    break;
67
                case RedisProxy::TYPE_LIST;
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
68
                    $tables[RedisDriver::TYPE_LIST]++;
69
                default:
70
                    break;
71
            }
72
        }
73
        return $tables;
74
    }
75
76
    public function tables(array $sorting = [])
77
    {
78
        $tables = [
79
            RedisDriver::TYPE_KEY => [
80
                'list_of_all_keys' => [
81
                    'key' => 'Show all keys',
82
                    'number_of_keys' => 0,
83
                ]
84
            ],
85
            RedisDriver::TYPE_HASH => [],
86
            RedisDriver::TYPE_SET => [],
87
            RedisDriver::TYPE_LIST => [],
88
        ];
89
        foreach ($this->connection->keys('*') as $key) {
90
            $type = $this->connection->type($key);
91
            if ($type === RedisProxy::TYPE_STRING) {
92
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
93 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...
94
                $result = $this->connection->hlen($key);
95
                $tables[RedisDriver::TYPE_HASH][$key] = [
96
                    'key' => $key,
97
                    'number_of_fields' => $result,
98
                ];
99
            } elseif ($type === RedisProxy::TYPE_SET) {
100
                $result = $this->connection->scard($key);
101
                $tables[RedisDriver::TYPE_SET][$key] = [
102
                    'key' => $key,
103
                    'number_of_members' => $result,
104
                ];
105 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...
106
                $result = $this->connection->llen($key);
107
                $tables[RedisDriver::TYPE_LIST][$key] = [
108
                    'key' => $key,
109
                    'number_of_elements' => $result,
110
                ];
111
            }
112
            // TODO sorted set
113
        }
114
        return [
115
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
116
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
117
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
118
            RedisDriver::TYPE_LIST => Multisort::sort($tables[RedisDriver::TYPE_LIST], $sorting),
119
        ];
120
    }
121
122
    public function itemsCount($type, $table, array $filter = [])
123
    {
124
        if ($this->itemsCountCache !== false) {
125
            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...
126
        }
127
        $itemsCount = 0;
128
        if ($type === RedisDriver::TYPE_KEY) {
129
            $manager = new RedisKeyDataManager($this->connection);
130
            $itemsCount = $manager->itemsCount($filter);
131 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...
132
            $manager = new RedisHashDataManager($this->connection);
133
            $itemsCount = $manager->itemsCount($table, $filter);
134
        } elseif ($type === RedisDriver::TYPE_SET) {
135
            $manager = new RedisSetDataManager($this->connection);
136
            $itemsCount = $manager->itemsCount($table, $filter);
137 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...
138
            $manager = new RedisListDataManager($this->connection);
139
            $itemsCount = $manager->itemsCount($table, $filter);
140
        }
141
        $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...
142
        return $itemsCount;
143
    }
144
145
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
146
    {
147
        $items = [];
148
        if ($type === RedisDriver::TYPE_KEY) {
149
            $manager = new RedisKeyDataManager($this->connection);
150
            $items = $manager->items($page, $onPage, $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
            $items = $manager->items($table, $page, $onPage, $filter);
154
        } elseif ($type === RedisDriver::TYPE_SET) {
155
            $manager = new RedisSetDataManager($this->connection);
156
            $items = $manager->items($table, $page, $onPage, $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
            $items = $manager->items($table, $page, $onPage, $filter);
160
        }
161
162
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
163
            $items = Multisort::sort($items, $sorting);
164
        } 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...
165
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
166
        }
167
168
        return $items;
169
    }
170
171
    public function deleteItem($type, $table, $item)
172
    {
173
        if ($type === RedisDriver::TYPE_HASH) {
174
            return $this->connection->hdel($table, $item);
175
        }
176
        if ($type === RedisDriver::TYPE_KEY) {
177
            return $this->connection->del($item);
178
        }
179
        if ($type === RedisDriver::TYPE_SET) {
180
            return $this->connection->srem($table, $item);
181
        }
182
        if ($type === RedisDriver::TYPE_LIST) {
183
            $value = md5(uniqid());
184
            $this->connection->lset($table, $item, $value);
185
            return $this->connection->lrem($table, $value);
186
        }
187
        return parent::deleteItem($type, $table, $item);
188
    }
189
190
    public function deleteTable($type, $table)
191
    {
192
        return $this->connection->del($table);
193
    }
194
195
    public function selectDatabase($database)
196
    {
197
        $this->connection->select($database);
198
    }
199
200
    public function execute($commands)
201
    {
202
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
203
            return $command;
204
        });
205
206
        $results = [];
207
        foreach ($listOfCommands as $command) {
208
            $commandParts = explode(' ', $command);
209
            $function = array_shift($commandParts);
210
            $function = strtolower($function);
211
            $results[$command]['headers'] = $this->headers($function);
212
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
213
            $items = $this->getItems($function, $rows);
214
            $results[$command]['items'] = $items;
215
            $results[$command]['count'] = count($items);
216
        }
217
        return $results;
218
    }
219
220
    private function headers($function)
221
    {
222
        if ($function === 'get' || $function === 'hget') {
223
            return ['value'];
224
        }
225
        if ($function === 'keys') {
226
            return ['key'];
227
        }
228
        if ($function === 'hgetall') {
229
            return ['key', 'value'];
230
        }
231
        if ($function === 'hlen') {
232
            return ['items_count'];
233
        }
234
        return [];
235
    }
236
237
    private function getItems($function, $rows)
238
    {
239
        $items = [];
240
        if ($function === 'keys') {
241
            foreach ($rows as $key) {
242
                $items[] = [$key];
243
            }
244
        } elseif ($function === 'hgetall') {
245
            foreach ($rows as $key => $value) {
246
                $items[] = [$key, $value];
247
            }
248
        } else {
249
            return [[$rows]];
250
        }
251
        return $items;
252
    }
253
}
254