Passed
Pull Request — master (#474)
by Def
02:44
created

AbstractDQLQueryBuilder::buildColumns()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 21
rs 9.2222
c 0
b 0
f 0
cc 6
nc 9
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\QueryBuilder;
6
7
use Yiisoft\Db\Command\Param;
8
use Yiisoft\Db\Command\ParamBuilder;
9
use Yiisoft\Db\Exception\Exception;
10
use Yiisoft\Db\Exception\InvalidArgumentException;
11
use Yiisoft\Db\Exception\InvalidConfigException;
12
use Yiisoft\Db\Exception\NotSupportedException;
13
use Yiisoft\Db\Expression\Expression;
14
use Yiisoft\Db\Expression\ExpressionBuilder;
15
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
16
use Yiisoft\Db\Expression\ExpressionInterface;
17
use Yiisoft\Db\QueryBuilder\Condition\HashCondition;
18
use Yiisoft\Db\QueryBuilder\Condition\Interface\ConditionInterface;
19
use Yiisoft\Db\QueryBuilder\Condition\SimpleCondition;
20
use Yiisoft\Db\Query\Query;
21
use Yiisoft\Db\Query\QueryExpressionBuilder;
22
use Yiisoft\Db\Query\QueryInterface;
23
use Yiisoft\Db\Schema\QuoterInterface;
24
use Yiisoft\Db\Schema\SchemaInterface;
25
26
use function array_filter;
27
use function array_merge;
28
use function array_shift;
29
use function ctype_digit;
30
use function implode;
31
use function is_array;
32
use function is_int;
33
use function is_string;
34
use function ltrim;
35
use function preg_match;
36
use function preg_split;
37
use function reset;
38
use function strtoupper;
39
use function trim;
40
41
abstract class AbstractDQLQueryBuilder implements DQLQueryBuilderInterface
42
{
43
    protected string $separator = ' ';
44
45
    /**
46
     * @var array map of condition aliases to condition classes. For example:
47
     *
48
     * ```php
49
     * return [
50
     *     'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class,
51
     * ];
52
     * ```
53
     *
54
     * This property is used by {@see createConditionFromArray} method.
55
     * See default condition classes list in {@see defaultConditionClasses()} method.
56
     *
57
     * In case you want to add custom conditions support, use the {@see setConditionClasses()} method.
58
     *
59
     * @see setConditonClasses()
60
     * @see defaultConditionClasses()
61
     */
62
    protected array $conditionClasses = [];
63
64
    /**
65
     * @psalm-var array<string, class-string<ExpressionBuilderInterface>> maps expression class to expression builder
66
     * class.
67
     *
68
     * For example:
69
     *
70
     * ```php
71
     * [
72
     *    Expression::class => ExpressionBuilder::class
73
     * ]
74
     * ```
75
     * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects.
76
     * See default values in {@see defaultExpressionBuilders()} method.
77
     *
78
     * {@see setExpressionBuilders()}
79
     * {@see defaultExpressionBuilders()}
80
     */
81
    protected array $expressionBuilders = [];
82
83
    public function __construct(
84
        private QueryBuilderInterface $queryBuilder,
85
        private QuoterInterface $quoter,
86
        private SchemaInterface $schema
87
    ) {
88
        $this->expressionBuilders = $this->defaultExpressionBuilders();
89
        $this->conditionClasses = $this->defaultConditionClasses();
90
    }
91
92
    public function build(QueryInterface $query, array $params = []): array
93
    {
94
        $query = $query->prepare($this->queryBuilder);
95
        $params = empty($params) ? $query->getParams() : array_merge($params, $query->getParams());
96
        $clauses = [
97
            $this->buildSelect($query->getSelect(), $params, $query->getDistinct(), $query->getSelectOption()),
98
            $this->buildFrom($query->getFrom(), $params),
99
            $this->buildJoin($query->getJoin(), $params),
100
            $this->buildWhere($query->getWhere(), $params),
101
            $this->buildGroupBy($query->getGroupBy(), $params),
102
            $this->buildHaving($query->getHaving(), $params),
103
        ];
104
        $sql = implode($this->separator, array_filter($clauses));
105
        $sql = $this->buildOrderByAndLimit($sql, $query->getOrderBy(), $query->getLimit(), $query->getOffset());
106
107
        if (!empty($query->getOrderBy())) {
108
            /** @psalm-var array<string, ExpressionInterface|string> */
109
            foreach ($query->getOrderBy() as $expression) {
110
                if ($expression instanceof ExpressionInterface) {
111
                    $this->buildExpression($expression, $params);
112
                }
113
            }
114
        }
115
116
        if (!empty($query->getGroupBy())) {
117
            /** @psalm-var array<string, ExpressionInterface|string> */
118
            foreach ($query->getGroupBy() as $expression) {
119
                if ($expression instanceof ExpressionInterface) {
120
                    $this->buildExpression($expression, $params);
121
                }
122
            }
123
        }
124
125
        $union = $this->buildUnion($query->getUnion(), $params);
126
127
        if ($union !== '') {
128
            $sql = "($sql)$this->separator$union";
129
        }
130
131
        $with = $this->buildWithQueries($query->getWithQueries(), $params);
132
133
        if ($with !== '') {
134
            $sql = "$with$this->separator$sql";
135
        }
136
137
        return [$sql, $params];
138
    }
139
140
    public function buildColumns(array|string $columns): string
141
    {
142
        if (!is_array($columns)) {
0 ignored issues
show
introduced by
The condition is_array($columns) is always true.
Loading history...
143
            if (str_contains($columns, '(')) {
144
                return $columns;
145
            }
146
147
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
148
        }
149
150
        /** @psalm-var ExpressionInterface|string $column */
151
        foreach ((array) $columns as $i => $column) {
152
            if ($column instanceof ExpressionInterface) {
153
                $columns[$i] = $this->buildExpression($column);
154
            } elseif (!str_contains($column, '(')) {
155
                $columns[$i] = $this->quoter->quoteColumnName($column);
156
            }
157
        }
158
159
        /** @psalm-var string[] $columns */
160
        return implode(', ', $columns);
161
    }
162
163
    public function buildCondition(array|string|ExpressionInterface|null $condition, array &$params = []): string
164
    {
165
        if (is_array($condition)) {
0 ignored issues
show
introduced by
The condition is_array($condition) is always true.
Loading history...
166
            if (empty($condition)) {
167
                return '';
168
            }
169
170
            $condition = $this->createConditionFromArray($condition);
171
        }
172
173
        if ($condition instanceof ExpressionInterface) {
0 ignored issues
show
introduced by
$condition is always a sub-type of Yiisoft\Db\Expression\ExpressionInterface.
Loading history...
174
            return $this->buildExpression($condition, $params);
175
        }
176
177
        return $condition ?? '';
178
    }
179
180
    /**
181
     * @throws InvalidArgumentException
182
     *
183
     * @psalm-suppress UndefinedInterfaceMethod
184
     * @psalm-suppress MixedMethodCall
185
     */
186
    public function buildExpression(ExpressionInterface $expression, array &$params = []): string
187
    {
188
        $builder = $this->queryBuilder->getExpressionBuilder($expression);
189
        return (string) $builder->build($expression, $params);
190
    }
191
192
    public function buildFrom(array|null $tables, array &$params): string
193
    {
194
        if (empty($tables)) {
195
            return '';
196
        }
197
198
        /** @psalm-var string[] */
199
        $tables = $this->quoteTableNames($tables, $params);
200
201
        return 'FROM ' . implode(', ', $tables);
202
    }
203
204
    public function buildGroupBy(array $columns, array &$params = []): string
205
    {
206
        if (empty($columns)) {
207
            return '';
208
        }
209
210
        /** @psalm-var array<string, Expression|string> $columns */
211
        foreach ($columns as $i => $column) {
212
            if ($column instanceof Expression) {
213
                $columns[$i] = $this->buildExpression($column);
214
                $params = array_merge($params, $column->getParams());
215
            } elseif (!str_contains($column, '(')) {
216
                $columns[$i] = $this->quoter->quoteColumnName($column);
217
            }
218
        }
219
220
        return 'GROUP BY ' . implode(', ', $columns);
221
    }
222
223
    public function buildHaving(array|ExpressionInterface|string|null $condition, array &$params = []): string
224
    {
225
        $having = $this->buildCondition($condition, $params);
226
227
        return ($having === '') ? '' : ('HAVING ' . $having);
228
    }
229
230
    public function buildJoin(array $joins, array &$params): string
231
    {
232
        if (empty($joins)) {
233
            return '';
234
        }
235
236
        /**
237
         * @psalm-var array<
238
         *   array-key,
239
         *   array{
240
         *     0?:string,
241
         *     1?:array<array-key, Query|string>|string,
242
         *     2?:array|ExpressionInterface|string|null
243
         *   }|null
244
         * > $joins
245
         */
246
        foreach ($joins as $i => $join) {
247
            if (!is_array($join) || !isset($join[0], $join[1])) {
248
                throw new Exception(
249
                    'A join clause must be specified as an array of join type, join table, and optionally join '
250
                    . 'condition.'
251
                );
252
            }
253
254
            /* 0:join type, 1:join table, 2:on-condition (optional) */
255
            [$joinType, $table] = $join;
256
257
            $tables = $this->quoteTableNames((array) $table, $params);
258
259
            /** @var string $table */
260
            $table = reset($tables);
261
            $joins[$i] = "$joinType $table";
262
263
            if (isset($join[2])) {
264
                $condition = $this->buildCondition($join[2], $params);
265
                if ($condition !== '') {
266
                    $joins[$i] .= ' ON ' . $condition;
267
                }
268
            }
269
        }
270
271
        /** @psalm-var array<string> $joins */
272
        return implode($this->separator, $joins);
273
    }
274
275
    public function buildLimit(Expression|int|null $limit, Expression|int|null $offset): string
276
    {
277
        $sql = '';
278
279
        if ($this->hasLimit($limit)) {
280
            $sql = 'LIMIT ' . (string) $limit;
281
        }
282
283
        if ($this->hasOffset($offset)) {
284
            $sql .= ' OFFSET ' . (string) $offset;
285
        }
286
287
        return ltrim($sql);
288
    }
289
290
    public function buildOrderBy(array $columns, array &$params = []): string
291
    {
292
        if (empty($columns)) {
293
            return '';
294
        }
295
296
        $orders = [];
297
298
        /** @psalm-var array<string, Expression|int|string> $columns */
299
        foreach ($columns as $name => $direction) {
300
            if ($direction instanceof Expression) {
301
                $orders[] = $this->buildExpression($direction);
302
                $params = array_merge($params, $direction->getParams());
303
            } else {
304
                $orders[] = $this->quoter->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
305
            }
306
        }
307
308
        return 'ORDER BY ' . implode(', ', $orders);
309
    }
310
311
    public function buildOrderByAndLimit(
312
        string $sql,
313
        array $orderBy,
314
        Expression|int|null $limit,
315
        Expression|int|null $offset,
316
        array &$params = []
317
    ): string {
318
        $orderBy = $this->buildOrderBy($orderBy, $params);
319
        if ($orderBy !== '') {
320
            $sql .= $this->separator . $orderBy;
321
        }
322
        $limit = $this->buildLimit($limit, $offset);
323
        if ($limit !== '') {
324
            $sql .= $this->separator . $limit;
325
        }
326
327
        return $sql;
328
    }
329
330
    public function buildSelect(
331
        array $columns,
332
        array &$params,
333
        bool|null $distinct = false,
334
        string $selectOption = null
335
    ): string {
336
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
337
338
        if ($selectOption !== null) {
339
            $select .= ' ' . $selectOption;
340
        }
341
342
        if (empty($columns)) {
343
            return $select . ' *';
344
        }
345
346
        /** @psalm-var array<array-key, ExpressionInterface|string> $columns */
347
        foreach ($columns as $i => $column) {
348
            if ($column instanceof ExpressionInterface) {
349
                if (is_int($i)) {
350
                    $columns[$i] = $this->buildExpression($column, $params);
351
                } else {
352
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS '
353
                        . $this->quoter->quoteColumnName($i);
354
                }
355
            } elseif (is_string($i) && $i !== $column) {
356
                if (!str_contains($column, '(')) {
357
                    $column = $this->quoter->quoteColumnName($column);
358
                }
359
                $columns[$i] = "$column AS " . $this->quoter->quoteColumnName($i);
360
            } elseif (!str_contains($column, '(')) {
361
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $column, $matches)) {
362
                    $columns[$i] = $this->quoter->quoteColumnName($matches[1])
363
                        . ' AS ' . $this->quoter->quoteColumnName($matches[2]);
364
                } else {
365
                    $columns[$i] = $this->quoter->quoteColumnName($column);
366
                }
367
            }
368
        }
369
370
        return $select . ' ' . implode(', ', $columns);
371
    }
372
373
    public function buildUnion(array $unions, array &$params): string
374
    {
375
        if (empty($unions)) {
376
            return '';
377
        }
378
379
        $result = '';
380
381
        /** @psalm-var array<array{query:Query|string, all:bool}> $unions */
382
        foreach ($unions as $i => $union) {
383
            $query = $union['query'];
384
            if ($query instanceof QueryInterface) {
385
                [$unions[$i]['query'], $params] = $this->build($query, $params);
386
            }
387
388
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
389
        }
390
391
        return trim($result);
392
    }
393
394
    public function buildWhere(
395
        array|string|ConditionInterface|ExpressionInterface|null $condition,
396
        array &$params = []
397
    ): string {
398
        $where = $this->buildCondition($condition, $params);
399
        return ($where === '') ? '' : ('WHERE ' . $where);
400
    }
401
402
    public function buildWithQueries(array $withs, array &$params): string
403
    {
404
        if (empty($withs)) {
405
            return '';
406
        }
407
408
        $recursive = false;
409
        $result = [];
410
411
        /** @psalm-var array<array-key, array{query:string|Query, alias:string, recursive:bool}> $withs */
412
        foreach ($withs as $with) {
413
            if ($with['recursive']) {
414
                $recursive = true;
415
            }
416
417
            $query = $with['query'];
418
            if ($query instanceof QueryInterface) {
419
                [$with['query'], $params] = $this->build($query, $params);
420
            }
421
422
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
423
        }
424
425
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
426
    }
427
428
    public function createConditionFromArray(array $condition): ConditionInterface
429
    {
430
        /** operator format: operator, operand 1, operand 2, ... */
431
        if (isset($condition[0])) {
432
            $operator = strtoupper((string) array_shift($condition));
433
434
            /** @var string $className */
435
            $className = $this->conditionClasses[$operator] ?? SimpleCondition::class;
436
437
            /** @var ConditionInterface $className */
438
            return $className::fromArrayDefinition($operator, $condition);
439
        }
440
441
        /** hash format: 'column1' => 'value1', 'column2' => 'value2', ... */
442
        return new HashCondition($condition);
443
    }
444
445
    public function getExpressionBuilder(ExpressionInterface $expression): object
446
    {
447
        $className = $expression::class;
448
449
        if (!isset($this->expressionBuilders[$className])) {
450
            throw new InvalidArgumentException(
451
                'Expression of class ' . $className . ' can not be built in ' . static::class
452
            );
453
        }
454
455
        return new $this->expressionBuilders[$className]($this->queryBuilder);
456
    }
457
458
    public function selectExists(string $rawSql): string
459
    {
460
        return 'SELECT EXISTS(' . $rawSql . ')';
461
    }
462
463
    public function setConditionClasses(array $classes): void
464
    {
465
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
466
    }
467
468
    public function setExpressionBuilders(array $builders): void
469
    {
470
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
471
    }
472
473
    /**
474
     * @param string the separator between different fragments of a SQL statement.
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\QueryBuilder\the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
475
     *
476
     * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement.
477
     */
478
    public function setSeparator(string $separator): void
479
    {
480
        $this->separator = $separator;
481
    }
482
483
    /**
484
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
485
     * for the query builder.
486
     *
487
     * See {@see conditionClasses} docs for details.
488
     */
489
    protected function defaultConditionClasses(): array
490
    {
491
        return [
492
            'NOT' => Condition\NotCondition::class,
493
            'AND' => Condition\AndCondition::class,
494
            'OR' => Condition\OrCondition::class,
495
            'BETWEEN' => Condition\BetweenCondition::class,
496
            'NOT BETWEEN' => Condition\BetweenCondition::class,
497
            'IN' => Condition\InCondition::class,
498
            'NOT IN' => Condition\InCondition::class,
499
            'LIKE' => Condition\LikeCondition::class,
500
            'NOT LIKE' => Condition\LikeCondition::class,
501
            'OR LIKE' => Condition\LikeCondition::class,
502
            'OR NOT LIKE' => Condition\LikeCondition::class,
503
            'EXISTS' => Condition\ExistsCondition::class,
504
            'NOT EXISTS' => Condition\ExistsCondition::class,
505
        ];
506
    }
507
508
    /**
509
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
510
     * expression builders for this query builder.
511
     *
512
     * See {@see expressionBuilders} docs for details.
513
     *
514
     * @psalm-return array<string, class-string<ExpressionBuilderInterface>>
515
     */
516
    protected function defaultExpressionBuilders(): array
517
    {
518
        return [
519
            Query::class => QueryExpressionBuilder::class,
520
            Param::class => ParamBuilder::class,
521
            Expression::class => ExpressionBuilder::class,
522
            Condition\AbstractConjunctionCondition::class => Condition\Builder\ConjunctionConditionBuilder::class,
523
            Condition\NotCondition::class => Condition\Builder\NotConditionBuilder::class,
524
            Condition\AndCondition::class => Condition\Builder\ConjunctionConditionBuilder::class,
525
            Condition\OrCondition::class => Condition\Builder\ConjunctionConditionBuilder::class,
526
            Condition\BetweenCondition::class => Condition\Builder\BetweenConditionBuilder::class,
527
            Condition\InCondition::class => Condition\Builder\InConditionBuilder::class,
528
            Condition\LikeCondition::class => Condition\Builder\LikeConditionBuilder::class,
529
            Condition\ExistsCondition::class => Condition\Builder\ExistsConditionBuilder::class,
530
            Condition\SimpleCondition::class => Condition\Builder\SimpleConditionBuilder::class,
531
            Condition\HashCondition::class => Condition\Builder\HashConditionBuilder::class,
532
            Condition\BetweenColumnsCondition::class => Condition\Builder\BetweenColumnsConditionBuilder::class,
533
        ];
534
    }
535
536
    /**
537
     * Extracts table alias if there is one or returns false.
538
     *
539
     * @psalm-return string[]|bool
540
     */
541
    protected function extractAlias(string $table): array|bool
542
    {
543
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
544
            return $matches;
545
        }
546
547
        return false;
548
    }
549
550
    /**
551
     * Checks to see if the given limit is effective.
552
     *
553
     * @param mixed $limit the given limit.
554
     *
555
     * @return bool whether the limit is effective.
556
     */
557
    protected function hasLimit(mixed $limit): bool
558
    {
559
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
560
    }
561
562
    /**
563
     * Checks to see if the given offset is effective.
564
     *
565
     * @param mixed $offset the given offset.
566
     *
567
     * @return bool whether the offset is effective.
568
     */
569
    protected function hasOffset(mixed $offset): bool
570
    {
571
        return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0');
572
    }
573
574
    /**
575
     * Quotes table names passed.
576
     *
577
     * @throws Exception|InvalidConfigException|NotSupportedException
578
     */
579
    private function quoteTableNames(array $tables, array &$params): array
580
    {
581
        /** @psalm-var array<array-key, array|QueryInterface|string> $tables */
582
        foreach ($tables as $i => $table) {
583
            if ($table instanceof QueryInterface) {
584
                [$sql, $params] = $this->build($table, $params);
585
                $tables[$i] = "($sql) " . $this->quoter->quoteTableName((string) $i);
586
            } elseif (is_string($table) && is_string($i)) {
587
                if (!str_contains($table, '(')) {
588
                    $table = $this->quoter->quoteTableName($table);
589
                }
590
                $tables[$i] = "$table " . $this->quoter->quoteTableName($i);
591
            } elseif ($table instanceof ExpressionInterface && is_string($i)) {
592
                $table = $this->buildExpression($table, $params);
593
                $tables[$i] = "$table " . $this->quoter->quoteTableName($i);
594
            } elseif (is_string($table) && !str_contains($table, '(')) {
595
                $tableWithAlias = $this->extractAlias($table);
596
                if (is_array($tableWithAlias)) { // with alias
597
                    $tables[$i] = $this->quoter->quoteTableName($tableWithAlias[1]) . ' '
598
                        . $this->quoter->quoteTableName($tableWithAlias[2]);
599
                } else {
600
                    $tables[$i] = $this->quoter->quoteTableName($table);
601
                }
602
            }
603
        }
604
605
        return $tables;
606
    }
607
}
608