Passed
Push — master ( f50cc5...0e0d61 )
by Petr
13:38
created

MySql::addSoftDelete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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