Passed
Push — master ( 2d02cb...58fbc2 )
by Petr
03:02
created

MySql::selectLimited()   F

Complexity

Conditions 14
Paths 2560

Size

Total Lines 59
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 14

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 43
c 2
b 0
f 0
dl 0
loc 59
ccs 44
cts 44
cp 1
rs 2.1
cc 14
nc 2560
nop 1
crap 14

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace kalanis\nested_tree\Sources\PDO;
4
5
use kalanis\nested_tree\Support;
6
use PDO as base_pdo;
7
8
/**
9
 * The default SQL implementation
10
 */
11
class MySql extends PDO
12
{
13 10
    public function selectLastPosition(?Support\Node $parentNode, ?Support\Conditions $where = null) : ?int
14
    {
15 10
        $sql = 'SELECT `' . $this->settings->idColumnName . '`, `' . $this->settings->parentIdColumnName . '`, `' . $this->settings->positionColumnName . '`'
16 10
            . ' FROM `' . $this->settings->tableName . '`'
17 10
            . ' WHERE TRUE';
18 10
        if (is_null($parentNode?->id)) {
0 ignored issues
show
introduced by
The condition is_null($parentNode->id) is always false.
Loading history...
19 3
            $sql .= ' AND `' . $this->settings->parentIdColumnName . '` IS NULL';
20
        } else {
21 9
            $sql .= ' AND `' . $this->settings->parentIdColumnName . '` = :filter_parent_id';
22
        }
23 10
        $sql .= $this->addCustomQuery($where, '');
24 10
        $sql .= $this->addSoftDelete();
25 10
        $sql .= ' ORDER BY `' . $this->settings->positionColumnName . '` DESC';
26
27 10
        $Sth = $this->pdo->prepare($sql);
28 10
        if (!is_null($parentNode?->id)) {
0 ignored issues
show
introduced by
The condition is_null($parentNode->id) is always false.
Loading history...
29 9
            $this->bindParentId($parentNode->id, $Sth);
30
        }
31 10
        $this->bindCustomQuery($where, $Sth);
32 10
        $this->bindSoftDelete($Sth);
33
34 10
        $Sth->execute();
35
        /** @var array<string|int, mixed>|false $row */
36 10
        $row = $Sth->fetch();
37 10
        $Sth->closeCursor();
38
39 10
        if (!empty($row)) {
40 10
            return is_null($row[$this->settings->positionColumnName]) ? null : max(1, intval($row[$this->settings->positionColumnName]));
41
        }
42
43 1
        return null;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 122
    public function selectSimple(Support\Options $options) : array
50
    {
51 122
        $sql = 'SELECT node.`' . $this->settings->idColumnName . '`'
52 122
            . ', node.`' . $this->settings->parentIdColumnName . '`'
53 122
            . ', node.`' . $this->settings->leftColumnName . '`'
54 122
            . ', node.`' . $this->settings->rightColumnName . '`'
55 122
            . ', node.`' . $this->settings->levelColumnName . '`'
56 122
            . ', node.`' . $this->settings->positionColumnName . '`'
57 122
        ;
58 122
        $sql .= $this->addAdditionalColumns($options, 'node.');
59 122
        $sql .= ' FROM `' . $this->settings->tableName . '` node';
60 122
        $sql .= ' WHERE 1';
61 122
        $sql .= $this->addCurrentId($options, 'node.');
62 122
        $sql .= $this->addCustomQuery($options->where, 'node.');
63 122
        $sql .= $this->addSoftDelete('node.');
64 122
        $sql .= ' ORDER BY node.`' . $this->settings->positionColumnName . '` ASC';
65
66 122
        $Sth = $this->pdo->prepare($sql);
67 122
        $this->bindCurrentId($options->currentId, $Sth);
68 122
        $this->bindCustomQuery($options->where, $Sth);
69 122
        $this->bindSoftDelete($Sth);
70
71 122
        $Sth->execute();
72 122
        $result = $Sth->fetchAll();
73
74 122
        return $result ? $this->fromDbRows($result) : [];
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 33
    public function selectParent(Support\Node $node, Support\Options $options) : ?Support\Node
81
    {
82 33
        if (is_null($node->parentId)) {
83 1
            return null;
84
        }
85
86 32
        $sql = 'SELECT node.`' . $this->settings->idColumnName . '`'
87 32
            . ', node.`' . $this->settings->parentIdColumnName . '`'
88 32
            . ', node.`' . $this->settings->leftColumnName . '`'
89 32
            . ', node.`' . $this->settings->rightColumnName . '`'
90 32
            . ', node.`' . $this->settings->levelColumnName . '`'
91 32
            . ', node.`' . $this->settings->positionColumnName . '`'
92 32
        ;
93 32
        $sql .= $this->addAdditionalColumns($options, 'node.');
94 32
        $sql .= ' FROM `' . $this->settings->tableName . '` node';
95 32
        $sql .= ' WHERE node.`' . $this->settings->idColumnName . '` = :filter_taxonomy_id';
96 32
        $sql .= $this->addCustomQuery($options->where, 'node.');
97 32
        $sql .= $this->addSoftDelete('node.');
98
99 32
        $Sth = $this->pdo->prepare($sql);
100 32
        $this->bindCurrentId($node->parentId, $Sth);
101 32
        $this->bindCustomQuery($options->where, $Sth);
102 32
        $this->bindSoftDelete($Sth);
103
104 32
        $Sth->execute();
105
        /** @var array<string|int, mixed>|false $row */
106 32
        $row = $Sth->fetch();
107 32
        $node = $row ? $this->fillDataFromRow($row) : null;
108 32
        $Sth->closeCursor();
109
110 32
        if (empty($node)) {
111 4
            return $this->settings->rootIsNull ? null : new Support\Node();
112
        }
113
114 28
        return $node;
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 82
    public function selectCount(Support\Options $options) : int
121
    {
122 82
        $joinChild = $this->canJoinChild($options);
123 82
        $sql = 'SELECT ';
124 82
        $sql .= ' ANY_VALUE(`parent`.`' . $this->settings->idColumnName . '`)';
125 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->parentIdColumnName . '`)';
126 82
        if ($this->settings->softDelete) {
127 20
            $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->softDelete->columnName . '`)';
128
        }
129 82
        if ($joinChild) {
130 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->idColumnName . '`) AS `' . $this->settings->idColumnName . '`';
131 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->parentIdColumnName . '`) AS `' . $this->settings->parentIdColumnName . '`';
132 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->leftColumnName . '`) AS `' . $this->settings->leftColumnName . '`';
133
        }
134 82
        $sql .= $this->addAdditionalColumns($options);
135 82
        $sql .= ' FROM `' . $this->settings->tableName . '` AS `parent`';
136
137 82
        if ($joinChild) {
138
            // if there is filter or search, there must be inner join to select all of filtered children.
139 69
            $sql .= ' INNER JOIN `' . $this->settings->tableName . '` AS `child`';
140 69
            $sql .= ' ON `child`.`' . $this->settings->leftColumnName . '` BETWEEN `parent`.`' . $this->settings->leftColumnName . '` AND `parent`.`' . $this->settings->rightColumnName . '`';
141
        }
142
143 82
        $sql .= ' WHERE TRUE';
144 82
        $sql .= $this->addFilterBy($options);
145 82
        $sql .= $this->addCurrentId($options, '`parent`.');
146 82
        $sql .= $this->addParentId($options, '`parent`.');
147 82
        $sql .= $this->addSearch($options, '`parent`.');
148 82
        $sql .= $this->addCustomQuery($options->where);
149 82
        $sql .= $this->addSoftDelete('`parent`.');
150 82
        $sql .= $this->addSorting($options);
151
152
        // prepare and get 'total' count.
153 82
        $Sth = $this->pdo->prepare($sql);
154 82
        $this->bindCurrentId($options->currentId, $Sth);
155 82
        $this->bindParentId($options->parentId, $Sth, true);
156 82
        $this->bindSearch($options, $Sth);
157 82
        $this->bindCustomQuery($options->where, $Sth);
158 82
        $this->bindSoftDelete($Sth);
159
160 82
        $Sth->execute();
161 82
        $result = $Sth->fetchAll();
162
163
        // "a bit" hardcore - get all lines and then count them
164
        // that's due problems with COUNT() aggregator in MySQL
165 82
        return $result ? count($result) : 0;
166
    }
167
168 82
    public function selectLimited(Support\Options $options) : array
169
    {
170 82
        $joinChild = $this->canJoinChild($options);
171 82
        $sql = 'SELECT';
172 82
        $sql .= ' ANY_VALUE(`parent`.`' . $this->settings->idColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->idColumnName . '`');
173 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->parentIdColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->parentIdColumnName . '`');
174 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->leftColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->leftColumnName . '`');
175 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->rightColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->rightColumnName . '`');
176 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->levelColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->levelColumnName . '`');
177 82
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->positionColumnName . '`)' . ($joinChild ? '' : ' AS `' . $this->settings->positionColumnName . '`');
178 82
        if ($joinChild) {
179 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->idColumnName . '`) AS `' . $this->settings->idColumnName . '`';
180 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->parentIdColumnName . '`) AS `' . $this->settings->parentIdColumnName . '`';
181 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->leftColumnName . '`) AS `' . $this->settings->leftColumnName . '`';
182 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->rightColumnName . '`) AS `' . $this->settings->rightColumnName . '`';
183 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->levelColumnName . '`) AS `' . $this->settings->levelColumnName . '`';
184 69
            $sql .= ', ANY_VALUE(`child`.`' . $this->settings->positionColumnName . '`) AS `' . $this->settings->positionColumnName . '`';
185
        }
186 82
        $sql .= $this->addAdditionalColumns($options);
187 82
        $sql .= ' FROM `' . $this->settings->tableName . '` AS `parent`';
188
189 82
        if ($joinChild) {
190
            // if there is filter or search, there must be inner join to select all of filtered children.
191 69
            $sql .= ' INNER JOIN `' . $this->settings->tableName . '` AS `child`';
192 69
            $sql .= ' ON `child`.`' . $this->settings->leftColumnName . '` BETWEEN `parent`.`' . $this->settings->leftColumnName . '` AND `parent`.`' . $this->settings->rightColumnName . '`';
193
        }
194
195 82
        $sql .= ' WHERE TRUE';
196 82
        $sql .= $this->addFilterBy($options);
197 82
        $sql .= $this->addCurrentId($options, '`parent`.');
198 82
        $sql .= $this->addParentId($options, '`parent`.');
199 82
        $sql .= $this->addSearch($options, '`parent`.');
200 82
        $sql .= $this->addCustomQuery($options->where);
201 82
        $sql .= $this->addSoftDelete('`parent`.');
202 82
        $sql .= $this->addSorting($options);
203
204
        // re-create query and prepare. second step is for set limit and fetch all items.
205 82
        if (!$options->unlimited) {
206 43
            if (empty($options->offset)) {
207 43
                $options->offset = 0;
208
            }
209 43
            if (empty($options->limit) || (10000 < $options->limit)) {
210 42
                $options->limit = 20;
211
            }
212
213 43
            $sql .= ' LIMIT ' . $options->offset . ', ' . $options->limit;
214
        }
215
216 82
        $Sth = $this->pdo->prepare($sql);
217 82
        $this->bindCurrentId($options->currentId, $Sth);
218 82
        $this->bindParentId($options->parentId, $Sth, true);
219 82
        $this->bindSearch($options, $Sth);
220 82
        $this->bindCustomQuery($options->where, $Sth);
221 82
        $this->bindSoftDelete($Sth);
222
223 82
        $Sth->execute();
224 82
        $result = $Sth->fetchAll();
225
226 82
        return $result ? $this->fromDbRows($result, $joinChild) : [];
227
    }
228
229
    /**
230
     * {@inheritdoc}
231
     */
232 18
    public function selectWithParents(Support\Options $options) : array
233
    {
234 18
        $sql = 'SELECT';
235 18
        $sql .= ' ANY_VALUE(`parent`.`' . $this->settings->idColumnName . '`) AS `' . $this->settings->idColumnName . '`';
236 18
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->parentIdColumnName . '`) AS `' . $this->settings->parentIdColumnName . '`';
237 18
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->leftColumnName . '`) AS `' . $this->settings->leftColumnName . '`';
238 18
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->rightColumnName . '`) AS `' . $this->settings->rightColumnName . '`';
239 18
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->levelColumnName . '`) AS `' . $this->settings->levelColumnName . '`';
240 18
        $sql .= ', ANY_VALUE(`parent`.`' . $this->settings->positionColumnName . '`) AS `' . $this->settings->positionColumnName . '`';
241 18
        $sql .= $this->addAdditionalColumns($options);
242 18
        $sql .= ' FROM `' . $this->settings->tableName . '` AS `node`,';
243 18
        $sql .= ' `' . $this->settings->tableName . '` AS `parent`';
244 18
        $sql .= ' WHERE';
245 18
        $sql .= ' (`node`.`' . $this->settings->leftColumnName . '` BETWEEN `parent`.`' . $this->settings->leftColumnName . '` AND `parent`.`' . $this->settings->rightColumnName . '`)';
246 18
        $sql .= $this->addCurrentId($options, '`node`.');
247 18
        $sql .= $this->addSearch($options, '`node`.');
248 18
        $sql .= $this->addCustomQuery($options->where);
249 18
        $sql .= $this->addSoftDelete('`node`.');
250 18
        $sql .= ' GROUP BY `parent`.`' . $this->settings->idColumnName . '`';
251 18
        $sql .= ' ORDER BY `parent`.`' . $this->settings->leftColumnName . '`';
252
253 18
        $Sth = $this->pdo->prepare($sql);
254 18
        $this->bindCurrentId($options->currentId, $Sth);
255 18
        $this->bindSearch($options, $Sth);
256 18
        $this->bindCustomQuery($options->where, $Sth);
257 18
        $this->bindSoftDelete($Sth);
258
259 18
        $Sth->execute();
260 18
        $result = $Sth->fetchAll();
261 18
        $Sth->closeCursor();
262
263 18
        if (empty($result)) {
264 2
            return [];
265
        }
266 18
        if ($options->skipCurrent) {
267 2
            unset($result[count($result)-1]);
268
        }
269
270 18
        return $this->fromDbRows($result);
271
    }
272
273 2
    public function add(Support\Node $node, ?Support\Conditions $where = null) : Support\Node
274
    {
275
        // Insert itself
276 2
        $sql = 'INSERT INTO `' . $this->settings->tableName . '`';
277 2
        $lookup = [];
278 2
        $pairs = [];
279 2
        foreach ((array) $node as $column => $value) {
280
            if (
281 2
                !is_numeric($column)
282 2
                && !$this->isColumnNameFromBasic($column)
283
            ) {
284 2
                $translateColumn = $this->translateColumn($this->settings, $column);
285 2
                if (!is_null($translateColumn)) {
286 2
                    $lookup['`' . $translateColumn . '`'] = ':' . $translateColumn;
287 2
                    $pairs[':' . $translateColumn] = $value;
288
                }
289
            }
290
        }
291 2
        if (empty($lookup)) {
292
            // @codeCoverageIgnoreStart
293
            // when this happens it is problem with inserted data, not with library
294
            throw new \RuntimeException('No lookup data!');
295
        }
296
        // @codeCoverageIgnoreEnd
297
298 2
        $sql .= '(' . implode(',', array_keys($lookup)) . ')';
299 2
        $sql .= ' VALUES (' . implode(',', array_keys($pairs)) . ')';
300
301 2
        $Sth = $this->pdo->prepare($sql);
302
303 2
        foreach ($pairs as $column => $value) {
304 2
            $Sth->bindValue($column, $value);
305
        }
306
307 2
        $execute = $Sth->execute();
308 2
        if (!$execute) {
309
            // @codeCoverageIgnoreStart
310
            // when this happens it is problem with DB, not with library
311
            throw new \RuntimeException('Cannot save!');
312
        }
313
        // @codeCoverageIgnoreEnd
314 2
        $Sth->closeCursor();
315
316
        // Now get it back
317 2
        $sql = 'SELECT * FROM `' . $this->settings->tableName . '` WHERE 1';
318 2
        foreach ($lookup as $column => $bind) {
319 2
            if (is_null($pairs[$bind])) {
320 1
                $sql .= ' AND ' . $column . ' IS NULL';
321
            } else {
322 2
                $sql .= ' AND ' . $column . ' = ' . $bind;
323
            }
324
        }
325 2
        $Lth = $this->pdo->prepare($sql);
326 2
        foreach ($pairs as $column => $value) {
327 2
            if (!is_null($value)) {
328 2
                $Lth->bindValue($column, $value);
329
            }
330
        }
331
332 2
        $Lth->execute();
333
        /** @var array<string|int, mixed>|false $row */
334 2
        $row = $Lth->fetch();
335 2
        $node = $row ? $this->fillDataFromRow($row) : null;
336 2
        $Lth->closeCursor();
337
338 2
        if (is_null($node)) {
339
            // @codeCoverageIgnoreStart
340
            // when this happens it is problem with DB, not with library
341
            throw new \RuntimeException('Node not found in database');
342
        }
343
        // @codeCoverageIgnoreEnd
344
345 2
        return $node;
346
    }
347
348 4
    public function updateData(Support\Node $node, ?Support\Conditions $where = null) : bool
349
    {
350 4
        $sql = 'UPDATE `' . $this->settings->tableName . '`';
351 4
        $sql .= ' SET ';
352 4
        $pairs = [];
353 4
        $lookup = [];
354 4
        foreach ((array) $node as $column => $value) {
355
            if (
356 4
                !is_numeric($column)
357 4
                && !$this->isColumnNameFromBasic($column)
358 4
                && !$this->isColumnNameFromTree($column)
359
            ) {
360 4
                $translateColumn = $this->translateColumn($this->settings, $column);
361 4
                if (!is_null($translateColumn)) {
362 3
                    $lookup[] = '`' . $translateColumn . '` = :' . $translateColumn;
363 3
                    $pairs[':' . $translateColumn] = $value;
364
                }
365
            }
366
        }
367 4
        if (empty($lookup)) {
368 1
            return false;
369
        }
370 3
        $sql .= implode(',', $lookup);
371 3
        $sql .= ' WHERE `' . $this->settings->idColumnName . '` = :id';
372
373 3
        $sql .= $this->addCustomQuery($where, '');
374 3
        $sql .= $this->addSoftDelete();
375 3
        $Sth = $this->pdo->prepare($sql);
376
377 3
        $Sth->bindValue(':id', $node->id, base_pdo::PARAM_INT);
378 3
        foreach ($pairs as $column => $value) {
379 3
            $Sth->bindValue($column, $value);
380
        }
381 3
        $this->bindCustomQuery($where, $Sth);
382 3
        $this->bindSoftDelete($Sth);
383
384 3
        $execute = $Sth->execute();
385 3
        $Sth->closeCursor();
386
387 3
        return $execute;
388
    }
389
390
    /**
391
     * {@inheritdoc}
392
     */
393 30
    public function updateNodeParent(Support\Node $node, ?Support\Node $parent, int $position, ?Support\Conditions $where = null) : bool
394
    {
395 30
        $parent = $parent ?: ($this->settings->rootIsNull ? null : new Support\Node());
396
397 30
        $sql = 'UPDATE `' . $this->settings->tableName . '`';
398 30
        $sql .= ' SET `' . $this->settings->parentIdColumnName . '` = :filter_parent_id';
399 30
        $sql .= ' , `' . $this->settings->positionColumnName . '` = :position';
400 30
        $sql .= ' WHERE `' . $this->settings->idColumnName . '` = :filter_taxonomy_id';
401 30
        $sql .= $this->addCustomQuery($where, '');
402 30
        $sql .= $this->addSoftDelete('');
403
404 30
        $Sth = $this->pdo->prepare($sql);
405 30
        $this->bindParentId($parent?->id, $Sth);
406 30
        $Sth->bindValue(':position', $position, base_pdo::PARAM_INT);
407 30
        $this->bindCurrentId($node->id, $Sth);
408 30
        $this->bindCustomQuery($where, $Sth);
409 30
        $this->bindSoftDelete($Sth);
410
411 30
        $execute = $Sth->execute();
412 30
        $Sth->closeCursor();
413
414 30
        return $execute;
415
    }
416
417
    /**
418
     * {@inheritdoc}
419
     */
420 7
    public function updateChildrenParent(Support\Node $node, ?Support\Node $parent, ?Support\Conditions $where = null) : bool
421
    {
422 7
        $parent = $parent ?: ($this->settings->rootIsNull ? null : new Support\Node());
423
424 7
        $sql = 'UPDATE `' . $this->settings->tableName . '`';
425 7
        $sql .= ' SET `' . $this->settings->parentIdColumnName . '` = :filter_parent_id';
426 7
        $sql .= ' WHERE `' . $this->settings->parentIdColumnName . '` = :filter_taxonomy_id';
427 7
        $sql .= $this->addCustomQuery($where, '');
428 7
        $sql .= $this->addSoftDelete();
429
430 7
        $Sth = $this->pdo->prepare($sql);
431 7
        $this->bindParentId($parent?->id, $Sth);
432 7
        $this->bindCurrentId($node->id, $Sth);
433 7
        $this->bindCustomQuery($where, $Sth);
434 7
        $this->bindSoftDelete($Sth);
435
436 7
        $execute = $Sth->execute();
437 7
        $Sth->closeCursor();
438
439 7
        return $execute;
440
    }
441
442 118
    public function updateLeftRightPos(Support\Node $row, ?Support\Conditions $where = null) : bool
443
    {
444 118
        $sql = 'UPDATE `' . $this->settings->tableName . '`';
445 118
        $sql .= ' SET';
446 118
        $sql .= ' `' . $this->settings->levelColumnName . '` = :level,';
447 118
        $sql .= ' `' . $this->settings->leftColumnName . '` = :left,';
448 118
        $sql .= ' `' . $this->settings->rightColumnName . '` = :right,';
449 118
        $sql .= ' `' . $this->settings->positionColumnName . '` = :pos';
450 118
        $sql .= ' WHERE `' . $this->settings->idColumnName . '` = :id';
451 118
        $sql .= $this->addCustomQuery($where, '');
452 118
        $sql .= $this->addSoftDelete();
453
454 118
        $Sth = $this->pdo->prepare($sql);
455 118
        $Sth->bindValue(':level', $row->level, base_pdo::PARAM_INT);
456 118
        $Sth->bindValue(':left', $row->left, base_pdo::PARAM_INT);
457 118
        $Sth->bindValue(':right', $row->right, base_pdo::PARAM_INT);
458 118
        $Sth->bindValue(':pos', $row->position, base_pdo::PARAM_INT);
459 118
        $Sth->bindValue(':id', $row->id, base_pdo::PARAM_INT);
460 118
        $this->bindCustomQuery($where, $Sth);
461 118
        $this->bindSoftDelete($Sth);
462
463 118
        $execute = $Sth->execute();
464 118
        $Sth->closeCursor();
465
466 118
        return $execute;
467
    }
468
469
    /**
470
     * {@inheritdoc}
471
     */
472 26
    public function makeHole(?Support\Node $parent, int $position, bool $moveUp, ?Support\Conditions $where = null) : bool
473
    {
474 26
        $parent = $parent ?: ($this->settings->rootIsNull ? null : new Support\Node());
475 26
        $direction = $moveUp ? '-' : '+';
476 26
        $compare = $moveUp ? '<=' : '>=';
477 26
        $sql = 'UPDATE `' . $this->settings->tableName . '`';
478 26
        $sql .= ' SET `' . $this->settings->positionColumnName . '` = `' . $this->settings->positionColumnName . '` ' . $direction . ' 1';
479 26
        if (is_null($parent)) {
480 1
            $sql .= ' WHERE `' . $this->settings->parentIdColumnName . '` IS NULL';
481
        } else {
482 25
            $sql .= ' WHERE `' . $this->settings->parentIdColumnName . '` = :filter_parent_id';
483
        }
484 26
        $sql .= ' AND `' . $this->settings->positionColumnName . '` ' . $compare . ' :position';
485
486 26
        $sql .= $this->addCustomQuery($where, '');
487 26
        $sql .= $this->addSoftDelete();
488 26
        $Sth = $this->pdo->prepare($sql);
489
490 26
        $Sth->bindValue(':position', $position, base_pdo::PARAM_INT);
491 26
        if (!is_null($parent)) {
492 25
            $this->bindParentId($parent->id, $Sth);
493
        }
494 26
        $this->bindCustomQuery($where, $Sth);
495 26
        $this->bindSoftDelete($Sth);
496
497 26
        $execute = $Sth->execute();
498 26
        $Sth->closeCursor();
499
500 26
        return $execute;
501
    }
502
503
    /**
504
     * {@inheritdoc}
505
     */
506 11
    public function deleteSolo(Support\Node $node, ?Support\Conditions $where = null) : bool
507
    {
508 11
        if ($this->settings->softDelete) {
509 3
            $sql = 'UPDATE `' . $this->settings->tableName . '`'
510 3
                . ' SET `' . $this->settings->softDelete->columnName . '` = ' . $this->settings->softDelete->bindAsKey . '_mk'
511 3
                . ' WHERE `' . $this->settings->idColumnName . '` = :filter_taxonomy_id';
512 3
            $sql .= $this->addCustomQuery($where, '');
513 3
            $sql .= $this->addSoftDelete();
514 3
            $Sth = $this->pdo->prepare($sql);
515
516 3
            $Sth->bindValue($this->settings->softDelete->bindAsKey . '_mk', $this->settings->softDelete->isDeleted);
517 3
            $this->bindCurrentId($node->id, $Sth);
518 3
            $this->bindCustomQuery($where, $Sth);
519 3
            $this->bindSoftDelete($Sth);
520
521 3
            $execute = $Sth->execute();
522 3
            $Sth->closeCursor();
523
524 3
            return $execute;
525
        }
526
527
        // delete the selected taxonomy ID
528 8
        $sql = 'DELETE FROM `' . $this->settings->tableName . '` WHERE `' . $this->settings->idColumnName . '` = :filter_taxonomy_id';
529 8
        $sql .= $this->addCustomQuery($where, '');
530 8
        $Sth = $this->pdo->prepare($sql);
531
532 8
        $this->bindCurrentId($node->id, $Sth);
533 8
        $this->bindCustomQuery($where, $Sth);
534
535 8
        $execute = $Sth->execute();
536 8
        $Sth->closeCursor();
537
538 8
        return $execute;
539
    }
540
541 61
    protected function replaceColumns(string $query, string $byWhat = '') : string
542
    {
543 61
        foreach (['`parent`.', '`child`.', '`node`.', 'parent.', 'child.', 'node.'] as $toReplace) {
544 61
            $query = str_replace($toReplace, $byWhat, $query);
545
        }
546
547 61
        return $query;
548
    }
549
550 122
    protected function addAdditionalColumns(Support\Options $options, ?string $replaceName = null) : string
551
    {
552 122
        $sql = '';
553 122
        if (!empty($options->additionalColumns)) {
554 75
            foreach ($options->additionalColumns as $column) {
555 75
                $sql .= ', ' . (!is_null($replaceName) ? $this->replaceColumns($column, $replaceName) : $column);
556
            }
557
        }
558
559 122
        return $sql;
560
    }
561
562 82
    protected function addFilterBy(Support\Options $options) : string
563
    {
564 82
        $sql = '';
565 82
        if (!empty($options->filterIdBy)) {
566
            // Due to IN() and NOT IN() cannot using bindValue directly.
567
            // read more at http://stackoverflow.com/questions/17746667/php-pdo-for-not-in-query-in-mysql
568
            // and http://stackoverflow.com/questions/920353/can-i-bind-an-array-to-an-in-condition
569
            // it is possible to go around that, but it needs a bit more tinkering
570
571
            // loop remove non-number for safety.
572 4
            foreach ($options->filterIdBy as $key => $eachNodeId) {
573 4
                if (!is_numeric($eachNodeId) || intval($eachNodeId) !== intval($eachNodeId)) {
574 2
                    unset($options->filterIdBy[$key]);
575
                }
576
            }
577
578
            // build value for use with `IN()` function. Example: 1,3,4,5.
579 4
            $nodeIdIn = implode(',', $options->filterIdBy);
580 4
            $sql .= ' AND `parent`.`' . $this->settings->idColumnName . '` IN (' . $nodeIdIn . ')';
581
        }
582
583 82
        return $sql;
584
    }
585
586 122
    protected function addCurrentId(Support\Options $options, string $dbPrefix = '') : string
587
    {
588 122
        $sql = '';
589 122
        if (!is_null($options->currentId)) {
590 71
            $sql .= ' AND ' . $dbPrefix . '`' . $this->settings->idColumnName . '` = :filter_taxonomy_id';
591
        }
592
593 122
        return $sql;
594
    }
595
596 82
    protected function addParentId(Support\Options $options, string $dbPrefix = '') : string
597
    {
598 82
        $sql = '';
599 82
        if (!is_null($options->parentId)) {
600 2
            $sql .= ' AND ' . $dbPrefix . '`' . $this->settings->parentIdColumnName . '` = :filter_parent_id';
601
        }
602
603 82
        return $sql;
604
    }
605
606 122
    protected function bindCurrentId(?int $currentId, \PDOStatement $pdo) : void
607
    {
608 122
        if (!is_null($currentId)) {
609 71
            $pdo->bindValue(':filter_taxonomy_id', $currentId, base_pdo::PARAM_INT);
610
        }
611
    }
612
613 89
    protected function bindParentId(?int $parentId, \PDOStatement $pdo, bool $skipNull = false) : void
614
    {
615 89
        if (is_null($parentId) && !$skipNull) {
616 1
            $pdo->bindValue(':filter_parent_id', null, base_pdo::PARAM_NULL);
617 89
        } elseif (!is_null($parentId)) {
618 43
            $pdo->bindValue(':filter_parent_id', $parentId, base_pdo::PARAM_INT);
619
        }
620
    }
621
622 96
    protected function addSearch(Support\Options $options, string $dbPrefix = '') : string
623
    {
624 96
        $sql = '';
625
        if (
626 96
            !empty($options->search->columns)
627 96
            && !empty($options->search->value)
628
        ) {
629 6
            $sql .= ' AND (';
630 6
            $array_keys = array_keys($options->search->columns);
631 6
            $last_array_key = array_pop($array_keys);
632 6
            foreach ($options->search->columns as $key => $column) {
633 6
                $sql .= $dbPrefix . '`' . $column . '` LIKE :search';
634 6
                if ($key !== $last_array_key) {
635 1
                    $sql .= ' OR ';
636
                }
637
            }
638 6
            $sql .= ')';
639
        }
640
641 96
        return $sql;
642
    }
643
644 96
    protected function bindSearch(Support\Options $options, \PDOStatement $pdo) : void
645
    {
646 96
        if (!empty($options->search->value)) {
647 6
            $pdo->bindValue(':search', '%' . $options->search->value . '%');
648
        }
649
    }
650
651 122
    protected function addCustomQuery(?Support\Conditions $where, ?string $replaceName = null, bool $clearName = false) : string
652
    {
653 122
        if (!empty($where->query)) {
654 67
            $query = (
655 67
                !is_null($replaceName)
656 61
                    ? $this->replaceColumns($where->query, $replaceName)
657 41
                    : ($clearName ? $this->replaceColumns($where->query) : $where->query)
658 67
            );
659 67
            if (!empty(trim($query))) {
660 67
                return ' AND ' . $query;
661
            }
662
        }
663
664 87
        return '';
665
    }
666
667 122
    protected function bindCustomQuery(?Support\Conditions $where, \PDOStatement $pdo) : void
668
    {
669 122
        if (!empty($where->bindValues)) {
670 67
            foreach ($where->bindValues as $bindName => $bindValue) {
671 67
                $pdo->bindValue($bindName, $bindValue);
672
            }
673
        }
674
    }
675
676 122
    protected function addSoftDelete(string $dbPrefix = '') : string
677
    {
678 122
        $sql = '';
679 122
        if (!is_null($this->settings->softDelete)) {
680 30
            $sql .= ' AND ' . $dbPrefix . '`' . $this->settings->softDelete->columnName . '` = ' . $this->settings->softDelete->bindAsKey;
681
        }
682
683 122
        return $sql;
684
    }
685
686 122
    protected function bindSoftDelete(\PDOStatement $pdo) : void
687
    {
688 122
        if (!empty($this->settings->softDelete)) {
689 30
            $pdo->bindValue(
690 30
                $this->settings->softDelete->bindAsKey,
691 30
                $this->settings->softDelete->canUse,
692 30
                is_numeric($this->settings->softDelete->canUse) ? base_pdo::PARAM_INT : base_pdo::PARAM_STR
693 30
            );
694
        }
695
    }
696
697 82
    protected function addSorting(Support\Options $options) : string
698
    {
699 82
        $sql = '';
700 82
        if (!$options->noSortOrder) {
701 80
            if ($this->canJoinChild($options)) {
702 67
                $sql .= ' GROUP BY `child`.`' . $this->settings->idColumnName . '`';
703 67
                $order_by = '`child`.`' . $this->settings->leftColumnName . '` ASC';
704 19
            } elseif (!empty($options->filterIdBy)) {
705 1
                $nodeIdIn = implode(',', $options->filterIdBy);
706 1
                $order_by = 'FIELD(`' . $this->settings->idColumnName . '`,' . $nodeIdIn . ')';
707
            } else {
708 18
                $order_by = '`parent`.`' . $this->settings->leftColumnName . '` ASC';
709
            }
710 80
            $sql .= ' ORDER BY ' . $order_by;
711 2
        } elseif ($options->joinChild) {
712 2
            $sql .= ' GROUP BY `' . $this->settings->idColumnName . '`';
713
        }
714
715 82
        return $sql;
716
    }
717
718 82
    protected function canJoinChild(Support\Options $options) : bool
719
    {
720 82
        return (!is_null($options->currentId) || !is_null($options->parentId) || !empty($options->search) || $options->joinChild);
721
    }
722
}
723