Completed
Push — master ( 3e38c4...3f7c7b )
by Michal
02:49
created

RedisDataManager   D

Complexity

Total Complexity 80

Size/Duplication

Total Lines 347
Duplicated Lines 11.24 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 1.59%

Importance

Changes 0
Metric Value
wmc 80
lcom 1
cbo 5
dl 39
loc 347
ccs 4
cts 252
cp 0.0159
rs 4.8717
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A databases() 0 13 3
A getDatabaseNameColumn() 0 4 1
B tables() 0 39 6
D itemsCount() 19 92 22
D items() 20 102 28
A deleteItem() 0 13 4
A deleteTable() 0 4 1
A selectDatabase() 0 4 1
A execute() 0 19 2
B headers() 0 16 6
B getItems() 0 16 5
A __construct() 0 5 1

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\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
                'all' => [
49
                    'key' => 'Show all keys',
50
                ]
51
            ],
52
            RedisDriver::TYPE_HASH => [],
53
            RedisDriver::TYPE_SET => [],
54
        ];
55
        $commands = [
56
            'hLen' => RedisDriver::TYPE_HASH,
57
            'sCard' => RedisDriver::TYPE_SET,
58
        ];
59
        foreach ($this->connection->keys('*') as $key) {
60
            foreach ($commands as $command => $label) {
61
                $result = $this->connection->$command($key);
62
                if ($this->connection->getLastError() !== null) {
63
                    $this->connection->clearLastError();
64
                    continue;
65
                }
66
                $tables[$label][$key] = [
67
                    'key' => $key
68
                ];
69
                if ($label == RedisDriver::TYPE_HASH) {
70
                    $tables[$label][$key]['number_of_fields'] = $result;
71
                } elseif ($label == RedisDriver::TYPE_SET) {
72
                    $tables[$label][$key]['number_of_members'] = $result;
73
                }
74
                break;
75
            }
76
        }
77
        return [
78
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
79
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
80
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
81
        ];
82
    }
83
84
    public function itemsCount($type, $table, array $filter = [])
85
    {
86
        if ($this->itemsCountCache !== false) {
87
            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...
88
        }
89
        if ($type == RedisDriver::TYPE_HASH) {
90
            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...
91
                $this->itemsCountCache = $this->connection->hLen($table);
0 ignored issues
show
Documentation Bug introduced by
The property $itemsCountCache was declared of type boolean, but $this->connection->hLen($table) 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...
92
                return $this->itemsCountCache;
93
            } else {
94
                $totalItems = 0;
95
                foreach ($filter as $filterParts) {
96
                    if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
97
                        $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
98
                        if ($res) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $res of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
99
                            $item = [
100
                                'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
101
                                'length' => strlen($res),
102
                                'value' => $res,
103
                            ];
104
                            if (Filter::apply($item, $filter)) {
105
                                $totalItems++;
106
                            }
107
                        }
108
                        $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...
109
                        return $this->itemsCountCache;
110
                    }
111
                }
112
                $iterator = '';
113
                do {
114
                    $pattern = null;
115
                    $res = $this->connection->hscan($table, $iterator, $pattern, 1000);
116
                    $res = $res ?: [];
117 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...
Bug introduced by
The expression $res of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
118
                        $item = [
119
                            'key' => $key,
120
                            'length' => strlen($value),
121
                            'value' => $value,
122
                        ];
123
                        if (Filter::apply($item, $filter)) {
124
                            $totalItems++;
125
                        }
126
                    }
127
                } while ($iterator !== 0);
128
                $this->itemsCountCache = $totalItems;
129
                return $this->itemsCountCache;
130
            }
131
        }
132
        if ($type == RedisDriver::TYPE_KEY) {
133
            $totalItems = 0;
134
            foreach ($this->connection->keys('*') as $key) {
135
                $result = $this->connection->get($key);
136
                if ($this->connection->getLastError() !== null) {
137
                    $this->connection->clearLastError();
138
                    continue;
139
                }
140
141
                $item = [
142
                    'key' => $key,
143
                    'value' => $result,
144
                    'length' => strlen($result),
145
                ];
146
147
                if (Filter::apply($item, $filter)) {
148
                    $totalItems++;
149
                }
150
            }
151
            return $totalItems;
152
        }
153
        if ($type == RedisDriver::TYPE_SET) {
154
            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...
155
                return $this->connection->scard($table);
156
            }
157
            $iterator = '';
158
            $totalItems = 0;
159
            do {
160
                $res = $this->connection->sscan($table, $iterator, null, 1000);
161
                $res = $res ?: [];
162 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...
Bug introduced by
The expression $res of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
163
                    $item = [
164
                        'member' => $member,
165
                        'length' => strlen($member),
166
                    ];
167
                    if (Filter::apply($item, $filter)) {
168
                        $totalItems++;
169
                    }
170
                }
171
            } while ($iterator !== 0);
172
            return $totalItems;
173
        }
174
        return 0;
175
    }
176
177
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
178
    {
179
        $items = [];
180
        $offset = ($page - 1) * $onPage;
181
        $skipped = 0;
182
        if ($type == RedisDriver::TYPE_HASH) {
183
            foreach ($filter as $filterParts) {
184
                if (isset($filterParts['key'][Filter::OPERATOR_EQUAL])) {
185
                    $items = [];
186
                    $res = $this->connection->hget($table, $filterParts['key'][Filter::OPERATOR_EQUAL]);
187
                    if ($res) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $res of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
188
                        $item = [
189
                            'key' => $filterParts['key'][Filter::OPERATOR_EQUAL],
190
                            'length' => strlen($res),
191
                            'value' => $res,
192
                        ];
193
                        if (Filter::apply($item, $filter)) {
194
                            $items[$item['key']] = $item;
195
                        }
196
                    }
197
                    return $items;
198
                }
199
            }
200
201
202
            $iterator = '';
203
            do {
204
                $pattern = null;
205
                $res = $this->connection->hscan($table, $iterator, $pattern, $onPage * 10);
206
                $res = $res ?: [];
207
                foreach ($res as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $res of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
208
                    $item = [
209
                        'key' => $key,
210
                        'length' => strlen($value),
211
                        'value' => $value,
212
                    ];
213 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...
214
                        if ($skipped < $offset) {
215
                            $skipped++;
216
                        } else {
217
                            $items[$key] = $item;
218
                            if (count($items) === $onPage) {
219
                                break;
220
                            }
221
                        }
222
                    }
223
                }
224
            } while ($iterator !== 0 && count($items) < $onPage);
225
        } elseif ($type == RedisDriver::TYPE_KEY) {
226
            foreach ($this->connection->keys('*') as $key) {
227
                $result = $this->connection->get($key);
228
                if ($this->connection->getLastError() !== null) {
229
                    $this->connection->clearLastError();
230
                    continue;
231
                }
232
233
                $item = [
234
                    'key' => $key,
235
                    'value' => $result,
236
                    'length' => strlen($result),
237
                ];
238
239 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...
240
                    if ($skipped < $offset) {
241
                        $skipped++;
242
                    } else {
243
                        $items[$key] = $item;
244
                        if (count($items) === $onPage) {
245
                            break;
246
                        }
247
                    }
248
                }
249
            }
250
        } elseif ($type == RedisDriver::TYPE_SET) {
251
            $iterator = '';
252
            do {
253
                $pattern = null;
254
                $res = $this->connection->sscan($table, $iterator, $pattern, $onPage * 10);
255
                $res = $res ?: [];
256
                foreach ($res as $member) {
0 ignored issues
show
Bug introduced by
The expression $res of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
257
                    $item = [
258
                        'member' => $member,
259
                        'length' => strlen($member),
260
                    ];
261
                    if (Filter::apply($item, $filter)) {
262
                        $items[$member] = $item;
263
                        if (count($items) === $onPage) {
264
                            break;
265
                        }
266
                    }
267
                }
268
            } while ($iterator !== 0 && count($items) < $onPage);
269
        }
270
271
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
272
            $items = Multisort::sort($items, $sorting);
273
        } 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...
274
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
275
        }
276
277
        return $items;
278
    }
279
280
    public function deleteItem($type, $table, $item)
281
    {
282
        if ($type == RedisDriver::TYPE_HASH) {
283
            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...
284
        }
285
        if ($type == RedisDriver::TYPE_KEY) {
286
            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...
287
        }
288
        if ($type == RedisDriver::TYPE_SET) {
289
            return $this->connection->srem($table, $item);
290
        }
291
        return parent::deleteItem($type, $table, $item);
292
    }
293
294
    public function deleteTable($type, $table)
295
    {
296
        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...
297
    }
298
299
    public function selectDatabase($database)
300
    {
301
        $this->connection->select($database);
302
    }
303
304
    public function execute($commands)
305
    {
306
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
307
            return $command;
308
        });
309
310
        $results = [];
311
        foreach ($listOfCommands as $command) {
312
            $commandParts = explode(' ', $command);
313
            $function = array_shift($commandParts);
314
            $function = strtolower($function);
315
            $results[$command]['headers'] = $this->headers($function);
316
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
317
            $items = $this->getItems($function, $rows);
318
            $results[$command]['items'] = $items;
319
            $results[$command]['count'] = count($items);
320
        }
321
        return $results;
322
    }
323
324
    private function headers($function)
325
    {
326
        if ($function === 'get' || $function === 'hget') {
327
            return ['value'];
328
        }
329
        if ($function === 'keys') {
330
            return ['key'];
331
        }
332
        if ($function === 'hgetall') {
333
            return ['key', 'value'];
334
        }
335
        if ($function === 'hlen') {
336
            return ['items_count'];
337
        }
338
        return [];
339
    }
340
341
    private function getItems($function, $rows)
342
    {
343
        $items = [];
344
        if ($function === 'keys') {
345
            foreach ($rows as $key) {
346
                $items[] = [$key];
347
            }
348
        } elseif ($function === 'hgetall') {
349
            foreach ($rows as $key => $value) {
350
                $items[] = [$key, $value];
351
            }
352
        } else {
353
            return [[$rows]];
354
        }
355
        return $items;
356
    }
357
}
358