Completed
Push — master ( f06abd...131973 )
by Ivan
02:27
created

TableQuery::any()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.8333
cc 3
nc 3
nop 1
crap 3
1
<?php
2
namespace vakata\database\schema;
3
4
use vakata\collection\Collection;
5
use vakata\database\DBInterface;
6
use vakata\database\DBException;
7
use vakata\database\ResultInterface;
8
9
/**
10
 * A database query class
11
 */
12
class TableQuery implements \IteratorAggregate, \ArrayAccess, \Countable
13
{
14
    const SEP = '___';
15
    /**
16
     * @var DBInterface
17
     */
18
    protected $db;
19
    /**
20
     * @var Table
21
     */
22
    protected $definition;
23
    /**
24
     * @var TableQueryIterator|null
25
     */
26
    protected $qiterator;
27
28
    /**
29
     * @var array
30
     */
31
    protected $where = [];
32
    /**
33
     * @var array
34
     */
35
    protected $order = [];
36
    /**
37
     * @var array
38
     */
39
    protected $group = [];
40
    /**
41
     * @var array
42
     */
43
    protected $having = [];
44
    /**
45
     * @var int[]
46
     */
47
    protected $li_of = [0,0,0];
48
    /**
49
     * @var array
50
     */
51
    protected $fields = [];
52
    /**
53
     * @var array
54
     */
55
    protected $withr = [];
56
    /**
57
     * @var array
58
     */
59
    protected $joins = [];
60
    /**
61
     * @var array
62
     */
63
    protected $pkey = [];
64
    /**
65
     * @var array
66
     */
67
    protected $aliases = [];
68
69
    /**
70
     * Create an instance
71
     * @param  DBInterface    $db         the database connection
72
     * @param  Table|string   $table      the name or definition of the main table in the query
73
     */
74 36
    public function __construct(DBInterface $db, $table)
75
    {
76 36
        $this->db = $db;
77 36
        $this->definition = $table instanceof Table ? $table : $this->db->definition((string)$table);
78 36
        $primary = $this->definition->getPrimaryKey();
79 36
        $columns = $this->definition->getColumns();
80 36
        $this->pkey = count($primary) ? $primary : $columns;
81 36
        $this->columns($columns);
82 36
    }
83
    public function __clone()
84
    {
85
        $this->reset();
86
    }
87
    /**
88
     * Get the table definition of the queried table
89
     * @return Table        the definition
90
     */
91
    public function getDefinition() : Table
92
    {
93
        return $this->definition;
94
    }
95
96 36
    protected function getColumn($column)
97
    {
98 36
        $column = explode('.', $column);
99 36
        if (count($column) === 1) {
100 36
            $column = [ $this->definition->getName(), $column[0] ];
101 36
            $col = $this->definition->getColumn($column[1]);
102 36
            if (!$col) {
103 36
                throw new DBException('Invalid column name in own table');
104
            }
105 4
        } elseif (count($column) === 2) {
106 4
            if ($column[0] === $this->definition->getName()) {
107
                $col = $this->definition->getColumn($column[1]);
108
                if (!$col) {
109
                    throw new DBException('Invalid column name in own table');
110
                }
111
            } else {
112 4
                if ($this->definition->hasRelation($column[0])) {
113 2
                    $col = $this->definition->getRelation($column[0])->table->getColumn($column[1]);
114 2
                    if (!$col) {
115 2
                        throw new DBException('Invalid column name in related table');
116
                    }
117 2
                } else if (isset($this->joins[$column[0]])) {
118 2
                    $col = $this->joins[$column[0]]->table->getColumn($column[1]);
119 2
                    if (!$col) {
120 2
                        throw new DBException('Invalid column name in related table');
121
                    }
122
                } else {
123 4
                    throw new DBException('Invalid foreign table name: ' . implode(',', $column));
124
                }
125
            }
126
        } else {
127
            $name = array_pop($column);
128
            $this->with(implode('.', $column));
129
            $table = $this->definition;
130
            $table = array_reduce(
131
                $column,
132
                function ($carry, $item) use (&$table) {
133
                    $table = $table->getRelation($item)->table;
134
                    return $table;
135
                }
136
            );
137
            $col = $table->getColumn($name);
138
            $column = [ implode(static::SEP, $column), $name ];
139
        }
140 36
        return [ 'name' => implode('.', $column), 'data' => $col ];
141
    }
142 18
    protected function normalizeValue(TableColumn $col, $value)
143
    {
144 18
        $strict = (int)$this->db->driverOption('strict', 0) > 0;
145 18
        if ($value === null && $col->isNullable()) {
146
            return null;
147
        }
148 18
        switch ($col->getBasicType()) {
149 18
            case 'date':
150
                if (is_string($value)) {
151
                    $temp = strtotime($value);
152
                    if (!$temp) {
153
                        if ($strict) {
154
                            throw new DBException('Invalid value for date column ' . $col->getName());
155
                        }
156
                        return null;
157
                    }
158
                    return date('Y-m-d', $temp);
159
                }
160
                if (is_int($value)) {
161
                    return date('Y-m-d', $value);
162
                }
163
                if ($value instanceof \DateTime) {
164
                    return $value->format('Y-m-d');
165
                }
166
                if ($strict) {
167
                    throw new DBException('Invalid value (unknown data type) for date column ' . $col->getName());
168
                }
169
                return $value;
170 18
            case 'datetime':
171
                if (is_string($value)) {
172
                    $temp = strtotime($value);
173
                    if (!$temp) {
174
                        if ($strict) {
175
                            throw new DBException('Invalid value for datetime column ' . $col->getName());
176
                        }
177
                        return null;
178
                    }
179
                    return date('Y-m-d H:i:s', $temp);
180
                }
181
                if (is_int($value)) {
182
                    return date('Y-m-d H:i:s', $value);
183
                }
184
                if ($value instanceof \DateTime) {
185
                    return $value->format('Y-m-d H:i:s');
186
                }
187
                if ($strict) {
188
                    throw new DBException('Invalid value (unknown data type) for datetime column ' . $col->getName());
189
                }
190
                return $value;
191 18
            case 'enum':
192
                $values = $col->getValues();
193
                if (is_int($value)) {
194
                    if (!isset($values[$value])) {
195
                        if ($strict) {
196
                            throw new DBException('Invalid value (using integer) for enum ' . $col->getName());
197
                        }
198
                        return $value;
199
                    }
200
                    return $values[$value];
201
                }
202
                if (!in_array($value, $col->getValues())) {
203
                    if ($strict) {
204
                        throw new DBException('Invalid value for enum ' . $col->getName());
205
                    }
206
                    return 0;
207
                }
208
                return $value;
209 18
            case 'int':
210 5
                return (int)preg_replace('([^+\-0-9]+)', '', $value);
211 15
            case 'float':
212
                return (float)preg_replace('([^+\-0-9.]+)', '', str_replace(',', '.', $value));
213 15
            case 'text':
214
                // check using strlen first, in order to avoid hitting mb_ functions which might be polyfilled
215
                // because the polyfill is quite slow
216 15
                if ($col->hasLength() && strlen($value) > $col->getLength() && mb_strlen($value) > $col->getLength()) {
217 4
                    if ($strict) {
218 2
                        throw new DBException('Invalid value for text column ' . $col->getName());
219
                    }
220 2
                    return mb_substr($value, 0, $col->getLength());
221
                }
222 12
                return $value;
223
            default: // time, blob, etc
224
                return $value;
225
        }
226
    }
227
228 12
    protected function filterSQL(string $column, $value, bool $negate = false) : array
229
    {
230 12
        list($name, $column) = array_values($this->getColumn($column));
231 12
        if (is_array($value) && count($value) === 1 && isset($value['not'])) {
232 2
            $negate = true;
233 2
            $value = $value['not'];
234
        }
235 12
        if (is_array($value) && count($value) === 1 && isset($value['like'])) {
236 2
            $value = $value['like'];
237
            // str_replace(['%', '_'], ['\\%','\\_'], $q)
238 2
            return $negate ?
239
                [
240
                    $name . ' NOT LIKE ?',
241
                    [ $this->normalizeValue($column, $value) ]
242
                ] :
243
                [
244 2
                    $name . ' LIKE ?',
245 2
                    [ $this->normalizeValue($column, $value) ]
246
                ];
247
        }
248 10
        if (is_null($value)) {
249
            return $negate ?
250
                [ $name . ' IS NOT NULL', [] ]:
251
                [ $name . ' IS NULL', [] ];
252
        }
253 10
        if (!is_array($value)) {
254 10
            return $negate ?
255
                [
256 2
                    $name . ' <> ?',
257 2
                    [ $this->normalizeValue($column, $value) ]
258
                ] :
259
                [
260 10
                    $name . ' = ?',
261 10
                    [ $this->normalizeValue($column, $value) ]
262
                ];
263
        }
264 6
        if (isset($value['beg']) && strlen($value['beg']) && (!isset($value['end']) || !strlen($value['end']))) {
265
            $value = [ 'gte' => $value['beg'] ];
266
        }
267 6
        if (isset($value['end']) && strlen($value['end']) && (!isset($value['beg']) || !strlen($value['beg']))) {
268
            $value = [ 'lte' => $value['end'] ];
269
        }
270 6
        if (isset($value['beg']) && isset($value['end'])) {
271
            return $negate ?
272
                [
273
                    $name.' NOT BETWEEN ? AND ?',
274
                    [
275
                        $this->normalizeValue($column, $value['beg']),
276
                        $this->normalizeValue($column, $value['end'])
277
                    ]
278
                ] :
279
                [
280
                    $name.' BETWEEN ? AND ?',
281
                    [
282
                        $this->normalizeValue($column, $value['beg']),
283
                        $this->normalizeValue($column, $value['end'])
284
                    ]
285
                ];
286
        }
287 6
        if (isset($value['gt']) || isset($value['lt']) || isset($value['gte']) || isset($value['lte'])) {
288 4
            $sql = [];
289 4
            $par = [];
290 4
            if (isset($value['gt'])) {
291 2
                $sql[] = $name. ' ' . ($negate ? '<=' : '>') . ' ?';
292 2
                $par[] = $this->normalizeValue($column, $value['gt']);
293
            }
294 4
            if (isset($value['gte'])) {
295 2
                $sql[] = $name. ' ' . ($negate ? '<' : '>=') . ' ?';
296 2
                $par[] = $this->normalizeValue($column, $value['gte']);
297
            }
298 4
            if (isset($value['lt'])) {
299 4
                $sql[] = $name. ' ' . ($negate ? '>=' : '<') . ' ?';
300 4
                $par[] = $this->normalizeValue($column, $value['lt']);
301
            }
302 4
            if (isset($value['lte'])) {
303 2
                $sql[] = $name. ' ' . ($negate ? '>' : '<=') . ' ?';
304 2
                $par[] = $this->normalizeValue($column, $value['lte']);
305
            }
306
            return [
307 4
                '(' . implode(' AND ', $sql) . ')',
308 4
                $par
309
            ];
310
        }
311 4
        return $negate ?
312
            [
313
                $name . ' NOT IN (??)',
314
                [ array_map(function ($v) use ($column) { return $this->normalizeValue($column, $v); }, $value) ]
315
            ] :
316
            [
317 4
                $name . ' IN (??)',
318
                [ array_map(function ($v) use ($column) { return $this->normalizeValue($column, $v); }, $value) ]
319
            ];
320
    }
321
    /**
322
     * Filter the results by a column and a value
323
     * @param  string $column  the column name to filter by (related columns can be used - for example: author.name)
324
     * @param  mixed  $value   a required value, array of values or range of values (range example: ['beg'=>1,'end'=>3])
325
     * @param  bool   $negate  optional boolean indicating that the filter should be negated
326
     * @return $this
327
     */
328 8
    public function filter(string $column, $value, bool $negate = false) : TableQuery
329
    {
330 8
        $sql = $this->filterSQL($column, $value, $negate);
331 8
        return strlen($sql[0]) ? $this->where($sql[0], $sql[1]) : $this;
332
    }
333
    /**
334
     * Filter the results matching any of the criteria
335
     * @param  array $criteria  each row is a column, value and optional negate flag (same as filter method)
336
     * @return $this
337
     */
338 4
    public function any(array $criteria) : TableQuery
339
    {
340 4
        $sql = [];
341 4
        $par = [];
342 4
        foreach ($criteria as $row) {
343 4
            if (isset($row[1])) {
344 4
                $temp = $this->filterSQL($row[0], $row[1] ?? null, $row[2] ?? false);
345 4
                $sql[] = $temp[0];
346 4
                $par = array_merge($par, $temp[1]);
347
            }
348
        }
349 4
        return $this->where('(' . implode(' OR ', $sql) . ')', $par);
350
    }
351
    /**
352
     * Filter the results matching all of the criteria
353
     * @param  array $criteria  each row is a column, value and optional negate flag (same as filter method)
354
     * @return $this
355
     */
356 2
    public function all(array $criteria) : TableQuery
357
    {
358 2
        $sql = [];
359 2
        $par = [];
360 2
        foreach ($criteria as $row) {
361 2
            if (isset($row[1])) {
362 2
                $temp = $this->filterSQL($row[0], $row[1] ?? null, $row[2] ?? false);
363 2
                $sql[] = $temp[0];
364 2
                $par = array_merge($par, $temp[1]);
365
            }
366
        }
367 2
        return $this->where('(' . implode(' AND ', $sql) . ')', $par);
368
    }
369
    /**
370
     * Sort by a column
371
     * @param  string       $column the column name to sort by (related columns can be used - for example: author.name)
372
     * @param  bool|boolean $desc   should the sorting be in descending order, defaults to `false`
373
     * @return $this
374
     */
375
    public function sort(string $column, bool $desc = false) : TableQuery
376
    {
377
        return $this->order($this->getColumn($column)['name'] . ' ' . ($desc ? 'DESC' : 'ASC'));
378
    }
379
    /**
380
     * Group by a column (or columns)
381
     * @param  string|array        $column the column name (or names) to group by
382
     * @return $this
383
     */
384 2
    public function group($column) : TableQuery
385
    {
386 2
        if (!is_array($column)) {
387 2
            $column = [ $column ];
388
        }
389 2
        foreach ($column as $k => $v) {
390 2
            $column[$k] = $this->getColumn($v)['name'];
391
        }
392 2
        return $this->groupBy(implode(', ', $column), []);
393
    }
394
    /**
395
     * Get a part of the data
396
     * @param  int|integer $page    the page number to get (1-based), defaults to 1
397
     * @param  int|integer $perPage the number of records per page - defaults to 25
398
     * @return $this
399
     */
400
    public function paginate(int $page = 1, int $perPage = 25) : TableQuery
401
    {
402
        return $this->limit($perPage, ($page - 1) * $perPage);
403
    }
404 2
    public function __call($name, $data)
405
    {
406 2
        if (strpos($name, 'filterBy') === 0) {
407
            return $this->filter(strtolower(substr($name, 8)), $data[0]);
408
        }
409 2
        if (strpos($name, 'sortBy') === 0) {
410
            return $this->sort(strtolower(substr($name, 6)), $data[0]);
411
        }
412 2
        if (strpos($name, 'groupBy') === 0) {
413 2
            return $this->group(strtolower(substr($name, 7)));
414
        }
415
    }
416
    /**
417
     * Remove all filters, sorting, etc
418
     * @return $this
419
     */
420 6
    public function reset() : TableQuery
421
    {
422 6
        $this->where = [];
423 6
        $this->joins = [];
424 6
        $this->group = [];
425 6
        $this->withr = [];
426 6
        $this->order = [];
427 6
        $this->having = [];
428 6
        $this->aliases = [];
429 6
        $this->li_of = [0,0,0];
430 6
        $this->qiterator = null;
431 6
        return $this;
432
    }
433
    /**
434
     * Apply advanced grouping
435
     * @param  string $sql    SQL statement to use in the GROUP BY clause
436
     * @param  array  $params optional params for the statement (defaults to an empty array)
437
     * @return $this
438
     */
439 2
    public function groupBy(string $sql, array $params = []) : TableQuery
440
    {
441 2
        $this->qiterator = null;
442 2
        $this->group = [ $sql, $params ];
443 2
        return $this;
444
    }
445
    /**
446
     * Join a table to the query (no need to do this for relations defined with foreign keys)
447
     * @param  Table|string $table     the table to join
448
     * @param  array        $fields    what to join on (joined_table_field => other_field) 
449
     * @param  string|null  $name      alias for the join, defaults to the table name 
450
     * @param  bool         $multiple  are multiple rows joined (results in a LEFT JOIN), default to true 
451
     * @return $this
452
     */
453 2
    public function join($table, array $fields, string $name = null, bool $multiple = true)
454
    {
455 2
        $table = $table instanceof Table ? $table : $this->db->definition((string)$table);
456 2
        $name = $name ?? $table->getName();
457 2
        if (isset($this->joins[$name]) || $this->definition->hasRelation($name)) {
458
            throw new DBException('Alias / table name already in use');
459
        }
460 2
        $this->joins[$name] = new TableRelation($name, $table, [], $multiple);
461 2
        foreach ($fields as $k => $v) {
462 2
            $k = explode('.', $k, 2);
463 2
            $k = count($k) == 2 ? $k[1] : $k[0];
464 2
            $this->joins[$name]->keymap[$this->getColumn($name . '.' . $k)['name']] = $this->getColumn($v)['name'];
465
        }
466 2
        return $this;
467
    }
468
    /**
469
     * Apply an advanced filter (can be called multiple times)
470
     * @param  string $sql    SQL statement to be used in the where clause
471
     * @param  array  $params parameters for the SQL statement (defaults to an empty array)
472
     * @return $this
473
     */
474 14
    public function where(string $sql, array $params = []) : TableQuery
475
    {
476 14
        $this->qiterator = null;
477 14
        $this->where[] = [ $sql, $params ];
478 14
        return $this;
479
    }
480
    /**
481
     * Apply an advanced HAVING filter (can be called multiple times)
482
     * @param  string $sql    SQL statement to be used in the HAING clause
483
     * @param  array  $params parameters for the SQL statement (defaults to an empty array)
484
     * @return $this
485
     */
486 2
    public function having(string $sql, array $params = []) : TableQuery
487
    {
488 2
        $this->qiterator = null;
489 2
        $this->having[] = [ $sql, $params ];
490 2
        return $this;
491
    }
492
    /**
493
     * Apply advanced sorting
494
     * @param  string $sql    SQL statement to use in the ORDER clause
495
     * @param  array  $params optional params for the statement (defaults to an empty array)
496
     * @return $this
497
     */
498 2
    public function order(string $sql, array $params = []) : TableQuery
499
    {
500 2
        $this->qiterator = null;
501 2
        $this->order = [ $sql, $params ];
502 2
        return $this;
503
    }
504
    /**
505
     * Apply an advanced limit
506
     * @param  int         $limit  number of rows to return
507
     * @param  int         $offset number of rows to skip from the beginning (defaults to 0)
508
     * @return $this
509
     */
510 2
    public function limit(int $limit, int $offset = 0, bool $limitOnMainTable = false) : TableQuery
511
    {
512 2
        $this->qiterator = null;
513 2
        $this->li_of = [ $limit, $offset, $limitOnMainTable ? 1 : 0 ];
514 2
        return $this;
515
    }
516
    /**
517
     * Get the number of records
518
     * @return int the total number of records (does not respect pagination)
519
     */
520 12
    public function count() : int
521
    {
522 12
        $aliases = [];
523 12
        $getAlias = function ($name) use (&$aliases) {
524
            // to bypass use: return $name;
525 2
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
526 12
        };
527 12
        $table = $this->definition->getName();
528 12
        $sql = 'SELECT COUNT(DISTINCT '.$table.'.'.implode(', '.$table.'.', $this->pkey).') FROM '.$table.' ';
529 12
        $par = [];
530
        
531 12
        $relations = $this->withr;
532 12
        foreach ($relations as $k => $v) {
533
            $getAlias($k);
534
        }
535 12
        $f = $this->fields;
0 ignored issues
show
Unused Code introduced by
$f is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
536 12
        $w = $this->where;
537 12
        $h = $this->having;
538 12
        $o = $this->order;
539 12
        $g = $this->group;
540
        $j = array_map(function ($v) { return clone $v; }, $this->joins);
541 12
        foreach ($this->definition->getRelations() as $k => $v) {
542 12
            foreach ($w as $kk => $vv) {
543 8
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
544 2
                    $relations[$k] = [ $v, $table ];
545 8
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
546
                }
547
            }
548 12
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
549
                $relations[$k] = [ $v, $table ];
550
            }
551 12
            foreach ($h as $kk => $vv) {
552
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
553
                    $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
554
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
555
                }
556
            }
557 12
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
558
                $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
559
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
560
            }
561 12
            foreach ($j as $kk => $v) {
562
                foreach ($v->keymap as $kkk => $vv) {
563
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv)) {
564
                        $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
565 12
                        $j[$k]->keymap[$kkk] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv);
566
                    }
567
                }
568
            }
569
        }
570
571 12
        foreach ($j as $k => $v) {
572
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
573
            $tmp = [];
574
            foreach ($v->keymap as $kk => $vv) {
575
                $tmp[] = $kk.' = '.$vv;
576
            }
577
            $sql .= implode(' AND ', $tmp) . ' ';
578
        }
579 12
        foreach ($relations as $k => $v) {
580 2
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
581 2
            $v = $v[0];
582 2
            if ($v->pivot) {
583 2
                $alias = $getAlias($k.'_pivot');
584 2
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
585 2
                $tmp = [];
586 2
                foreach ($v->keymap as $kk => $vv) {
587 2
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
588
                }
589 2
                $sql .= implode(' AND ', $tmp) . ' ';
590 2
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($k).' ON ';
591 2
                $tmp = [];
592 2
                foreach ($v->pivot_keymap as $kk => $vv) {
593 2
                    $tmp[] = $getAlias($k).'.'.$vv.' = '.$alias.'.'.$kk.' ';
594
                }
595 2
                $sql .= implode(' AND ', $tmp) . ' ';
596
            } else {
597 2
                $alias = $getAlias($k);
598 2
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
599 2
                $tmp = [];
600 2
                foreach ($v->keymap as $kk => $vv) {
601 2
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
602
                }
603 2
                if ($v->sql) {
604
                    $tmp[] = $v->sql . ' ';
605
                    $par = array_merge($par, $v->par ?? []);
606
                }
607 2
                $sql .= implode(' AND ', $tmp) . ' ';
608
            }
609
        }
610 12
        if (count($w)) {
611 8
            $sql .= 'WHERE ';
612 8
            $tmp = [];
613 8
            foreach ($w as $v) {
614 8
                $tmp[] = '(' . $v[0] . ')';
615 8
                $par = array_merge($par, $v[1]);
616
            }
617 8
            $sql .= implode(' AND ', $tmp).' ';
618
        }
619 12
        if (count($g)) {
620
            $sql .= 'GROUP BY ' . $g[0] . ' ';
621
            $par = array_merge($par, $g[1]);
622
        }
623 12
        if (count($h)) {
624
            $sql .= 'HAVING ';
625
            $tmp = [];
626
            foreach ($h as $v) {
627
                $tmp[] = '(' . $v[0] . ')';
628
                $par = array_merge($par, $v[1]);
629
            }
630
            $sql .= implode(' AND ', $tmp).' ';
631
        }
632 12
        return $this->db->one($sql, $par);
633
    }
634
    /**
635
     * Specify which columns to fetch (be default all table columns are fetched)
636
     * @param  array $fields optional array of columns to select (related columns can be used too)
637
     * @return $this
638
     */
639 36
    public function columns(array $fields) : TableQuery
640
    {
641 36
        foreach ($fields as $k => $v) {
642 36
            if (strpos($v, '*') !== false) {
643
                $temp = explode('.', $v);
644
                if (count($temp) === 1) {
645
                    $table = $this->definition->getName();
646
                    $cols = $this->definition->getColumns();
647
                } else if (count($temp) === 2) {
648
                    $table = $temp[0];
649
                    if ($this->definition->hasRelation($table)) {
650
                        $cols = $this->definition->getRelation($table)->table->getColumns();
651
                    } else if (isset($this->joins[$table])) {
652
                        $cols = $this->joins[$table]->table->getColumns();
653
                    } else {
654
                        throw new DBException('Invalid foreign table name');
655
                    }
656
                } else {
657
                    array_pop($temp);
658
                    $this->with(implode('.', $temp));
659
                    $table = array_reduce(
660
                        $temp,
661
                        function ($carry, $item) use (&$table) {
662
                            return $table->getRelation($item)->table;
663
                        }
664
                    );
665
                    $cols = $table->getColumns();
666
                    $table = implode(static::SEP, $temp);
667
                }
668
                unset($fields[$k]);
669
                foreach ($cols as $col) {
670 36
                    $fields[] = $table . '.' . $col;
671
                }
672
            }
673
        }
674 36
        $primary = $this->definition->getPrimaryKey();
675 36
        foreach ($fields as $k => $v) {
676
            try {
677 36
                $fields[$k] = $this->getColumn($v)['name'];
678 2
            } catch (DBException $e) {
679 36
                $fields[$k] = $v;
680
            }
681
        }
682 36
        foreach ($primary as $field) {
683 36
            $field = $this->getColumn($field)['name'];
684 36
            if (!in_array($field, $fields)) {
685 36
                $fields[] = $field;
686
            }
687
        }
688 36
        $this->fields = $fields;
689 36
        return $this;
690
    }
691
    /**
692
     * Perform the actual fetch
693
     * @param  array|null $fields optional array of columns to select (related columns can be used too)
694
     * @return TableQueryIterator               the query result as an iterator
695
     */
696 24
    public function iterator(array $fields = null) : TableQueryIterator
697
    {
698 24
        if ($this->qiterator) {
699 10
            return $this->qiterator;
700
        }
701 24
        $aliases = [];
702 24
        $getAlias = function ($name) use (&$aliases) {
703
            // to bypass use: return $name;
704 8
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
705 24
        };
706 24
        $table = $this->definition->getName();
707 24
        if ($fields !== null) {
708 2
            $this->columns($fields);
709
        }
710 24
        $relations = $this->withr;
711 24
        foreach ($relations as $k => $v) {
712 8
            $getAlias($k);
713
        }
714
715 24
        $f = $this->fields;
716 24
        $w = $this->where;
717 24
        $h = $this->having;
718 24
        $o = $this->order;
719 24
        $g = $this->group;
720
        $j = array_map(function ($v) { return clone $v; }, $this->joins);
721
722 24
        $porder = [];
723 24
        foreach ($this->definition->getPrimaryKey() as $field) {
724 24
            $porder[] = $this->getColumn($field)['name'];
725
        }
726
727 24
        if (count($porder) && $this->li_of[2] === 1) {
728
            $ids = $this->ids();
729
            if (count($ids)) {
730
                if (count($porder) > 1) {
731
                    $pkw = [];
732
                    foreach ($porder as $name) {
733
                        $pkw[] = $name . ' = ?';
734
                    }
735
                    $pkw = '(' . implode(' AND ', $pkw) . ')';
736
                    $pkp = [];
737
                    foreach ($ids as $id) {
738
                        foreach ($id as $p) {
739
                            $pkp[] = $p;
740
                        }
741
                    }
742
                    $w[] = [
743
                        implode(' OR ', array_fill(0, count($ids), $pkw)),
744
                        $pkp
745
                    ];
746
                } else {
747
                    $w[] = [ $porder[0] . ' IN ('.implode(',', array_fill(0, count($ids), '?')).')', $ids ];
748
                }
749
            } else {
750
                $w[] = [ '1=0', [] ];
751
            }
752
        }
753
754 24
        foreach ($this->definition->getRelations() as $k => $relation) {
755 24
            foreach ($f as $kk => $field) {
756 24
                if (strpos($field, $k . '.') === 0) {
757
                    $relations[$k] = [ $relation, $table ];
758 24
                    $f[$kk] = str_replace($k . '.', $getAlias($k) . '.', $field);
759
                }
760
            }
761 24
            foreach ($w as $kk => $v) {
762 2
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $v[0])) {
763
                    $relations[$k] = [ $relation, $table ];
764 2
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $v[0]);
765
                }
766
            }
767 24
            foreach ($h as $kk => $v) {
768 2
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $v[0])) {
769
                    $relations[$k] = [ $relation, $table ];
770 2
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $v[0]);
771
                }
772
            }
773 24
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
774
                $relations[$k] = [ $relation, $table ];
775
                $o[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $o[0]);
776
            }
777 24
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
778
                $relations[$k] = [ $relation, $table ];
779
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
780
            }
781 24
            foreach ($j as $kk => $v) {
782 2
                foreach ($v->keymap as $kkk => $vv) {
783 2
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv)) {
784
                        $relations[$k] = [ $relation, $table ];
785 24
                        $j[$k]->keymap[$kkk] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv);
786
                    }
787
                }
788
            }
789
        }
790 24
        $select = [];
791 24
        foreach ($f as $k => $field) {
792 24
            $select[] = $field . (!is_numeric($k) ? ' ' . $k : '');
793
        }
794 24
        foreach ($this->withr as $name => $relation) {
795 8
            foreach ($relation[0]->table->getColumns() as $column) {
796 8
                $select[] = $getAlias($name) . '.' . $column . ' ' . $getAlias($name . static::SEP . $column);
797
            }
798
        }
799 24
        $sql = 'SELECT '.implode(', ', $select).' FROM '.$table.' ';
800 24
        $par = [];
801 24
        foreach ($j as $k => $v) {
802 2
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
803 2
            $tmp = [];
804 2
            foreach ($v->keymap as $kk => $vv) {
805 2
                $tmp[] = $kk.' = '.$vv;
806
            }
807 2
            $sql .= implode(' AND ', $tmp) . ' ';
808
        }
809 24
        foreach ($relations as $relation => $v) {
810 8
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
811 8
            $v = $v[0];
812 8
            if ($v->pivot) {
813 6
                $alias = $getAlias($relation.'_pivot');
814 6
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
815 6
                $tmp = [];
816 6
                foreach ($v->keymap as $kk => $vv) {
817 6
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
818
                }
819 6
                $sql .= implode(' AND ', $tmp) . ' ';
820 6
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($relation).' ON ';
821 6
                $tmp = [];
822 6
                foreach ($v->pivot_keymap as $kk => $vv) {
823 6
                    $tmp[] = $getAlias($relation).'.'.$vv.' = '.$alias.'.'.$kk.' ';
824
                }
825 6
                $sql .= implode(' AND ', $tmp) . ' ';
826
            } else {
827 8
                $alias = $getAlias($relation);
828
829 8
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
830 8
                $tmp = [];
831 8
                foreach ($v->keymap as $kk => $vv) {
832 8
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
833
                }
834 8
                if ($v->sql) {
835
                    $tmp[] = $v->sql . ' ';
836
                    $par = array_merge($par, $v->par ?? []);
837
                }
838 8
                $sql .= implode(' AND ', $tmp) . ' ';
839
            }
840
        }
841 24
        if (count($w)) {
842 2
            $sql .= 'WHERE ';
843 2
            $tmp = [];
844 2
            foreach ($w as $v) {
845 2
                $tmp[] = '(' . $v[0] . ')';
846 2
                $par = array_merge($par, $v[1]);
847
            }
848 2
            $sql .= implode(' AND ', $tmp).' ';
849
        }
850 24
        if (count($g)) {
851 2
            $sql .= 'GROUP BY ' . $g[0] . ' ';
852 2
            $par = array_merge($par, $g[1]);
853
        }
854 24
        if (count($h)) {
855 2
            $sql .= 'HAVING ';
856 2
            $tmp = [];
857 2
            foreach ($h as $v) {
858 2
                $tmp[] = '(' . $v[0] . ')';
859 2
                $par = array_merge($par, $v[1]);
860
            }
861 2
            $sql .= implode(' AND ', $tmp).' ';
862
        }
863 24
        if (count($o)) {
864 2
            $sql .= 'ORDER BY ' . $o[0] . ' ';
865 2
            $par = array_merge($par, $o[1]);
866
        }
867 24
        if (count($porder)) {
868 24
            $pdir = (count($o) && strpos($o[0], 'DESC') !== false) ? 'DESC' : 'ASC';
869
            $porder = array_map(function ($v) use ($pdir) { return $v . ' ' . $pdir; }, $porder);
870 24
            $sql .= (count($o) ? ', ' : 'ORDER BY ') . implode(', ', $porder) . ' ';
871
        }
872 24
        if (($this->li_of[2] === 0 || !count($porder)) && $this->li_of[0]) {
873 2
            if ($this->db->driverName() === 'oracle') {
874
                if ((int)$this->db->driverOption('version', 0) >= 12) {
875
                    $sql .= 'OFFSET ' . $this->li_of[1] . ' ROWS FETCH NEXT ' . $this->li_of[0] . ' ROWS ONLY';
876
                } else {
877
                    $f = array_map(function ($v) {
878
                        $v = explode(' ', trim($v), 2);
879
                        if (count($v) === 2) { return $v[1]; }
880
                        $v = explode('.', $v[0], 2);
881
                        return count($v) === 2 ? $v[1] : $v[0];
882
                    }, $select);
883
                    $sql = "SELECT " . implode(', ', $f) . " 
884
                            FROM (
885
                                SELECT tbl__.*, rownum rnum__ FROM (
886
                                    " . $sql . "
887
                                ) tbl__ 
888
                                WHERE rownum <= " . ($this->li_of[0] + $this->li_of[1]) . "
889
                            ) WHERE rnum__ > " . $this->li_of[1];
890
                }
891
            } else {
892 2
                $sql .= 'LIMIT ' . $this->li_of[0] . ' OFFSET ' . $this->li_of[1];
893
            }
894
        }
895 24
        return $this->qiterator = new TableQueryIterator(
896 24
            $this->db->get($sql, $par), 
897 24
            $this->pkey,
898 24
            $this->withr,
899 24
            $aliases
900
        );
901
    }
902
    /**
903
     * Perform the actual fetch
904
     * @param  array|null $fields optional array of columns to select (related columns can be used too)
905
     * @return array               the query result as an array
906
     */
907 2
    public function select(array $fields = null) : array
908
    {
909 2
        return iterator_to_array($this->iterator($fields));
910
    }
911
    /**
912
     * Insert a new row in the table
913
     * @param  array   $data   key value pairs, where each key is the column name and the value is the value to insert
914
     * @return array           the inserted ID where keys are column names and values are column values
915
     */
916 6
    public function insert(array $data) : array
917
    {
918 6
        $table = $this->definition->getName();
919 6
        $columns = $this->definition->getFullColumns();
920 6
        $insert = [];
921 6
        foreach ($data as $column => $value) {
922 6
            if (isset($columns[$column])) {
923 6
                $insert[$column] = $this->normalizeValue($columns[$column], $value);
924
            }
925
        }
926 4
        if (!count($insert)) {
927
            throw new DBException('No valid columns to insert');
928
        }
929 4
        $sql = 'INSERT INTO '.$table.' ('.implode(', ', array_keys($insert)).') VALUES (??)';
930 4
        $par = [$insert];
931 4
        $primary = $this->definition->getPrimaryKey();
932 4
        if (!count($primary)) {
933
            $this->db->query($sql, $par);
934
            return [];
935
        }
936 4
        if ($this->db->driverName() === 'oracle') {
937
            $ret = [];
938
            foreach ($primary as $k) {
939
                $ret[$k] = str_repeat(' ', 255);
940
                $par[] = &$ret[$k];
941
            }
942
            $sql .= ' RETURNING ' . implode(',', $primary) . ' INTO ' . implode(',', array_fill(0, count($primary), '?'));
943
            $this->db->query($sql, $par);
944
            return $ret;
945
        } else {
946 4
            $ret = [];
947 4
            $ins = $this->db->query($sql, $par)->insertID();
948 4
            foreach ($primary as $k) {
949 4
                $ret[$k] = $data[$k] ?? $ins;
950
            }
951 4
            return $ret;
952
        }
953
    }
954
    /**
955
     * Update the filtered rows with new data
956
     * @param  array  $data key value pairs, where each key is the column name and the value is the value to insert
957
     * @return int          the number of affected rows
958
     */
959 2
    public function update(array $data) : int
960
    {
961 2
        $table = $this->definition->getName();
962 2
        $columns = $this->definition->getFullColumns();
963 2
        $update = [];
964 2
        foreach ($data as $column => $value) {
965 2
            if (isset($columns[$column])) {
966 2
                $update[$column] = $this->normalizeValue($columns[$column], $value);
967
            }
968
        }
969 2
        if (!count($update)) {
970
            throw new DBException('No valid columns to update');
971
        }
972 2
        $sql = 'UPDATE '.$table.' SET ';
973 2
        $par = [];
974
        $sql .= implode(', ', array_map(function ($v) { return $v . ' = ?'; }, array_keys($update))) . ' ';
975 2
        $par = array_merge($par, array_values($update));
976 2
        if (count($this->where)) {
977 2
            $sql .= 'WHERE ';
978 2
            $tmp = [];
979 2
            foreach ($this->where as $v) {
980 2
                $tmp[] = $v[0];
981 2
                $par = array_merge($par, $v[1]);
982
            }
983 2
            $sql .= implode(' AND ', $tmp) . ' ';
984
        }
985 2
        if (count($this->order)) {
986
            $sql .= $this->order[0];
987
            $par = array_merge($par, $this->order[1]);
988
        }
989 2
        return $this->db->query($sql, $par)->affected();
990
    }
991
    /**
992
     * Delete the filtered rows from the DB
993
     * @return int the number of deleted rows
994
     */
995 2
    public function delete() : int
996
    {
997 2
        $table = $this->definition->getName();
998 2
        $sql = 'DELETE FROM '.$table.' ';
999 2
        $par = [];
1000 2
        if (count($this->where)) {
1001 2
            $sql .= 'WHERE ';
1002 2
            $tmp = [];
1003 2
            foreach ($this->where as $v) {
1004 2
                $tmp[] = $v[0];
1005 2
                $par = array_merge($par, $v[1]);
1006
            }
1007 2
            $sql .= implode(' AND ', $tmp) . ' ';
1008
        }
1009 2
        if (count($this->order)) {
1010
            $sql .= $this->order[0];
1011
            $par = array_merge($par, $this->order[1]);
1012
        }
1013 2
        return $this->db->query($sql, $par)->affected();
1014
    }
1015
    /**
1016
     * Solve the n+1 queries problem by prefetching a relation by name
1017
     * @param  string $relation the relation name to fetch along with the data
1018
     * @return $this
1019
     */
1020 8
    public function with(string $relation) : TableQuery
1021
    {
1022 8
        $this->qiterator = null;
1023 8
        $parts = explode('.', $relation);
1024 8
        $table = $this->definition;
1025 8
        array_reduce(
1026 8
            $parts,
1027 8
            function ($carry, $item) use (&$table) {
1028 8
                $relation = $table->getRelation($item);
1029 8
                if (!$relation) {
1030
                    throw new DBException('Invalid relation name');
1031
                }
1032 8
                $name = $carry ? $carry . static::SEP . $item : $item;
1033 8
                $this->withr[$name] = [ $relation, $carry ?? $table->getName() ];
1034 8
                $table = $relation->table;
1035 8
                return $name;
1036 8
            }
1037
        );
1038 8
        return $this;
1039
    }
1040
1041 2
    public function getIterator()
1042
    {
1043 2
        return $this->iterator();
1044
    }
1045
1046 20
    public function offsetGet($offset)
1047
    {
1048 20
        return $this->iterator()->offsetGet($offset);
1049
    }
1050
    public function offsetExists($offset)
1051
    {
1052
        return $this->iterator()->offsetExists($offset);
1053
    }
1054
    public function offsetUnset($offset)
1055
    {
1056
        return $this->iterator()->offsetUnset($offset);
1057
    }
1058
    public function offsetSet($offset, $value)
1059
    {
1060
        return $this->iterator()->offsetSet($offset, $value);
1061
    }
1062
1063
    public function collection(array $fields = null) : Collection
1064
    {
1065
        return new Collection($this->iterator($fields));
1066
    }
1067
1068
    public function ids()
1069
    {
1070
        $aliases = [];
1071
        $getAlias = function ($name) use (&$aliases) {
1072
            // to bypass use: return $name;
1073
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
1074
        };
1075
        $table = $this->definition->getName();
1076
        $sql = 'SELECT DISTINCT '.$table.'.'.implode(', '.$table.'.', $this->pkey).' FROM '.$table.' ';
1077
        $par = [];
1078
        
1079
        $relations = $this->withr;
1080
        foreach ($relations as $k => $v) {
1081
            $getAlias($k);
1082
        }
1083
        $f = $this->fields;
0 ignored issues
show
Unused Code introduced by
$f is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1084
        $w = $this->where;
1085
        $h = $this->having;
1086
        $o = $this->order;
1087
        $g = $this->group;
1088
        $j = array_map(function ($v) { return clone $v; }, $this->joins);
1089
        foreach ($this->definition->getRelations() as $k => $v) {
1090
            foreach ($w as $kk => $vv) {
1091
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
1092
                    $relations[$k] = [ $v, $table ];
1093
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
1094
                }
1095
            }
1096
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
1097
                $relations[$k] = [ $v, $table ];
1098
                $o[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $o[0]);
1099
            }
1100
            foreach ($h as $kk => $vv) {
1101
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
1102
                    $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1103
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
1104
                }
1105
            }
1106
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
1107
                $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1108
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
1109
            }
1110
            foreach ($j as $kk => $v) {
1111
                foreach ($v->keymap as $kkk => $vv) {
1112
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv)) {
1113
                        $relations[$k] = [ $relation, $table ];
0 ignored issues
show
Bug introduced by
The variable $relation does not exist. Did you mean $relations?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1114
                        $j[$k]->keymap[$kkk] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv);
1115
                    }
1116
                }
1117
            }
1118
        }
1119
1120
        foreach ($j as $k => $v) {
1121
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
1122
            $tmp = [];
1123
            foreach ($v->keymap as $kk => $vv) {
1124
                $tmp[] = $kk.' = '.$vv;
1125
            }
1126
            $sql .= implode(' AND ', $tmp) . ' ';
1127
        }
1128
        foreach ($relations as $k => $v) {
1129
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
1130
            $v = $v[0];
1131
            if ($v->pivot) {
1132
                $alias = $getAlias($k.'_pivot');
1133
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
1134
                $tmp = [];
1135
                foreach ($v->keymap as $kk => $vv) {
1136
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
1137
                }
1138
                $sql .= implode(' AND ', $tmp) . ' ';
1139
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($k).' ON ';
1140
                $tmp = [];
1141
                foreach ($v->pivot_keymap as $kk => $vv) {
1142
                    $tmp[] = $getAlias($k).'.'.$vv.' = '.$alias.'.'.$kk.' ';
1143
                }
1144
                $sql .= implode(' AND ', $tmp) . ' ';
1145
            } else {
1146
                $alias = $getAlias($k);
1147
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
1148
                $tmp = [];
1149
                foreach ($v->keymap as $kk => $vv) {
1150
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
1151
                }
1152
                if ($v->sql) {
1153
                    $tmp[] = $v->sql . ' ';
1154
                    $par = array_merge($par, $v->par ?? []);
1155
                }
1156
                $sql .= implode(' AND ', $tmp) . ' ';
1157
            }
1158
        }
1159
        if (count($w)) {
1160
            $sql .= 'WHERE ';
1161
            $tmp = [];
1162
            foreach ($w as $v) {
1163
                $tmp[] = '(' . $v[0] . ')';
1164
                $par = array_merge($par, $v[1]);
1165
            }
1166
            $sql .= implode(' AND ', $tmp).' ';
1167
        }
1168
        if (count($g)) {
1169
            $sql .= 'GROUP BY ' . $g[0] . ' ';
1170
            $par = array_merge($par, $g[1]);
1171
        }
1172
        if (count($h)) {
1173
            $sql .= 'HAVING ';
1174
            $tmp = [];
1175
            foreach ($h as $v) {
1176
                $tmp[] = '(' . $v[0] . ')';
1177
                $par = array_merge($par, $v[1]);
1178
            }
1179
            $sql .= implode(' AND ', $tmp).' ';
1180
        }
1181
        if (count($o)) {
1182
            $sql .= 'ORDER BY ' . $o[0] . ' ';
1183
            $par = array_merge($par, $o[1]);
1184
        }
1185
        $porder = [];
1186
        $pdir = (count($o) && strpos($o[0], 'DESC') !== false) ? 'DESC' : 'ASC';
1187
        foreach ($this->definition->getPrimaryKey() as $field) {
1188
            $porder[] = $this->getColumn($field)['name'] . ' ' . $pdir;
1189
        }
1190
        if (count($porder)) {
1191
            $sql .= (count($o) ? ', ' : 'ORDER BY ') . implode(', ', $porder) . ' ';
1192
        }
1193
1194
        if ($this->li_of[0]) {
1195
            if ($this->db->driverName() === 'oracle') {
1196
                if ((int)$this->db->driverOption('version', 0) >= 12) {
1197
                    $sql .= 'OFFSET ' . $this->li_of[1] . ' ROWS FETCH NEXT ' . $this->li_of[0] . ' ROWS ONLY';
1198
                } else {
1199
                    $f = array_map(function ($v) {
1200
                        $v = explode(' ', trim($v), 2);
1201
                        if (count($v) === 2) { return $v[1]; }
1202
                        $v = explode('.', $v[0], 2);
1203
                        return count($v) === 2 ? $v[1] : $v[0];
1204
                    }, $select);
0 ignored issues
show
Bug introduced by
The variable $select does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1205
                    $sql = "SELECT " . implode(', ', $f) . " 
1206
                            FROM (
1207
                                SELECT tbl__.*, rownum rnum__ FROM (
1208
                                    " . $sql . "
1209
                                ) tbl__ 
1210
                                WHERE rownum <= " . ($this->li_of[0] + $this->li_of[1]) . "
1211
                            ) WHERE rnum__ > " . $this->li_of[1];
1212
                }
1213
            } else {
1214
                $sql .= 'LIMIT ' . $this->li_of[0] . ' OFFSET ' . $this->li_of[1];
1215
            }
1216
        }
1217
        return $this->db->all($sql, $par);
1218
    }
1219
}
1220