MySqlDataManager::createWhere()   B
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 43
ccs 0
cts 17
cp 0
rs 7.9875
c 0
b 0
f 0
cc 8
nc 7
nop 1
crap 72
1
<?php
2
3
namespace UniMan\Drivers\MySql;
4
5
use UniMan\Core\DataManager\AbstractDataManager;
6
use UniMan\Core\Exception\OperatorNotSupportedException;
7
use UniMan\Core\Utils\Filter;
8
use UniMan\Core\Utils\Multisort;
9
use InvalidArgumentException;
10
use Nette\Utils\Strings;
11
use PDO;
12
13
class MySqlDataManager extends AbstractDataManager
14
{
15
    private $columns = null;
16
17
    private $connection;
18
19
    private $database;
20
21
    /**
22
     * cache
23
     * @var array|null
24
     */
25
    private $databases = null;
26
27 6
    public function __construct(PDO $connection)
28
    {
29 6
        $this->connection = $connection;
30 6
    }
31
32
    public function databases(array $sorting = [])
33
    {
34
        if ($this->databases !== null) {
35
            return $this->databases;
36
        }
37
38
        $query = 'SELECT information_schema.SCHEMATA.*, count(information_schema.TABLES.TABLE_NAME) AS tables_count, SUM(information_schema.TABLES.DATA_LENGTH) AS size
39
FROM information_schema.SCHEMATA
40
LEFT JOIN information_schema.TABLES ON information_schema.SCHEMATA.SCHEMA_NAME = information_schema.TABLES.TABLE_SCHEMA
41
GROUP BY information_schema.SCHEMATA.SCHEMA_NAME
42
ORDER BY information_schema.SCHEMATA.SCHEMA_NAME';
43
44
        $databases = [];
45
        foreach ($this->connection->query($query)->fetchAll(PDO::FETCH_ASSOC) as $database) {
46
            $databases[$database['SCHEMA_NAME']] = [
47
                'database' => $database['SCHEMA_NAME'],
48
                'charset' => $database['DEFAULT_CHARACTER_SET_NAME'],
49
                'collation' => $database['DEFAULT_COLLATION_NAME'],
50
                'tables_count' => $database['tables_count'],
51
                'size' => $database['size'] ?: 0,
52
            ];
53
        }
54
        $this->databases = $databases;
55
        return Multisort::sort($databases, $sorting);
56
    }
57
58
    protected function getDatabaseNameColumn()
59
    {
60
        return 'database';
61
    }
62
63
    public function tables(array $sorting = [])
64
    {
65
        $tables = [
66
            MySqlDriver::TYPE_TABLE => [],
67
            MySqlDriver::TYPE_VIEW => [],
68
        ];
69
        $type = 'BASE TABLE';
70
        if ($this->database === 'information_schema') {
71
            $type = 'SYSTEM VIEW';
72
        }
73
74
        foreach ($this->connection->query("SELECT * FROM information_schema.TABLES WHERE TABLE_TYPE = '$type' AND TABLE_SCHEMA = '{$this->database}' ORDER BY TABLE_NAME")->fetchAll(PDO::FETCH_ASSOC) as $table) {
75
            $tables[MySqlDriver::TYPE_TABLE][$table['TABLE_NAME']] = [
76
                'table' => $table['TABLE_NAME'],
77
                'engine' => $table['ENGINE'],
78
                'collation' => $table['TABLE_COLLATION'],
79
                'data_length' => $table['DATA_LENGTH'],
80
                'index_length' => $table['INDEX_LENGTH'],
81
                'data_free' => $table['DATA_FREE'],
82
                'autoincrement' => $table['AUTO_INCREMENT'],
83
                'rows' => $table['TABLE_ROWS'],
84
            ];
85
        }
86
87
        foreach ($this->connection->query("SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '{$this->database}' ORDER BY TABLE_NAME")->fetchAll(PDO::FETCH_ASSOC) as $view) {
88
            $tables[MySqlDriver::TYPE_VIEW][$view['TABLE_NAME']] = [
89
                'view' => $view['TABLE_NAME'],
90
                'check_option' => $view['CHECK_OPTION'],
91
                'is_updatable' => $view['IS_UPDATABLE'],
92
                'definer' => $view['DEFINER'],
93
                'security_type' => $view['SECURITY_TYPE'],
94
                'character_set' => $view['CHARACTER_SET_CLIENT'],
95
                'collation' => $view['COLLATION_CONNECTION'],
96
            ];
97
        }
98
        return [
99
            MySqlDriver::TYPE_TABLE => Multisort::sort($tables[MySqlDriver::TYPE_TABLE], $sorting),
100
            MySqlDriver::TYPE_VIEW => Multisort::sort($tables[MySqlDriver::TYPE_VIEW], $sorting),
101
        ];
102
    }
103
104
    public function itemsCount($type, $table, array $filter = [])
105
    {
106
        $query = sprintf('SELECT count(*) FROM `%s`', $table) . $this->createWhere($filter);
107
        return $this->connection->query($query)->fetch(PDO::FETCH_COLUMN);
108
    }
109
110
    public function items($type, $table, $page, $onPage, array $filter = [], array $sorting = [])
111
    {
112
        $primaryColumns = $this->getPrimaryColumns($type, $table);
113
        $query = sprintf('SELECT * FROM `%s`', $table);
114
        $query .= $this->createWhere($filter);
115
        $query .= $this->createOrderBy($sorting);
116
        $query .= ' LIMIT ' . (($page - 1) * $onPage) . ', ' . $onPage;
117
        $items = [];
118
        foreach ($this->connection->query($query)->fetchAll(PDO::FETCH_ASSOC) as $item) {
119
            $pk = [];
120
            foreach ($primaryColumns as $primaryColumn) {
121
                $pk[] = $item[$primaryColumn];
122
            }
123
            $items[md5(implode('|', $pk))] = $item;
124
        }
125
        return $items;
126
    }
127
128
    private function createWhere(array $filter)
129
    {
130
        if (empty($filter)) {
131
            return '';
132
        }
133
134
        $operatorsMap = [
135
            Filter::OPERATOR_EQUAL => '= "%s"',
136
            Filter::OPERATOR_GREATER_THAN => '> "%s"',
137
            Filter::OPERATOR_GREATER_THAN_OR_EQUAL => '>= "%s"',
138
            Filter::OPERATOR_LESS_THAN => '< "%s"',
139
            Filter::OPERATOR_LESS_THAN_OR_EQUAL => '<= "%s"',
140
            Filter::OPERATOR_NOT_EQUAL => '!= "%s"',
141
            Filter::OPERATOR_CONTAINS => 'LIKE "%%%s%%"',
142
            Filter::OPERATOR_NOT_CONTAINS => 'NOT LIKE "%%%s%%"',
143
            Filter::OPERATOR_STARTS_WITH => 'LIKE "%s%%"',
144
            Filter::OPERATOR_ENDS_WITH => 'LIKE "%%%s"',
145
            Filter::OPERATOR_IS_NULL => 'IS NULL',
146
            Filter::OPERATOR_IS_NOT_NULL => 'IS NOT NULL',
147
            Filter::OPERATOR_IS_IN => 'IN (%s)',
148
            Filter::OPERATOR_IS_NOT_IN => 'NOT IN (%s)',
149
        ];
150
151
        $where = ' WHERE ';
152
        $whereParts = [];
153
        foreach ($filter as $filterPart) {
154
            foreach ($filterPart as $key => $filterSettings) {
155
                foreach ($filterSettings as $operator => $value) {
156
                    if (!isset($operatorsMap[$operator])) {
157
                        throw new OperatorNotSupportedException('Operator "' . $operator . '" is not supported.');
158
                    }
159
                    if ($operator === Filter::OPERATOR_IS_IN || $operator === Filter::OPERATOR_IS_NOT_IN) {
160
                        $value = implode(', ', array_map(function ($item) {
161
                            return '"' . $item . '"';
162
                        }, explode(',', $value)));
163
                    }
164
                    $whereParts[] = "`$key` " . sprintf($operatorsMap[$operator], $value);
165
                }
166
            }
167
        }
168
        $where .= implode(' AND ', $whereParts);
169
        return $where;
170
    }
171
172
    private function createOrderBy(array $sorting)
173
    {
174
        if (empty($sorting)) {
175
            return '';
176
        }
177
        $orderBy = ' ORDER BY ';
178
        $order = [];
179
        foreach ($sorting as $sort) {
180
            foreach ($sort as $key => $direction) {
181
                $direction = strtolower($direction) === 'asc' ? 'ASC' : 'DESC';
182
                $order[] = "`$key` $direction";
183
            }
184
        }
185
        $orderBy .= implode(', ', $order);
186
        return $orderBy;
187
    }
188
189
    public function loadItem($type, $table, $item)
190
    {
191
        $primaryColumns = $this->getPrimaryColumns($type, $table);
192
        $query = sprintf('SELECT * FROM `%s` WHERE md5(concat(%s)) = "%s"', $table, implode(', "|", ', $primaryColumns), $item);
193
        return $this->connection->query($query)->fetch(PDO::FETCH_ASSOC);
194
    }
195
196
    public function deleteItem($type, $table, $item)
197
    {
198
        $primaryColumns = $this->getPrimaryColumns($type, $table);
199
        $query = sprintf('DELETE FROM `%s` WHERE md5(concat(%s)) = "%s"', $table, implode(', "|", ', $primaryColumns), $item);
200
        return $this->connection->query($query);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->query($query); (PDOStatement) 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
203
    public function deleteTable($type, $table)
204
    {
205
        if ($type === MySqlDriver::TYPE_TABLE) {
206
            $query = sprintf('DROP TABLE `%s`', $table);
207
        } elseif ($type === MySqlDriver::TYPE_VIEW) {
208
            $query = sprintf('DROP VIEW `%s`', $table);
209
        } else {
210
            throw new InvalidArgumentException('Type "' . $type . '" is not supported');
211
        }
212
        return $this->connection->query($query);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->query($query); (PDOStatement) 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...
213
    }
214
215
    public function deleteDatabase($database)
216
    {
217
        $query = sprintf('DROP DATABASE `%s`', $database);
218
        return $this->connection->query($query);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->connection->query($query); (PDOStatement) is incompatible with the return type declared by the interface UniMan\Core\DataManager\...terface::deleteDatabase 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...
219
    }
220
221
    public function selectDatabase($database)
222
    {
223
        $this->database = $database;
224
        $query = sprintf('USE `%s`', $database);
225
        $this->connection->query($query);
226
    }
227
228
    public function getPrimaryColumns($type, $table)
229
    {
230
        $primaryColumns = [];
231
        $columns = [];
232
        foreach ($this->getColumns($type, $table) as $column) {
233
            $columns[] = $column['Field'];
234
            if ($column['Key'] === 'PRI') {
235
                $primaryColumns[] = $column['Field'];
236
            }
237
        }
238
        if (empty($primaryColumns)) {
239
            $primaryColumns = $columns;
240
        }
241
        return $primaryColumns;
242
    }
243
244
    public function getColumns($type, $table)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
245
    {
246
        if ($this->columns === null) {
247
            $columns = $this->connection->query(sprintf('SHOW FULL COLUMNS FROM `%s`', $table))->fetchAll(PDO::FETCH_ASSOC);
248
            $keys = [];
249
            foreach ($this->connection->query(sprintf('SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = "%s" AND TABLE_NAME = "%s"', $this->database, $table))->fetchAll(PDO::FETCH_ASSOC) as $key) {
250
                $keys[$key['COLUMN_NAME']] = $key;
251
            }
252
            $this->columns = [];
253
            foreach ($columns as $column) {
254
                $column['key_info'] = isset($keys[$column['Field']]) ? $keys[$column['Field']] : [];
255
                $this->columns[$column['Field']] = $column;
256
            }
257
        }
258
        return $this->columns;
259
    }
260
261
    public function execute($commands)
262
    {
263
        $queries = array_filter(array_map('trim', explode(';', $commands)), function ($query) {
264
            return $query;
265
        });
266
        $results = [];
267
        foreach ($queries as $query) {
268
            $results[$query]['headers'] = [];
269
            $statement = $this->connection->query($query);
270
            if (Strings::startsWith(strtolower($query), 'select ') || Strings::startsWith(strtolower($query), 'show ')) {
271
                $res = $statement->fetchAll(PDO::FETCH_ASSOC);
272
                $results[$query]['headers'] = array_keys(current($res));
273
                $results[$query]['items'] = $res;
274
                continue;
275
            }
276
            $results[$query] = (bool) $statement;
277
        }
278
        return $results;
279
    }
280
}
281