Completed
Push — master ( 85ddb2...d5b935 )
by Michal
11:09
created

RedisDataManager::items()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 16
cp 0
rs 8.9457
c 0
b 0
f 0
cc 6
nc 12
nop 6
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\Filter;
8
use UniMan\Core\Utils\Multisort;
9
use UniMan\Drivers\Redis\DataManager\RedisHashDataManager;
10
use UniMan\Drivers\Redis\DataManager\RedisKeyDataManager;
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
        ];
54
        foreach ($this->connection->keys('*') as $key) {
55
            $type = $this->connection->type($key);
56
            switch ($type) {
57
                case RedisProxy::TYPE_STRING:
58
                    $tables[RedisDriver::TYPE_KEY]++;
59
                    break;
60
                case RedisProxy::TYPE_HASH:
61
                    $tables[RedisDriver::TYPE_HASH]++;
62
                    break;
63
                case RedisProxy::TYPE_SET:
64
                    $tables[RedisDriver::TYPE_SET]++;
65
                    break;
66
                default:
67
                    break;
68
            }
69
        }
70
        return $tables;
71
    }
72
73
    public function tables(array $sorting = [])
74
    {
75
        $tables = [
76
            RedisDriver::TYPE_KEY => [
77
                'list_of_all_keys' => [
78
                    'key' => 'Show all keys',
79
                    'number_of_keys' => 0,
80
                ]
81
            ],
82
            RedisDriver::TYPE_HASH => [],
83
            RedisDriver::TYPE_SET => [],
84
        ];
85
        foreach ($this->connection->keys('*') as $key) {
86
            $type = $this->connection->type($key);
87
            if ($type === RedisProxy::TYPE_STRING) {
88
                $tables[RedisDriver::TYPE_KEY]['list_of_all_keys']['number_of_keys']++;
89
            } elseif ($type === RedisProxy::TYPE_HASH) {
90
                $result = $this->connection->hlen($key);
91
                $tables[RedisDriver::TYPE_HASH][$key] = [
92
                    'key' => $key,
93
                    'number_of_fields' => $result,
94
                ];
95
            } elseif ($type === RedisProxy::TYPE_SET) {
96
                $result = $this->connection->scard($key);
97
                $tables[RedisDriver::TYPE_SET][$key] = [
98
                    'key' => $key,
99
                    'number_of_members' => $result,
100
                ];
101
            }
102
            // TODO list and sorted set
103
        }
104
        return [
105
            RedisDriver::TYPE_KEY => Multisort::sort($tables[RedisDriver::TYPE_KEY], $sorting),
106
            RedisDriver::TYPE_HASH => Multisort::sort($tables[RedisDriver::TYPE_HASH], $sorting),
107
            RedisDriver::TYPE_SET => Multisort::sort($tables[RedisDriver::TYPE_SET], $sorting),
108
        ];
109
    }
110
111
    public function itemsCount($type, $table, array $filter = [])
112
    {
113
        if ($this->itemsCountCache !== false) {
114
            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...
115
        }
116
        $itemsCount = 0;
117
        if ($type == RedisDriver::TYPE_HASH) {
118
            $manager = new RedisHashDataManager($this->connection);
119
            $itemsCount = $manager->itemsCount($table, $filter);
120
        } elseif ($type == RedisDriver::TYPE_KEY) {
121
            $manager = new RedisKeyDataManager($this->connection);
122
            $itemsCount = $manager->itemsCount($filter);
123
        } elseif ($type == RedisDriver::TYPE_SET) {
124
            $manager = new RedisSetDataManager($this->connection);
125
            $itemsCount = $manager->itemsCount($table, $filter);
126
        }
127
        $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...
128
        return $itemsCount;
129
    }
130
131
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
132
    {
133
        $items = [];
134
        if ($type == RedisDriver::TYPE_HASH) {
135
            $manager = new RedisHashDataManager($this->connection);
136
            $items = $manager->items($table, $page, $onPage, $filter);
137
        } elseif ($type == RedisDriver::TYPE_KEY) {
138
            $manager = new RedisKeyDataManager($this->connection);
139
            $items = $manager->items($page, $onPage, $filter);
140
        } elseif ($type == RedisDriver::TYPE_SET) {
141
            $manager = new RedisSetDataManager($this->connection);
142
            $items = $manager->items($table, $page, $onPage, $filter);
143
        }
144
145
        if ($this->itemsCount($type, $table, $filter) <= $onPage) {
146
            $items = Multisort::sort($items, $sorting);
147
        } 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...
148
            $this->addMessage('Sorting has not been applied because the number of items is greater then the limit. Increase the limit or modify the filter.');
149
        }
150
151
        return $items;
152
    }
153
154
    public function deleteItem($type, $table, $item)
155
    {
156
        if ($type == RedisDriver::TYPE_HASH) {
157
            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...
158
        }
159
        if ($type == RedisDriver::TYPE_KEY) {
160
            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...
161
        }
162
        if ($type == RedisDriver::TYPE_SET) {
163
            return $this->connection->srem($table, $item);
164
        }
165
        return parent::deleteItem($type, $table, $item);
166
    }
167
168
    public function deleteTable($type, $table)
169
    {
170
        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...
171
    }
172
173
    public function selectDatabase($database)
174
    {
175
        $this->connection->select($database);
176
    }
177
178
    public function execute($commands)
179
    {
180
        $listOfCommands = array_filter(array_map('trim', explode("\n", $commands)), function ($command) {
181
            return $command;
182
        });
183
184
        $results = [];
185
        foreach ($listOfCommands as $command) {
186
            $commandParts = explode(' ', $command);
187
            $function = array_shift($commandParts);
188
            $function = strtolower($function);
189
            $results[$command]['headers'] = $this->headers($function);
190
            $rows = call_user_func_array([$this->connection, $function], $commandParts);
191
            $items = $this->getItems($function, $rows);
192
            $results[$command]['items'] = $items;
193
            $results[$command]['count'] = count($items);
194
        }
195
        return $results;
196
    }
197
198
    private function headers($function)
199
    {
200
        if ($function === 'get' || $function === 'hget') {
201
            return ['value'];
202
        }
203
        if ($function === 'keys') {
204
            return ['key'];
205
        }
206
        if ($function === 'hgetall') {
207
            return ['key', 'value'];
208
        }
209
        if ($function === 'hlen') {
210
            return ['items_count'];
211
        }
212
        return [];
213
    }
214
215
    private function getItems($function, $rows)
216
    {
217
        $items = [];
218
        if ($function === 'keys') {
219
            foreach ($rows as $key) {
220
                $items[] = [$key];
221
            }
222
        } elseif ($function === 'hgetall') {
223
            foreach ($rows as $key => $value) {
224
                $items[] = [$key, $value];
225
            }
226
        } else {
227
            return [[$rows]];
228
        }
229
        return $items;
230
    }
231
}
232