Passed
Pull Request — master (#19761)
by
unknown
12:56 queued 03:52
created

BaseQuery::column()   C

Complexity

Conditions 12
Paths 29

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 24
c 1
b 0
f 0
nc 29
nop 1
dl 0
loc 38
ccs 22
cts 22
cp 1
crap 12
rs 6.9666

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidArgumentException;
13
use yii\helpers\ArrayHelper;
14
use yii\base\InvalidConfigException;
15
16
/**
17
 * BaseQuery provides concrete implementation for [[Query]].
18
 *
19
 * Do not use BaseQuery. Use [[Query]] instead.
20
 *
21
 * @property-read string[] $tablesUsedInFrom Table names indexed by aliases.
22
 *
23
 * @author Qiang Xue <[email protected]>
24
 * @author Carsten Brandt <[email protected]>
25
 * @since 2.0
26
 */
27
class BaseQuery extends Component implements QueryInterface, ExpressionInterface
28
{
29
    use QueryTrait;
30
31
    /**
32
     * @var array|null the columns being selected. For example, `['id', 'name']`.
33
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
34
     * @see select()
35
     */
36
    public $select;
37
    /**
38
     * @var string|null additional option that should be appended to the 'SELECT' keyword. For example,
39
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
40
     */
41
    public $selectOption;
42
    /**
43
     * @var bool whether to select distinct rows of data only. If this is set true,
44
     * the SELECT clause would be changed to SELECT DISTINCT.
45
     */
46
    public $distinct = false;
47
    /**
48
     * @var array|null the table(s) to be selected from. For example, `['user', 'post']`.
49
     * This is used to construct the FROM clause in a SQL statement.
50
     * @see from()
51
     */
52
    public $from;
53
    /**
54
     * @var array|null how to group the query results. For example, `['company', 'department']`.
55
     * This is used to construct the GROUP BY clause in a SQL statement.
56
     */
57
    public $groupBy;
58
    /**
59
     * @var array|null how to join with other tables. Each array element represents the specification
60
     * of one join which has the following structure:
61
     *
62
     * ```php
63
     * [$joinType, $tableName, $joinCondition]
64
     * ```
65
     *
66
     * For example,
67
     *
68
     * ```php
69
     * [
70
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
71
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
72
     * ]
73
     * ```
74
     */
75
    public $join;
76
    /**
77
     * @var string|array|ExpressionInterface|null the condition to be applied in the GROUP BY clause.
78
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
79
     */
80
    public $having;
81
    /**
82
     * @var array|null this is used to construct the UNION clause(s) in a SQL statement.
83
     * Each array element is an array of the following structure:
84
     *
85
     * - `query`: either a string or a [[Query]] object representing a query
86
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
87
     */
88
    public $union;
89
    /**
90
     * @var array|null this is used to construct the WITH section in a SQL query.
91
     * Each array element is an array of the following structure:
92
     *
93
     * - `query`: either a string or a [[Query]] object representing a query
94
     * - `alias`: string, alias of query for further usage
95
     * - `recursive`: boolean, whether it should be `WITH RECURSIVE` or `WITH`
96
     * @see withQuery()
97
     * @since 2.0.35
98
     */
99
    public $withQueries;
100
    /**
101
     * @var array|null list of query parameter values indexed by parameter placeholders.
102
     * For example, `[':name' => 'Dan', ':age' => 31]`.
103
     */
104
    public $params = [];
105
    /**
106
     * @var int|bool|null the default number of seconds that query results can remain valid in cache.
107
     * Use 0 to indicate that the cached data will never expire.
108
     * Use a negative number to indicate that query cache should not be used.
109
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
110
     * @see cache()
111
     * @since 2.0.14
112
     */
113
    public $queryCacheDuration;
114
    /**
115
     * @var \yii\caching\Dependency|null the dependency to be associated with the cached query result for this query
116
     * @see cache()
117
     * @since 2.0.14
118
     */
119
    public $queryCacheDependency;
120
121
122
    /**
123
     * Creates a DB command that can be used to execute this query.
124
     * @param Connection|null $db the database connection used to generate the SQL statement.
125
     * If this parameter is not given, the `db` application component will be used.
126
     * @return Command the created DB command instance.
127
     */
128 393
    public function createCommand($db = null)
129
    {
130 393
        if ($db === null) {
131 43
            $db = Yii::$app->getDb();
132
        }
133 393
        list($sql, $params) = $db->getQueryBuilder()->build($this);
134
135 393
        $command = $db->createCommand($sql, $params);
136 393
        $this->setCommandCache($command);
137
138 393
        return $command;
139
    }
140
141
    /**
142
     * Prepares for building SQL.
143
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
144
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
145
     * @param QueryBuilder $builder
146
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
147
     */
148 897
    public function prepare($builder)
0 ignored issues
show
Unused Code introduced by
The parameter $builder is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

148
    public function prepare(/** @scrutinizer ignore-unused */ $builder)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
    {
150 897
        return $this;
151
    }
152
153
    /**
154
     * Starts a batch query.
155
     *
156
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
157
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
158
     * and can be traversed to retrieve the data in batches.
159
     *
160
     * For example,
161
     *
162
     * ```php
163
     * $query = (new Query)->from('user');
164
     * foreach ($query->batch() as $rows) {
165
     *     // $rows is an array of 100 or fewer rows from user table
166
     * }
167
     * ```
168
     *
169
     * @param int $batchSize the number of records to be fetched in each batch.
170
     * @param Connection|null $db the database connection. If not set, the "db" application component will be used.
171
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
172
     * and can be traversed to retrieve the data in batches.
173
     */
174 12
    public function batch($batchSize = 100, $db = null)
175
    {
176 12
        return Yii::createObject([
177 12
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

177
            'class' => /** @scrutinizer ignore-deprecated */ BatchQueryResult::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
178 12
            'query' => $this,
179 12
            'batchSize' => $batchSize,
180 12
            'db' => $db,
181
            'each' => false,
182
        ]);
183
    }
184
185
    /**
186
     * Starts a batch query and retrieves data row by row.
187
     *
188
     * This method is similar to [[batch()]] except that in each iteration of the result,
189
     * only one row of data is returned. For example,
190
     *
191
     * ```php
192
     * $query = (new Query)->from('user');
193
     * foreach ($query->each() as $row) {
194
     * }
195
     * ```
196
     *
197
     * @param int $batchSize the number of records to be fetched in each batch.
198
     * @param Connection|null $db the database connection. If not set, the "db" application component will be used.
199
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
200
     * and can be traversed to retrieve the data in batches.
201
     */
202 3
    public function each($batchSize = 100, $db = null)
203
    {
204 3
        return Yii::createObject([
205 3
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

205
            'class' => /** @scrutinizer ignore-deprecated */ BatchQueryResult::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
206 3
            'query' => $this,
207 3
            'batchSize' => $batchSize,
208 3
            'db' => $db,
209
            'each' => true,
210
        ]);
211
    }
212
213
    /**
214
     * Executes the query and returns all results as an array.
215
     * @param Connection|null $db the database connection used to generate the SQL statement.
216
     * If this parameter is not given, the `db` application component will be used.
217
     * @return array the query results. If the query results in nothing, an empty array will be returned.
218
     */
219 494
    public function all($db = null)
220
    {
221 494
        if ($this->emulateExecution) {
222 12
            return [];
223
        }
224
225 488
        $rows = $this->createCommand($db)->queryAll();
226
227 488
        return $this->populate($rows);
228
    }
229
230
    /**
231
     * Converts the raw query results into the format as specified by this query.
232
     * This method is internally used to convert the data fetched from database
233
     * into the format as required by this query.
234
     * @param array $rows the raw query result from database
235
     * @return array the converted query result
236
     */
237 637
    public function populate($rows)
238
    {
239 637
        if ($this->indexBy === null) {
240 628
            return $rows;
241
        }
242 27
        $result = [];
243 27
        foreach ($rows as $row) {
244 27
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
245
        }
246
247 27
        return $result;
248
    }
249
250
    /**
251
     * Executes the query and returns a single row of result.
252
     * @param Connection|null $db the database connection used to generate the SQL statement.
253
     * If this parameter is not given, the `db` application component will be used.
254
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
255
     * results in nothing.
256
     */
257 486
    public function one($db = null)
258
    {
259 486
        if ($this->emulateExecution) {
260 6
            return false;
261
        }
262
263 480
        return $this->createCommand($db)->queryOne();
264
    }
265
266
    /**
267
     * Returns the query result as a scalar value.
268
     * The value returned will be the first column in the first row of the query results.
269
     * @param Connection|null $db the database connection used to generate the SQL statement.
270
     * If this parameter is not given, the `db` application component will be used.
271
     * @return string|int|null|false the value of the first column in the first row of the query result.
272
     * False is returned if the query result is empty.
273
     */
274 36
    public function scalar($db = null)
275
    {
276 36
        if ($this->emulateExecution) {
277 6
            return null;
278
        }
279
280 30
        return $this->createCommand($db)->queryScalar();
281
    }
282
283
    /**
284
     * Executes the query and returns the first column of the result.
285
     * @param Connection|null $db the database connection used to generate the SQL statement.
286
     * If this parameter is not given, the `db` application component will be used.
287
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
288
     */
289 82
    public function column($db = null)
290
    {
291 82
        if ($this->emulateExecution) {
292 6
            return [];
293
        }
294
295 76
        if ($this->indexBy === null) {
296 70
            return $this->createCommand($db)->queryColumn();
297
        }
298
299 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
300 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
301 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
302
            } else {
303 3
                $this->select[] = $this->indexBy;
304
            }
305
        }
306 9
        $rows = $this->createCommand($db)->queryAll();
307 9
        $results = [];
308 9
        $column = null;
309 9
        if (is_string($this->indexBy)) {
310 9
            if (($dotPos = strpos($this->indexBy, '.')) === false) {
311 9
                $column = $this->indexBy;
312
            } else {
313 3
                $column = substr($this->indexBy, $dotPos + 1);
314
            }
315
        }
316 9
        foreach ($rows as $row) {
317 9
            $value = reset($row);
318
319 9
            if ($this->indexBy instanceof \Closure) {
320 3
                $results[call_user_func($this->indexBy, $row)] = $value;
321
            } else {
322 9
                $results[$row[$column]] = $value;
323
            }
324
        }
325
326 9
        return $results;
327
    }
328
329
    /**
330
     * Returns the number of records.
331
     * @param string $q the COUNT expression. Defaults to '*'.
332
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
333
     * @param Connection|null $db the database connection used to generate the SQL statement.
334
     * If this parameter is not given (or null), the `db` application component will be used.
335
     * @return int|string|null number of records. The result may be a string depending on the
336
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
337
     */
338 96
    public function count($q = '*', $db = null)
339
    {
340 96
        if ($this->emulateExecution) {
341 6
            return 0;
342
        }
343
344 96
        return $this->queryScalar("COUNT($q)", $db);
345
    }
346
347
    /**
348
     * Returns the sum of the specified column values.
349
     * @param string $q the column name or expression.
350
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
351
     * @param Connection|null $db the database connection used to generate the SQL statement.
352
     * If this parameter is not given, the `db` application component will be used.
353
     * @return mixed the sum of the specified column values.
354
     */
355 9
    public function sum($q, $db = null)
356
    {
357 9
        if ($this->emulateExecution) {
358 6
            return 0;
359
        }
360
361 3
        return $this->queryScalar("SUM($q)", $db);
362
    }
363
364
    /**
365
     * Returns the average of the specified column values.
366
     * @param string $q the column name or expression.
367
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
368
     * @param Connection|null $db the database connection used to generate the SQL statement.
369
     * If this parameter is not given, the `db` application component will be used.
370
     * @return mixed the average of the specified column values.
371
     */
372 9
    public function average($q, $db = null)
373
    {
374 9
        if ($this->emulateExecution) {
375 6
            return 0;
376
        }
377
378 3
        return $this->queryScalar("AVG($q)", $db);
379
    }
380
381
    /**
382
     * Returns the minimum of the specified column values.
383
     * @param string $q the column name or expression.
384
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
385
     * @param Connection|null $db the database connection used to generate the SQL statement.
386
     * If this parameter is not given, the `db` application component will be used.
387
     * @return mixed the minimum of the specified column values.
388
     */
389 9
    public function min($q, $db = null)
390
    {
391 9
        return $this->queryScalar("MIN($q)", $db);
392
    }
393
394
    /**
395
     * Returns the maximum of the specified column values.
396
     * @param string $q the column name or expression.
397
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
398
     * @param Connection|null $db the database connection used to generate the SQL statement.
399
     * If this parameter is not given, the `db` application component will be used.
400
     * @return mixed the maximum of the specified column values.
401
     */
402 9
    public function max($q, $db = null)
403
    {
404 9
        return $this->queryScalar("MAX($q)", $db);
405
    }
406
407
    /**
408
     * Returns a value indicating whether the query result contains any row of data.
409
     * @param Connection|null $db the database connection used to generate the SQL statement.
410
     * If this parameter is not given, the `db` application component will be used.
411
     * @return bool whether the query result contains any row of data.
412
     */
413 89
    public function exists($db = null)
414
    {
415 89
        if ($this->emulateExecution) {
416 6
            return false;
417
        }
418 83
        $command = $this->createCommand($db);
419 83
        $params = $command->params;
420 83
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
421 83
        $command->bindValues($params);
422 83
        return (bool) $command->queryScalar();
423
    }
424
425
    /**
426
     * Queries a scalar value by setting [[select]] first.
427
     * Restores the value of select to make this query reusable.
428
     * @param string|ExpressionInterface $selectExpression
429
     * @param Connection|null $db the database connection used to execute the query.
430
     * @return bool|string|null
431
     * @throws \Throwable if can't create command
432
     */
433 96
    protected function queryScalar($selectExpression, $db)
434
    {
435 96
        if ($this->emulateExecution) {
436 6
            return null;
437
        }
438
439
        if (
440 96
            !$this->distinct
441 96
            && empty($this->groupBy)
442 96
            && empty($this->having)
443 96
            && empty($this->union)
444
        ) {
445 95
            $select = $this->select;
446 95
            $order = $this->orderBy;
447 95
            $limit = $this->limit;
448 95
            $offset = $this->offset;
449
450 95
            $this->select = [$selectExpression];
451 95
            $this->orderBy = null;
452 95
            $this->limit = null;
453 95
            $this->offset = null;
454
455 95
            $e = null;
456
            try {
457 95
                $command = $this->createCommand($db);
458
            } catch (\Exception $e) {
459
                // throw it later (for PHP < 7.0)
460
            } catch (\Throwable $e) {
461
                // throw it later
462
            }
463
464 95
            $this->select = $select;
465 95
            $this->orderBy = $order;
466 95
            $this->limit = $limit;
467 95
            $this->offset = $offset;
468
469 95
            if ($e !== null) {
470
                throw $e;
471
            }
472
473 95
            return $command->queryScalar();
474
        }
475
476 7
        $command = (new self())
477 7
            ->select([$selectExpression])
478 7
            ->from(['c' => $this])
479 7
            ->createCommand($db);
480 7
        $this->setCommandCache($command);
481
482 7
        return $command->queryScalar();
483
    }
484
485
    /**
486
     * Returns table names used in [[from]] indexed by aliases.
487
     * Both aliases and names are enclosed into {{ and }}.
488
     * @return string[] table names indexed by aliases
489
     * @throws \yii\base\InvalidConfigException
490
     * @since 2.0.12
491
     */
492 120
    public function getTablesUsedInFrom()
493
    {
494 120
        if (empty($this->from)) {
495
            return [];
496
        }
497
498 120
        if (is_array($this->from)) {
0 ignored issues
show
introduced by
The condition is_array($this->from) is always true.
Loading history...
499 84
            $tableNames = $this->from;
500 36
        } elseif (is_string($this->from)) {
501 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
502 12
        } elseif ($this->from instanceof Expression) {
503 6
            $tableNames = [$this->from];
504
        } else {
505 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
506
        }
507
508 114
        return $this->cleanUpTableNames($tableNames);
509
    }
510
511
    /**
512
     * Clean up table names and aliases
513
     * Both aliases and names are enclosed into {{ and }}.
514
     * @param array $tableNames non-empty array
515
     * @return string[] table names indexed by aliases
516
     * @since 2.0.14
517
     */
518 287
    protected function cleanUpTableNames($tableNames)
519
    {
520 287
        $cleanedUpTableNames = [];
521 287
        foreach ($tableNames as $alias => $tableName) {
522 287
            if (is_string($tableName) && !is_string($alias)) {
523
                $pattern = <<<PATTERN
524 227
~
525
^
526
\s*
527
(
528
(?:['"`\[]|{{)
529
.*?
530
(?:['"`\]]|}})
531
|
532
\(.*?\)
533
|
534
.*?
535
)
536
(?:
537
(?:
538
    \s+
539
    (?:as)?
540
    \s*
541
)
542
(
543
   (?:['"`\[]|{{)
544
    .*?
545
    (?:['"`\]]|}})
546
    |
547
    .*?
548
)
549
)?
550
\s*
551
$
552
~iux
553
PATTERN;
554 227
                if (preg_match($pattern, $tableName, $matches)) {
555 227
                    if (isset($matches[2])) {
556 18
                        list(, $tableName, $alias) = $matches;
557
                    } else {
558 221
                        $tableName = $alias = $matches[1];
559
                    }
560
                }
561
            }
562
563
564 287
            if ($tableName instanceof Expression) {
565 12
                if (!is_string($alias)) {
566 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
567
                }
568 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
569 275
            } elseif ($tableName instanceof self) {
570 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
571
            } else {
572 269
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
573
            }
574
        }
575
576 281
        return $cleanedUpTableNames;
577
    }
578
579
    /**
580
     * Ensures name is wrapped with {{ and }}
581
     * @param string $name
582
     * @return string
583
     */
584 281
    private function ensureNameQuoted($name)
585
    {
586 281
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
587 281
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
588 269
            return '{{' . $name . '}}';
589
        }
590
591 30
        return $name;
592
    }
593
594
    /**
595
     * Sets the SELECT part of the query.
596
     * @param string|array|ExpressionInterface $columns the columns to be selected.
597
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
598
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
599
     * The method will automatically quote the column names unless a column contains some parenthesis
600
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
601
     * an [[ExpressionInterface]] object.
602
     *
603
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
604
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
605
     *
606
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
607
     * does not need alias, do not use a string key).
608
     *
609
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
610
     * as a `Query` instance representing the sub-query.
611
     *
612
     * @param string|null $option additional option that should be appended to the 'SELECT' keyword. For example,
613
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
614
     * @return $this the query object itself
615
     */
616 432
    public function select($columns, $option = null)
617
    {
618 432
        $this->select = $this->normalizeSelect($columns);
619 432
        $this->selectOption = $option;
620 432
        return $this;
621
    }
622
623
    /**
624
     * Add more columns to the SELECT part of the query.
625
     *
626
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
627
     * if you want to select all remaining columns too:
628
     *
629
     * ```php
630
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
631
     * ```
632
     *
633
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
634
     * details about the format of this parameter.
635
     * @return $this the query object itself
636
     * @see select()
637
     */
638 9
    public function addSelect($columns)
639
    {
640 9
        if ($this->select === null) {
641 3
            return $this->select($columns);
642
        }
643 9
        if (!is_array($this->select)) {
0 ignored issues
show
introduced by
The condition is_array($this->select) is always true.
Loading history...
644
            $this->select = $this->normalizeSelect($this->select);
645
        }
646 9
        $this->select = array_merge($this->select, $this->normalizeSelect($columns));
647
648 9
        return $this;
649
    }
650
651
    /**
652
     * Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]].
653
     *
654
     * @param string|array|ExpressionInterface $columns
655
     * @return array
656
     * @since 2.0.21
657
     */
658 432
    protected function normalizeSelect($columns)
659
    {
660 432
        if ($columns instanceof ExpressionInterface) {
661 3
            $columns = [$columns];
662 432
        } elseif (!is_array($columns)) {
663 121
            $columns = preg_split('/\s*,\s*/', trim((string)$columns), -1, PREG_SPLIT_NO_EMPTY);
664
        }
665 432
        $select = [];
666 432
        foreach ($columns as $columnAlias => $columnDefinition) {
667 429
            if (is_string($columnAlias)) {
668
                // Already in the normalized format, good for them
669 55
                $select[$columnAlias] = $columnDefinition;
670 55
                continue;
671
            }
672 424
            if (is_string($columnDefinition)) {
673
                if (
674 421
                    preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
675 421
                    !preg_match('/^\d+$/', $matches[2]) &&
676 421
                    strpos($matches[2], '.') === false
677
                ) {
678
                    // Using "columnName as alias" or "columnName alias" syntax
679 21
                    $select[$matches[2]] = $matches[1];
680 21
                    continue;
681
                }
682 415
                if (strpos($columnDefinition, '(') === false) {
683
                    // Normal column name, just alias it to itself to ensure it's not selected twice
684 405
                    $select[$columnDefinition] = $columnDefinition;
685 405
                    continue;
686
                }
687
            }
688
            // Either a string calling a function, DB expression, or sub-query
689 36
            $select[] = $columnDefinition;
690
        }
691 432
        return $select;
692
    }
693
694
    /**
695
     * Returns unique column names excluding duplicates.
696
     * Columns to be removed:
697
     * - if column definition already present in SELECT part with same alias
698
     * - if column definition without alias already present in SELECT part without alias too
699
     * @param array $columns the columns to be merged to the select.
700
     * @since 2.0.14
701
     * @deprecated in 2.0.21
702
     */
703
    protected function getUniqueColumns($columns)
704
    {
705
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
0 ignored issues
show
Deprecated Code introduced by
The function yii\db\BaseQuery::getUnaliasedColumnsFromSelect() has been deprecated: in 2.0.21 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

705
        $unaliasedColumns = /** @scrutinizer ignore-deprecated */ $this->getUnaliasedColumnsFromSelect();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
706
707
        $result = [];
708
        foreach ($columns as $columnAlias => $columnDefinition) {
709
            if (!$columnDefinition instanceof self) {
710
                if (is_string($columnAlias)) {
711
                    $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
712
                    if ($existsInSelect) {
713
                        continue;
714
                    }
715
                } elseif (is_int($columnAlias)) {
716
                    $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
717
                    $existsInResultSet = in_array($columnDefinition, $result, true);
718
                    if ($existsInSelect || $existsInResultSet) {
719
                        continue;
720
                    }
721
                }
722
            }
723
724
            $result[$columnAlias] = $columnDefinition;
725
        }
726
        return $result;
727
    }
728
729
    /**
730
     * @return array List of columns without aliases from SELECT statement.
731
     * @since 2.0.14
732
     * @deprecated in 2.0.21
733
     */
734
    protected function getUnaliasedColumnsFromSelect()
735
    {
736
        $result = [];
737
        if (is_array($this->select)) {
738
            foreach ($this->select as $name => $value) {
739
                if (is_int($name)) {
740
                    $result[] = $value;
741
                }
742
            }
743
        }
744
        return array_unique($result);
745
    }
746
747
    /**
748
     * Sets the value indicating whether to SELECT DISTINCT or not.
749
     * @param bool $value whether to SELECT DISTINCT or not.
750
     * @return $this the query object itself
751
     */
752 9
    public function distinct($value = true)
753
    {
754 9
        $this->distinct = $value;
755 9
        return $this;
756
    }
757
758
    /**
759
     * Sets the FROM part of the query.
760
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
761
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
762
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
763
     * The method will automatically quote the table names unless it contains some parenthesis
764
     * (which means the table is given as a sub-query or DB expression).
765
     *
766
     * When the tables are specified as an array, you may also use the array keys as the table aliases
767
     * (if a table does not need alias, do not use a string key).
768
     *
769
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
770
     * as the alias for the sub-query.
771
     *
772
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
773
     *
774
     * Here are some examples:
775
     *
776
     * ```php
777
     * // SELECT * FROM  `user` `u`, `profile`;
778
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
779
     *
780
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
781
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
782
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
783
     *
784
     * // subquery can also be a string with plain SQL wrapped in parenthesis
785
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
786
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
787
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
788
     * ```
789
     *
790
     * @return $this the query object itself
791
     */
792 490
    public function from($tables)
793
    {
794 490
        if ($tables instanceof ExpressionInterface) {
795 6
            $tables = [$tables];
796
        }
797 490
        if (is_string($tables)) {
798 434
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
799
        }
800 490
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type string. However, the property $from is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
801 490
        return $this;
802
    }
803
804
    /**
805
     * Sets the WHERE part of the query.
806
     *
807
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
808
     * specifying the values to be bound to the query.
809
     *
810
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
811
     *
812
     * {@inheritdoc}
813
     *
814
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
815
     * @param array $params the parameters (name => value) to be bound to the query.
816
     * @return $this the query object itself
817
     * @see andWhere()
818
     * @see orWhere()
819
     * @see QueryInterface::where()
820
     */
821 878
    public function where($condition, $params = [])
822
    {
823 878
        $this->where = $condition;
824 878
        $this->addParams($params);
825 878
        return $this;
826
    }
827
828
    /**
829
     * Adds an additional WHERE condition to the existing one.
830
     * The new condition and the existing one will be joined using the `AND` operator.
831
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
832
     * on how to specify this parameter.
833
     * @param array $params the parameters (name => value) to be bound to the query.
834
     * @return $this the query object itself
835
     * @see where()
836
     * @see orWhere()
837
     */
838 456
    public function andWhere($condition, $params = [])
839
    {
840 456
        if ($this->where === null) {
841 393
            $this->where = $condition;
842 135
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
843 43
            $this->where[] = $condition;
844
        } else {
845 135
            $this->where = ['and', $this->where, $condition];
846
        }
847 456
        $this->addParams($params);
848 456
        return $this;
849
    }
850
851
    /**
852
     * Adds an additional WHERE condition to the existing one.
853
     * The new condition and the existing one will be joined using the `OR` operator.
854
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
855
     * on how to specify this parameter.
856
     * @param array $params the parameters (name => value) to be bound to the query.
857
     * @return $this the query object itself
858
     * @see where()
859
     * @see andWhere()
860
     */
861 8
    public function orWhere($condition, $params = [])
862
    {
863 8
        if ($this->where === null) {
864
            $this->where = $condition;
865
        } else {
866 8
            $this->where = ['or', $this->where, $condition];
867
        }
868 8
        $this->addParams($params);
869 8
        return $this;
870
    }
871
872
    /**
873
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
874
     *
875
     * It adds an additional WHERE condition for the given field and determines the comparison operator
876
     * based on the first few characters of the given value.
877
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
878
     * The new condition and the existing one will be joined using the `AND` operator.
879
     *
880
     * The comparison operator is intelligently determined based on the first few characters in the given value.
881
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
882
     *
883
     * - `<`: the column must be less than the given value.
884
     * - `>`: the column must be greater than the given value.
885
     * - `<=`: the column must be less than or equal to the given value.
886
     * - `>=`: the column must be greater than or equal to the given value.
887
     * - `<>`: the column must not be the same as the given value.
888
     * - `=`: the column must be equal to the given value.
889
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
890
     *
891
     * @param string $name the column name.
892
     * @param string $value the column value optionally prepended with the comparison operator.
893
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
894
     * Defaults to `=`, performing an exact match.
895
     * @return $this The query object itself
896
     * @since 2.0.8
897
     */
898 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
899
    {
900 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', (string)$value, $matches)) {
901 3
            $operator = $matches[1];
902 3
            $value = substr($value, strlen($operator));
903
        } else {
904 3
            $operator = $defaultOperator;
905
        }
906
907 3
        return $this->andFilterWhere([$operator, $name, $value]);
908
    }
909
910
    /**
911
     * Appends a JOIN part to the query.
912
     * The first parameter specifies what type of join it is.
913
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
914
     * @param string|array $table the table or sub-query to be joined.
915
     *
916
     * Use a string to represent the name of the table to be joined.
917
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
918
     * The method will automatically quote the table name unless it contains some parenthesis
919
     * (which means the table is given as a sub-query or DB expression).
920
     *
921
     * You may also specify the table as an array with one element, using the array key as the table alias
922
     * (e.g. ['u' => 'user']).
923
     *
924
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
925
     * representing the sub-query, and the corresponding key representing the alias.
926
     *
927
     * @param string|array $on the join condition that should appear in the ON part.
928
     * Please refer to [[where()]] on how to specify this parameter.
929
     *
930
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
931
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
932
     * match the `post.author_id` column value against the string `'user.id'`.
933
     * It is recommended to use the string syntax here which is more suited for a join:
934
     *
935
     * ```php
936
     * 'post.author_id = user.id'
937
     * ```
938
     *
939
     * @param array $params the parameters (name => value) to be bound to the query.
940
     * @return $this the query object itself
941
     */
942 90
    public function join($type, $table, $on = '', $params = [])
943
    {
944 90
        $this->join[] = [$type, $table, $on];
945 90
        return $this->addParams($params);
946
    }
947
948
    /**
949
     * Appends an INNER JOIN part to the query.
950
     * @param string|array $table the table or sub-query to be joined.
951
     *
952
     * Use a string to represent the name of the table to be joined.
953
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
954
     * The method will automatically quote the table name unless it contains some parenthesis
955
     * (which means the table is given as a sub-query or DB expression).
956
     *
957
     * You may also specify the table as an array with one element, using the array key as the table alias
958
     * (e.g. ['u' => 'user']).
959
     *
960
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
961
     * representing the sub-query, and the corresponding key representing the alias.
962
     *
963
     * @param string|array $on the join condition that should appear in the ON part.
964
     * Please refer to [[join()]] on how to specify this parameter.
965
     * @param array $params the parameters (name => value) to be bound to the query.
966
     * @return $this the query object itself
967
     */
968 6
    public function innerJoin($table, $on = '', $params = [])
969
    {
970 6
        $this->join[] = ['INNER JOIN', $table, $on];
971 6
        return $this->addParams($params);
972
    }
973
974
    /**
975
     * Appends a LEFT OUTER JOIN part to the query.
976
     * @param string|array $table the table or sub-query to be joined.
977
     *
978
     * Use a string to represent the name of the table to be joined.
979
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
980
     * The method will automatically quote the table name unless it contains some parenthesis
981
     * (which means the table is given as a sub-query or DB expression).
982
     *
983
     * You may also specify the table as an array with one element, using the array key as the table alias
984
     * (e.g. ['u' => 'user']).
985
     *
986
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
987
     * representing the sub-query, and the corresponding key representing the alias.
988
     *
989
     * @param string|array $on the join condition that should appear in the ON part.
990
     * Please refer to [[join()]] on how to specify this parameter.
991
     * @param array $params the parameters (name => value) to be bound to the query
992
     * @return $this the query object itself
993
     */
994 3
    public function leftJoin($table, $on = '', $params = [])
995
    {
996 3
        $this->join[] = ['LEFT JOIN', $table, $on];
997 3
        return $this->addParams($params);
998
    }
999
1000
    /**
1001
     * Appends a RIGHT OUTER JOIN part to the query.
1002
     * @param string|array $table the table or sub-query to be joined.
1003
     *
1004
     * Use a string to represent the name of the table to be joined.
1005
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
1006
     * The method will automatically quote the table name unless it contains some parenthesis
1007
     * (which means the table is given as a sub-query or DB expression).
1008
     *
1009
     * You may also specify the table as an array with one element, using the array key as the table alias
1010
     * (e.g. ['u' => 'user']).
1011
     *
1012
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
1013
     * representing the sub-query, and the corresponding key representing the alias.
1014
     *
1015
     * @param string|array $on the join condition that should appear in the ON part.
1016
     * Please refer to [[join()]] on how to specify this parameter.
1017
     * @param array $params the parameters (name => value) to be bound to the query
1018
     * @return $this the query object itself
1019
     */
1020
    public function rightJoin($table, $on = '', $params = [])
1021
    {
1022
        $this->join[] = ['RIGHT JOIN', $table, $on];
1023
        return $this->addParams($params);
1024
    }
1025
1026
    /**
1027
     * Sets the GROUP BY part of the query.
1028
     * @param string|array|ExpressionInterface $columns the columns to be grouped by.
1029
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1030
     * The method will automatically quote the column names unless a column contains some parenthesis
1031
     * (which means the column contains a DB expression).
1032
     *
1033
     * Note that if your group-by is an expression containing commas, you should always use an array
1034
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1035
     * the group-by columns.
1036
     *
1037
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1038
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1039
     * @return $this the query object itself
1040
     * @see addGroupBy()
1041
     */
1042 29
    public function groupBy($columns)
1043
    {
1044 29
        if ($columns instanceof ExpressionInterface) {
1045 3
            $columns = [$columns];
1046 29
        } elseif (!is_array($columns)) {
1047 29
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1048
        }
1049 29
        $this->groupBy = $columns;
1050 29
        return $this;
1051
    }
1052
1053
    /**
1054
     * Adds additional group-by columns to the existing ones.
1055
     * @param string|array|ExpressionInterface $columns additional columns to be grouped by.
1056
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1057
     * The method will automatically quote the column names unless a column contains some parenthesis
1058
     * (which means the column contains a DB expression).
1059
     *
1060
     * Note that if your group-by is an expression containing commas, you should always use an array
1061
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1062
     * the group-by columns.
1063
     *
1064
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1065
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1066
     * @return $this the query object itself
1067
     * @see groupBy()
1068
     */
1069 3
    public function addGroupBy($columns)
1070
    {
1071 3
        if ($columns instanceof ExpressionInterface) {
1072
            $columns = [$columns];
1073 3
        } elseif (!is_array($columns)) {
1074 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1075
        }
1076 3
        if ($this->groupBy === null) {
1077
            $this->groupBy = $columns;
1078
        } else {
1079 3
            $this->groupBy = array_merge($this->groupBy, $columns);
1080
        }
1081
1082 3
        return $this;
1083
    }
1084
1085
    /**
1086
     * Sets the HAVING part of the query.
1087
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1088
     * Please refer to [[where()]] on how to specify this parameter.
1089
     * @param array $params the parameters (name => value) to be bound to the query.
1090
     * @return $this the query object itself
1091
     * @see andHaving()
1092
     * @see orHaving()
1093
     */
1094 13
    public function having($condition, $params = [])
1095
    {
1096 13
        $this->having = $condition;
1097 13
        $this->addParams($params);
1098 13
        return $this;
1099
    }
1100
1101
    /**
1102
     * Adds an additional HAVING condition to the existing one.
1103
     * The new condition and the existing one will be joined using the `AND` operator.
1104
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1105
     * on how to specify this parameter.
1106
     * @param array $params the parameters (name => value) to be bound to the query.
1107
     * @return $this the query object itself
1108
     * @see having()
1109
     * @see orHaving()
1110
     */
1111 3
    public function andHaving($condition, $params = [])
1112
    {
1113 3
        if ($this->having === null) {
1114
            $this->having = $condition;
1115
        } else {
1116 3
            $this->having = ['and', $this->having, $condition];
1117
        }
1118 3
        $this->addParams($params);
1119 3
        return $this;
1120
    }
1121
1122
    /**
1123
     * Adds an additional HAVING condition to the existing one.
1124
     * The new condition and the existing one will be joined using the `OR` operator.
1125
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1126
     * on how to specify this parameter.
1127
     * @param array $params the parameters (name => value) to be bound to the query.
1128
     * @return $this the query object itself
1129
     * @see having()
1130
     * @see andHaving()
1131
     */
1132 3
    public function orHaving($condition, $params = [])
1133
    {
1134 3
        if ($this->having === null) {
1135
            $this->having = $condition;
1136
        } else {
1137 3
            $this->having = ['or', $this->having, $condition];
1138
        }
1139 3
        $this->addParams($params);
1140 3
        return $this;
1141
    }
1142
1143
    /**
1144
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1145
     *
1146
     * This method is similar to [[having()]]. The main difference is that this method will
1147
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1148
     * for building query conditions based on filter values entered by users.
1149
     *
1150
     * The following code shows the difference between this method and [[having()]]:
1151
     *
1152
     * ```php
1153
     * // HAVING `age`=:age
1154
     * $query->filterHaving(['name' => null, 'age' => 20]);
1155
     * // HAVING `age`=:age
1156
     * $query->having(['age' => 20]);
1157
     * // HAVING `name` IS NULL AND `age`=:age
1158
     * $query->having(['name' => null, 'age' => 20]);
1159
     * ```
1160
     *
1161
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1162
     *
1163
     * @param array $condition the conditions that should be put in the HAVING part.
1164
     * See [[having()]] on how to specify this parameter.
1165
     * @return $this the query object itself
1166
     * @see having()
1167
     * @see andFilterHaving()
1168
     * @see orFilterHaving()
1169
     * @since 2.0.11
1170
     */
1171 6
    public function filterHaving(array $condition)
1172
    {
1173 6
        $condition = $this->filterCondition($condition);
1174 6
        if ($condition !== []) {
1175 6
            $this->having($condition);
1176
        }
1177
1178 6
        return $this;
1179
    }
1180
1181
    /**
1182
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1183
     * The new condition and the existing one will be joined using the `AND` operator.
1184
     *
1185
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1186
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1187
     * for building query conditions based on filter values entered by users.
1188
     *
1189
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1190
     * on how to specify this parameter.
1191
     * @return $this the query object itself
1192
     * @see filterHaving()
1193
     * @see orFilterHaving()
1194
     * @since 2.0.11
1195
     */
1196 6
    public function andFilterHaving(array $condition)
1197
    {
1198 6
        $condition = $this->filterCondition($condition);
1199 6
        if ($condition !== []) {
1200
            $this->andHaving($condition);
1201
        }
1202
1203 6
        return $this;
1204
    }
1205
1206
    /**
1207
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1208
     * The new condition and the existing one will be joined using the `OR` operator.
1209
     *
1210
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1211
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1212
     * for building query conditions based on filter values entered by users.
1213
     *
1214
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1215
     * on how to specify this parameter.
1216
     * @return $this the query object itself
1217
     * @see filterHaving()
1218
     * @see andFilterHaving()
1219
     * @since 2.0.11
1220
     */
1221 6
    public function orFilterHaving(array $condition)
1222
    {
1223 6
        $condition = $this->filterCondition($condition);
1224 6
        if ($condition !== []) {
1225
            $this->orHaving($condition);
1226
        }
1227
1228 6
        return $this;
1229
    }
1230
1231
    /**
1232
     * Appends a SQL statement using UNION operator.
1233
     * @param string|Query $sql the SQL statement to be appended using UNION
1234
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1235
     * @return $this the query object itself
1236
     */
1237 16
    public function union($sql, $all = false)
1238
    {
1239 16
        $this->union[] = ['query' => $sql, 'all' => $all];
1240 16
        return $this;
1241
    }
1242
1243
    /**
1244
     * Prepends a SQL statement using WITH syntax.
1245
     * @param string|Query $query the SQL statement to be prepended using WITH
1246
     * @param string $alias query alias in WITH construction
1247
     * @param bool $recursive TRUE if using WITH RECURSIVE and FALSE if using WITH
1248
     * @return $this the query object itself
1249
     * @since 2.0.35
1250
     */
1251 9
    public function withQuery($query, $alias, $recursive = false)
1252
    {
1253 9
        $this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive];
1254 9
        return $this;
1255
    }
1256
1257
    /**
1258
     * Sets the parameters to be bound to the query.
1259
     * @param array $params list of query parameter values indexed by parameter placeholders.
1260
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1261
     * @return $this the query object itself
1262
     * @see addParams()
1263
     */
1264 6
    public function params($params)
1265
    {
1266 6
        $this->params = $params;
1267 6
        return $this;
1268
    }
1269
1270
    /**
1271
     * Adds additional parameters to be bound to the query.
1272
     * @param array $params list of query parameter values indexed by parameter placeholders.
1273
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1274
     * @return $this the query object itself
1275
     * @see params()
1276
     */
1277 1226
    public function addParams($params)
1278
    {
1279 1226
        if (!empty($params)) {
1280 90
            if (empty($this->params)) {
1281 90
                $this->params = $params;
1282
            } else {
1283 6
                foreach ($params as $name => $value) {
1284 6
                    if (is_int($name)) {
1285
                        $this->params[] = $value;
1286
                    } else {
1287 6
                        $this->params[$name] = $value;
1288
                    }
1289
                }
1290
            }
1291
        }
1292
1293 1226
        return $this;
1294
    }
1295
1296
    /**
1297
     * Enables query cache for this Query.
1298
     * @param int|true $duration the number of seconds that query results can remain valid in cache.
1299
     * Use 0 to indicate that the cached data will never expire.
1300
     * Use a negative number to indicate that query cache should not be used.
1301
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1302
     * Defaults to `true`.
1303
     * @param \yii\caching\Dependency|null $dependency the cache dependency associated with the cached result.
1304
     * @return $this the Query object itself
1305
     * @since 2.0.14
1306
     */
1307 3
    public function cache($duration = true, $dependency = null)
1308
    {
1309 3
        $this->queryCacheDuration = $duration;
1310 3
        $this->queryCacheDependency = $dependency;
1311 3
        return $this;
1312
    }
1313
1314
    /**
1315
     * Disables query cache for this Query.
1316
     * @return $this the Query object itself
1317
     * @since 2.0.14
1318
     */
1319 32
    public function noCache()
1320
    {
1321 32
        $this->queryCacheDuration = -1;
1322 32
        return $this;
1323
    }
1324
1325
    /**
1326
     * Sets $command cache, if this query has enabled caching.
1327
     *
1328
     * @param Command $command
1329
     * @return Command
1330
     * @since 2.0.14
1331
     */
1332 860
    protected function setCommandCache($command)
1333
    {
1334 860
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1335 32
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1336 32
            $command->cache($duration, $this->queryCacheDependency);
0 ignored issues
show
Bug introduced by
It seems like $duration can also be of type false; however, parameter $duration of yii\db\Command::cache() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1336
            $command->cache(/** @scrutinizer ignore-type */ $duration, $this->queryCacheDependency);
Loading history...
1337
        }
1338
1339 860
        return $command;
1340
    }
1341
1342
    /**
1343
     * Creates a new Query object and copies its property values from an existing one.
1344
     * The properties being copies are the ones to be used by query builders.
1345
     * @param Query $from the source query object
1346
     * @return Query the new Query object
1347
     */
1348 505
    public static function create($from)
1349
    {
1350 505
        return new static([
1351 505
            'where' => $from->where,
1352 505
            'limit' => $from->limit,
1353 505
            'offset' => $from->offset,
1354 505
            'orderBy' => $from->orderBy,
1355 505
            'indexBy' => $from->indexBy,
1356 505
            'select' => $from->select,
1357 505
            'selectOption' => $from->selectOption,
1358 505
            'distinct' => $from->distinct,
1359 505
            'from' => $from->from,
1360 505
            'groupBy' => $from->groupBy,
1361 505
            'join' => $from->join,
1362 505
            'having' => $from->having,
1363 505
            'union' => $from->union,
1364 505
            'params' => $from->params,
1365 505
            'withQueries' => $from->withQueries,
1366
        ]);
1367
    }
1368
1369
    /**
1370
     * Returns the SQL representation of Query
1371
     * @return string
1372
     */
1373
    public function __toString()
1374
    {
1375
        return serialize($this);
1376
    }
1377
}
1378