Passed
Push — master ( f7d6c6...2d02cb )
by Petr
02:57
created

MySql::addSorting()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

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