Completed
Push — 2.1 ( 481970...56545c )
by
unknown
11:50
created

Query::where()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
ccs 4
cts 4
cp 1
cc 1
eloc 4
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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
 * Query represents a SELECT SQL statement in a way that is independent of DBMS.
18
 *
19
 * Query provides a set of methods to facilitate the specification of different clauses
20
 * in a SELECT statement. These methods can be chained together.
21
 *
22
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
23
 * used to perform/execute the DB query against a database.
24
 *
25
 * For example,
26
 *
27
 * ```php
28
 * $query = new Query;
29
 * // compose the query
30
 * $query->select('id, name')
31
 *     ->from('user')
32
 *     ->limit(10);
33
 * // build and execute the query
34
 * $rows = $query->all();
35
 * // alternatively, you can create DB command and execute it
36
 * $command = $query->createCommand();
37
 * // $command->sql returns the actual SQL
38
 * $rows = $command->queryAll();
39
 * ```
40
 *
41
 * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
42
 *
43
 * A more detailed usage guide on how to work with Query can be found in the [guide article on Query Builder](guide:db-query-builder).
44
 *
45
 * @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only.
46
 *
47
 * @author Qiang Xue <[email protected]>
48
 * @author Carsten Brandt <[email protected]>
49
 * @since 2.0
50
 */
51
class Query extends Component implements QueryInterface, ExpressionInterface
52
{
53
    use QueryTrait;
54
55
    /**
56
     * @var array the columns being selected. For example, `['id', 'name']`.
57
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
58
     * @see select()
59
     */
60
    public $select;
61
    /**
62
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
63
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
64
     */
65
    public $selectOption;
66
    /**
67
     * @var bool whether to select distinct rows of data only. If this is set true,
68
     * the SELECT clause would be changed to SELECT DISTINCT.
69
     */
70
    public $distinct;
71
    /**
72
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
73
     * This is used to construct the FROM clause in a SQL statement.
74
     * @see from()
75
     */
76
    public $from;
77
    /**
78
     * @var array how to group the query results. For example, `['company', 'department']`.
79
     * This is used to construct the GROUP BY clause in a SQL statement.
80
     */
81
    public $groupBy;
82
    /**
83
     * @var array how to join with other tables. Each array element represents the specification
84
     * of one join which has the following structure:
85
     *
86
     * ```php
87
     * [$joinType, $tableName, $joinCondition]
88
     * ```
89
     *
90
     * For example,
91
     *
92
     * ```php
93
     * [
94
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
95
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
96
     * ]
97
     * ```
98
     */
99
    public $join;
100
    /**
101
     * @var string|array|ExpressionInterface the condition to be applied in the GROUP BY clause.
102
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
103
     */
104
    public $having;
105
    /**
106
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
107
     * Each array element is an array of the following structure:
108
     *
109
     * - `query`: either a string or a [[Query]] object representing a query
110
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
111
     */
112
    public $union;
113
    /**
114
     * @var array list of query parameter values indexed by parameter placeholders.
115
     * For example, `[':name' => 'Dan', ':age' => 31]`.
116
     */
117
    public $params = [];
118
    /**
119
     * @var int|true the default number of seconds that query results can remain valid in cache.
120
     * Use 0 to indicate that the cached data will never expire.
121
     * Use a negative number to indicate that query cache should not be used.
122
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
123
     * @see cache()
124
     * @since 2.0.14
125
     */
126
    public $queryCacheDuration;
127
    /**
128
     * @var \yii\caching\Dependency the dependency to be associated with the cached query result for this query
129
     * @see cache()
130
     * @since 2.0.14
131
     */
132
    public $queryCacheDependency;
133
134
135
    /**
136
     * Creates a DB command that can be used to execute this query.
137
     * @param Connection $db the database connection used to generate the SQL statement.
138
     * If this parameter is not given, the `db` application component will be used.
139
     * @return Command the created DB command instance.
140
     */
141 363
    public function createCommand($db = null)
142
    {
143 363
        if ($db === null) {
144 37
            $db = Yii::$app->getDb();
145
        }
146 363
        [$sql, $params] = $db->getQueryBuilder()->build($this);
0 ignored issues
show
Bug introduced by
The variable $sql 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...
Bug introduced by
The variable $params 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...
147
148 363
        $command = $db->createCommand($sql, $params);
149 363
        $this->setCommandCache($command);
150
151 363
        return $command;
152
    }
153
154
    /**
155
     * Prepares for building SQL.
156
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
157
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
158
     * @param QueryBuilder $builder
159
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
160
     */
161 775
    public function prepare($builder)
0 ignored issues
show
Unused Code introduced by
The parameter $builder is not used and could be removed.

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

Loading history...
162
    {
163 775
        return $this;
164
    }
165
166
    /**
167
     * Starts a batch query.
168
     *
169
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
170
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
171
     * and can be traversed to retrieve the data in batches.
172
     *
173
     * For example,
174
     *
175
     * ```php
176
     * $query = (new Query)->from('user');
177
     * foreach ($query->batch() as $rows) {
178
     *     // $rows is an array of 100 or fewer rows from user table
179
     * }
180
     * ```
181
     *
182
     * @param int $batchSize the number of records to be fetched in each batch.
183
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
184
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
185
     * and can be traversed to retrieve the data in batches.
186
     */
187 6
    public function batch($batchSize = 100, $db = null)
188
    {
189 6
        return Yii::createObject([
190 6
            'class' => BatchQueryResult::class,
191 6
            'query' => $this,
192 6
            'batchSize' => $batchSize,
193 6
            'db' => $db,
194
            'each' => false,
195
        ]);
196
    }
197
198
    /**
199
     * Starts a batch query and retrieves data row by row.
200
     *
201
     * This method is similar to [[batch()]] except that in each iteration of the result,
202
     * only one row of data is returned. For example,
203
     *
204
     * ```php
205
     * $query = (new Query)->from('user');
206
     * foreach ($query->each() as $row) {
207
     * }
208
     * ```
209
     *
210
     * @param int $batchSize the number of records to be fetched in each batch.
211
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
212
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
213
     * and can be traversed to retrieve the data in batches.
214
     */
215 3
    public function each($batchSize = 100, $db = null)
216
    {
217 3
        return Yii::createObject([
218 3
            'class' => BatchQueryResult::class,
219 3
            'query' => $this,
220 3
            'batchSize' => $batchSize,
221 3
            'db' => $db,
222
            'each' => true,
223
        ]);
224
    }
225
226
    /**
227
     * Executes the query and returns all results as an array.
228
     * @param Connection $db the database connection used to generate the SQL statement.
229
     * If this parameter is not given, the `db` application component will be used.
230
     * @return array the query results. If the query results in nothing, an empty array will be returned.
231
     */
232 424
    public function all($db = null)
233
    {
234 424
        if ($this->emulateExecution) {
235 9
            return [];
236
        }
237 418
        $rows = $this->createCommand($db)->queryAll();
238 418
        return $this->populate($rows);
239
    }
240
241
    /**
242
     * Converts the raw query results into the format as specified by this query.
243
     * This method is internally used to convert the data fetched from database
244
     * into the format as required by this query.
245
     * @param array $rows the raw query result from database
246
     * @return array the converted query result
247
     */
248 555
    public function populate($rows)
249
    {
250 555
        if ($this->indexBy === null) {
251 549
            return $rows;
252
        }
253 21
        $result = [];
254 21
        foreach ($rows as $row) {
255 21
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
0 ignored issues
show
Documentation introduced by
$this->indexBy is of type callable, but the function expects a string|object<Closure>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
256
        }
257
258 21
        return $result;
259
    }
260
261
    /**
262
     * Executes the query and returns a single row of result.
263
     * @param Connection $db the database connection used to generate the SQL statement.
264
     * If this parameter is not given, the `db` application component will be used.
265
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
266
     * results in nothing.
267
     */
268 458
    public function one($db = null)
269
    {
270 458
        if ($this->emulateExecution) {
271 6
            return false;
272
        }
273
274 452
        return $this->createCommand($db)->queryOne();
275
    }
276
277
    /**
278
     * Returns the query result as a scalar value.
279
     * The value returned will be the first column in the first row of the query results.
280
     * @param Connection $db the database connection used to generate the SQL statement.
281
     * If this parameter is not given, the `db` application component will be used.
282
     * @return string|null|false the value of the first column in the first row of the query result.
283
     * False is returned if the query result is empty.
284
     */
285 30
    public function scalar($db = null)
286
    {
287 30
        if ($this->emulateExecution) {
288 6
            return null;
289
        }
290
291 24
        return $this->createCommand($db)->queryScalar();
292
    }
293
294
    /**
295
     * Executes the query and returns the first column of the result.
296
     * @param Connection $db the database connection used to generate the SQL statement.
297
     * If this parameter is not given, the `db` application component will be used.
298
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
299
     */
300 73
    public function column($db = null)
301
    {
302 73
        if ($this->emulateExecution) {
303 6
            return [];
304
        }
305
306 67
        if ($this->indexBy === null) {
307 61
            return $this->createCommand($db)->queryColumn();
308
        }
309
310 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
311 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
312 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
313
            } else {
314
                $this->select[] = $this->indexBy;
315
            }
316
        }
317 9
        $rows = $this->createCommand($db)->queryAll();
318 9
        $results = [];
319 9
        foreach ($rows as $row) {
320 9
            $value = reset($row);
321
322 9
            if ($this->indexBy instanceof \Closure) {
323 3
                $results[call_user_func($this->indexBy, $row)] = $value;
324
            } else {
325 9
                $results[$row[$this->indexBy]] = $value;
326
            }
327
        }
328
329 9
        return $results;
330
    }
331
332
    /**
333
     * Returns the number of records.
334
     * @param string $q the COUNT expression. Defaults to '*'.
335
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
336
     * @param Connection $db the database connection used to generate the SQL statement.
337
     * If this parameter is not given (or null), the `db` application component will be used.
338
     * @return int|string number of records. The result may be a string depending on the
339
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
340
     */
341 90
    public function count($q = '*', $db = null)
342
    {
343 90
        if ($this->emulateExecution) {
344 6
            return 0;
345
        }
346
347 90
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->queryScalar("COUNT({$q})", $db); of type null|string|false adds false to the return on line 347 which is incompatible with the return type declared by the interface yii\db\QueryInterface::count of type integer. It seems like you forgot to handle an error condition.
Loading history...
348
    }
349
350
    /**
351
     * Returns the sum of the specified column values.
352
     * @param string $q the column name or expression.
353
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
354
     * @param Connection $db the database connection used to generate the SQL statement.
355
     * If this parameter is not given, the `db` application component will be used.
356
     * @return mixed the sum of the specified column values.
357
     */
358 9
    public function sum($q, $db = null)
359
    {
360 9
        if ($this->emulateExecution) {
361 6
            return 0;
362
        }
363
364 3
        return $this->queryScalar("SUM($q)", $db);
365
    }
366
367
    /**
368
     * Returns the average of the specified column values.
369
     * @param string $q the column name or expression.
370
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
371
     * @param Connection $db the database connection used to generate the SQL statement.
372
     * If this parameter is not given, the `db` application component will be used.
373
     * @return mixed the average of the specified column values.
374
     */
375 9
    public function average($q, $db = null)
376
    {
377 9
        if ($this->emulateExecution) {
378 6
            return 0;
379
        }
380
381 3
        return $this->queryScalar("AVG($q)", $db);
382
    }
383
384
    /**
385
     * Returns the minimum of the specified column values.
386
     * @param string $q the column name or expression.
387
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
388
     * @param Connection $db the database connection used to generate the SQL statement.
389
     * If this parameter is not given, the `db` application component will be used.
390
     * @return mixed the minimum of the specified column values.
391
     */
392 9
    public function min($q, $db = null)
393
    {
394 9
        return $this->queryScalar("MIN($q)", $db);
395
    }
396
397
    /**
398
     * Returns the maximum of the specified column values.
399
     * @param string $q the column name or expression.
400
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
401
     * @param Connection $db the database connection used to generate the SQL statement.
402
     * If this parameter is not given, the `db` application component will be used.
403
     * @return mixed the maximum of the specified column values.
404
     */
405 9
    public function max($q, $db = null)
406
    {
407 9
        return $this->queryScalar("MAX($q)", $db);
408
    }
409
410
    /**
411
     * Returns a value indicating whether the query result contains any row of data.
412
     * @param Connection $db the database connection used to generate the SQL statement.
413
     * If this parameter is not given, the `db` application component will be used.
414
     * @return bool whether the query result contains any row of data.
415
     */
416 76
    public function exists($db = null)
417
    {
418 76
        if ($this->emulateExecution) {
419 6
            return false;
420
        }
421 70
        $command = $this->createCommand($db);
422 70
        $params = $command->params;
423 70
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
424 70
        $command->bindValues($params);
425 70
        return (bool) $command->queryScalar();
426
    }
427
428
    /**
429
     * Queries a scalar value by setting [[select]] first.
430
     * Restores the value of select to make this query reusable.
431
     * @param string|ExpressionInterface $selectExpression
432
     * @param Connection|null $db
433
     * @return bool|string
434
     */
435 90
    protected function queryScalar($selectExpression, $db)
436
    {
437 90
        if ($this->emulateExecution) {
438 6
            return null;
439
        }
440
441
        if (
442 90
            !$this->distinct
443 90
            && empty($this->groupBy)
444 90
            && empty($this->having)
445 90
            && empty($this->union)
446
        ) {
447 89
            $select = $this->select;
448 89
            $order = $this->orderBy;
449 89
            $limit = $this->limit;
450 89
            $offset = $this->offset;
451
452 89
            $this->select = [$selectExpression];
453 89
            $this->orderBy = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $orderBy.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
454 89
            $this->limit = null;
455 89
            $this->offset = null;
456 89
            $command = $this->createCommand($db);
457
458 89
            $this->select = $select;
459 89
            $this->orderBy = $order;
460 89
            $this->limit = $limit;
461 89
            $this->offset = $offset;
462
463 89
            return $command->queryScalar();
464
        }
465
466 7
        $command = (new self())
467 7
            ->select([$selectExpression])
468 7
            ->from(['c' => $this])
469 7
            ->createCommand($db);
470 7
        $this->setCommandCache($command);
471
472 7
        return $command->queryScalar();
473
    }
474
475
    /**
476
     * Returns table names used in [[from]] indexed by aliases.
477
     * Both aliases and names are enclosed into {{ and }}.
478
     * @return string[] table names indexed by aliases
479
     * @throws \yii\base\InvalidConfigException
480
     * @since 2.0.12
481
     */
482 69
    public function getTablesUsedInFrom()
483
    {
484 69
        if (empty($this->from)) {
485
            return [];
486
        }
487
488 69
        if (is_array($this->from)) {
489 33
            $tableNames = $this->from;
490 36
        } elseif (is_string($this->from)) {
491 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
492 12
        } elseif ($this->from instanceof Expression) {
493 6
            $tableNames = [$this->from];
494
        } else {
495 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
496
        }
497
498 63
        return $this->cleanUpTableNames($tableNames);
499
    }
500
501
    /**
502
     * Clean up table names and aliases
503
     * Both aliases and names are enclosed into {{ and }}.
504
     * @param array $tableNames non-empty array
505
     * @return string[] table names indexed by aliases
506
     * @since 2.0.14
507
     */
508 166
    protected function cleanUpTableNames($tableNames)
509
    {
510 166
        $cleanedUpTableNames = [];
511 166
        foreach ($tableNames as $alias => $tableName) {
512 166
            if (is_string($tableName) && !is_string($alias)) {
513
                $pattern = <<<PATTERN
514 145
~
515
^
516
\s*
517
(
518
(?:['"`\[]|{{)
519
.*?
520
(?:['"`\]]|}})
521
|
522
\(.*?\)
523
|
524
.*?
525
)
526
(?:
527
(?:
528
    \s+
529
    (?:as)?
530
    \s*
531
)
532
(
533
   (?:['"`\[]|{{)
534
    .*?
535
    (?:['"`\]]|}})
536
    |
537
    .*?
538
)
539
)?
540
\s*
541
$
542
~iux
543
PATTERN;
544 145
                if (preg_match($pattern, $tableName, $matches)) {
545 145
                    if (isset($matches[2])) {
546 18
                        [, $tableName, $alias] = $matches;
547
                    } else {
548 139
                        $tableName = $alias = $matches[1];
549
                    }
550
                }
551
            }
552
553
554 166
            if ($tableName instanceof Expression) {
555 12
                if (!is_string($alias)) {
556 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
557
                }
558 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
559 154
            } elseif ($tableName instanceof self) {
560 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
561
            } else {
562 160
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
563
            }
564
        }
565
566 160
        return $cleanedUpTableNames;
567
    }
568
569
    /**
570
     * Ensures name is wrapped with {{ and }}
571
     * @param string $name
572
     * @return string
573
     */
574 160
    private function ensureNameQuoted($name)
575
    {
576 160
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
577 160
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
578 148
            return '{{' . $name . '}}';
579
        }
580
581 30
        return $name;
582
    }
583
584
    /**
585
     * Sets the SELECT part of the query.
586
     * @param string|array|ExpressionInterface $columns the columns to be selected.
587
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
588
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
589
     * The method will automatically quote the column names unless a column contains some parenthesis
590
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
591
     * an [[ExpressionInterface]] object.
592
     *
593
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
594
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
595
     *
596
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
597
     * does not need alias, do not use a string key).
598
     *
599
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
600
     * as a `Query` instance representing the sub-query.
601
     *
602
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
603
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
604
     * @return $this the query object itself
605
     */
606 399
    public function select($columns, $option = null)
607
    {
608 399
        if ($columns instanceof ExpressionInterface) {
609 3
            $columns = [$columns];
610 396
        } elseif (!is_array($columns)) {
611 104
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
612
        }
613 399
        $this->select = [];
614 399
        $this->select = $this->getUniqueColumns($columns);
615 399
        $this->selectOption = $option;
616 399
        return $this;
617
    }
618
619
    /**
620
     * Add more columns to the SELECT part of the query.
621
     *
622
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
623
     * if you want to select all remaining columns too:
624
     *
625
     * ```php
626
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
627
     * ```
628
     *
629
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
630
     * details about the format of this parameter.
631
     * @return $this the query object itself
632
     * @see select()
633
     */
634 9
    public function addSelect($columns)
635
    {
636 9
        if ($columns instanceof ExpressionInterface) {
637 3
            $columns = [$columns];
638 9
        } elseif (!is_array($columns)) {
639 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
640
        }
641 9
        $columns = $this->getUniqueColumns($columns);
642 9
        if ($this->select === null) {
643 3
            $this->select = $columns;
644
        } else {
645 9
            $this->select = array_merge($this->select, $columns);
646
        }
647
648 9
        return $this;
649
    }
650
651
    /**
652
     * Returns unique column names excluding duplicates.
653
     * Columns to be removed:
654
     * - if column definition already present in SELECT part with same alias
655
     * - if column definition without alias already present in SELECT part without alias too
656
     * @param array $columns the columns to be merged to the select.
657
     * @since 2.0.14
658
     */
659 399
    protected function getUniqueColumns($columns)
660
    {
661 399
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
662
663 399
        $result = [];
664 399
        foreach ($columns as $columnAlias => $columnDefinition) {
665 396
            if (!$columnDefinition instanceof Query) {
666 396
                if (is_string($columnAlias)) {
667 47
                    $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
668 47
                    if ($existsInSelect) {
669 47
                        continue;
670
                    }
671 391
                } elseif (is_integer($columnAlias)) {
672 391
                    $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
673 391
                    $existsInResultSet = in_array($columnDefinition, $result, true);
674 391
                    if ($existsInSelect || $existsInResultSet) {
675 3
                        continue;
676
                    }
677
                }
678
            }
679
680 396
            $result[$columnAlias] = $columnDefinition;
681
        }
682 399
        return $result;
683
    }
684
685
    /**
686
     * @return array List of columns without aliases from SELECT statement.
687
     * @since 2.0.14
688
     */
689 399
    protected function getUnaliasedColumnsFromSelect()
690
    {
691 399
        $result = [];
692 399
        if (is_array($this->select)) {
693 399
            foreach ($this->select as $name => $value) {
694 9
                if (is_integer($name)) {
695 9
                    $result[] = $value;
696
                }
697
            }
698
        }
699 399
        return array_unique($result);
700
    }
701
702
    /**
703
     * Sets the value indicating whether to SELECT DISTINCT or not.
704
     * @param bool $value whether to SELECT DISTINCT or not.
705
     * @return $this the query object itself
706
     */
707 6
    public function distinct($value = true)
708
    {
709 6
        $this->distinct = $value;
710 6
        return $this;
711
    }
712
713
    /**
714
     * Sets the FROM part of the query.
715
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
716
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
717
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
718
     * The method will automatically quote the table names unless it contains some parenthesis
719
     * (which means the table is given as a sub-query or DB expression).
720
     *
721
     * When the tables are specified as an array, you may also use the array keys as the table aliases
722
     * (if a table does not need alias, do not use a string key).
723
     *
724
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
725
     * as the alias for the sub-query.
726
     *
727
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
728
     *
729
     * Here are some examples:
730
     *
731
     * ```php
732
     * // SELECT * FROM  `user` `u`, `profile`;
733
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
734
     *
735
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
736
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
737
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
738
     *
739
     * // subquery can also be a string with plain SQL wrapped in parenthesis
740
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
741
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
742
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
743
     * ```
744
     *
745
     * @return $this the query object itself
746
     */
747 438
    public function from($tables)
748
    {
749 438
        if ($tables instanceof Expression) {
750 6
            $tables = [$tables];
751
        }
752 438
        if (is_string($tables)) {
753 402
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
754
        }
755 438
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type object<yii\db\ExpressionInterface>. However, the property $from is declared as type array. 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...
756 438
        return $this;
757
    }
758
759
    /**
760
     * Sets the WHERE part of the query.
761
     *
762
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
763
     * specifying the values to be bound to the query.
764
     *
765
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
766
     *
767
     * {@inheritdoc}
768
     *
769
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
770
     * @param array $params the parameters (name => value) to be bound to the query.
771
     * @return $this the query object itself
772
     * @see andWhere()
773
     * @see orWhere()
774
     * @see QueryInterface::where()
775
     */
776 748
    public function where($condition, $params = [])
777
    {
778 748
        $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
779 748
        $this->addParams($params);
780 748
        return $this;
781
    }
782
783
    /**
784
     * Adds an additional WHERE condition to the existing one.
785
     * The new condition and the existing one will be joined using the `AND` operator.
786
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
787
     * on how to specify this parameter.
788
     * @param array $params the parameters (name => value) to be bound to the query.
789
     * @return $this the query object itself
790
     * @see where()
791
     * @see orWhere()
792
     */
793 350
    public function andWhere($condition, $params = [])
794
    {
795 350
        if ($this->where === null) {
796 293
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
797 108
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
798 38
            $this->where[] = $condition;
799
        } else {
800 108
            $this->where = ['and', $this->where, $condition];
801
        }
802 350
        $this->addParams($params);
803 350
        return $this;
804
    }
805
806
    /**
807
     * Adds an additional WHERE condition to the existing one.
808
     * The new condition and the existing one will be joined using the `OR` operator.
809
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
810
     * on how to specify this parameter.
811
     * @param array $params the parameters (name => value) to be bound to the query.
812
     * @return $this the query object itself
813
     * @see where()
814
     * @see andWhere()
815
     */
816 7
    public function orWhere($condition, $params = [])
817
    {
818 7
        if ($this->where === null) {
819
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
820
        } else {
821 7
            $this->where = ['or', $this->where, $condition];
822
        }
823 7
        $this->addParams($params);
824 7
        return $this;
825
    }
826
827
    /**
828
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
829
     *
830
     * It adds an additional WHERE condition for the given field and determines the comparison operator
831
     * based on the first few characters of the given value.
832
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
833
     * The new condition and the existing one will be joined using the `AND` operator.
834
     *
835
     * The comparison operator is intelligently determined based on the first few characters in the given value.
836
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
837
     *
838
     * - `<`: the column must be less than the given value.
839
     * - `>`: the column must be greater than the given value.
840
     * - `<=`: the column must be less than or equal to the given value.
841
     * - `>=`: the column must be greater than or equal to the given value.
842
     * - `<>`: the column must not be the same as the given value.
843
     * - `=`: the column must be equal to the given value.
844
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
845
     *
846
     * @param string $name the column name.
847
     * @param string $value the column value optionally prepended with the comparison operator.
848
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
849
     * Defaults to `=`, performing an exact match.
850
     * @return $this The query object itself
851
     * @since 2.0.8
852
     */
853 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
854
    {
855 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
856 3
            $operator = $matches[1];
857 3
            $value = substr($value, strlen($operator));
858
        } else {
859 3
            $operator = $defaultOperator;
860
        }
861
862 3
        return $this->andFilterWhere([$operator, $name, $value]);
863
    }
864
865
    /**
866
     * Appends a JOIN part to the query.
867
     * The first parameter specifies what type of join it is.
868
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
869
     * @param string|array $table the table to be joined.
870
     *
871
     * Use a string to represent the name of the table to be joined.
872
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
873
     * The method will automatically quote the table name unless it contains some parenthesis
874
     * (which means the table is given as a sub-query or DB expression).
875
     *
876
     * Use an array to represent joining with a sub-query. The array must contain only one element.
877
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
878
     * represents the alias for the sub-query.
879
     *
880
     * @param string|array $on the join condition that should appear in the ON part.
881
     * Please refer to [[where()]] on how to specify this parameter.
882
     *
883
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
884
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
885
     * match the `post.author_id` column value against the string `'user.id'`.
886
     * It is recommended to use the string syntax here which is more suited for a join:
887
     *
888
     * ```php
889
     * 'post.author_id = user.id'
890
     * ```
891
     *
892
     * @param array $params the parameters (name => value) to be bound to the query.
893
     * @return $this the query object itself
894
     */
895 48
    public function join($type, $table, $on = '', $params = [])
896
    {
897 48
        $this->join[] = [$type, $table, $on];
898 48
        return $this->addParams($params);
899
    }
900
901
    /**
902
     * Appends an INNER JOIN part to the query.
903
     * @param string|array $table the table to be joined.
904
     *
905
     * Use a string to represent the name of the table to be joined.
906
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
907
     * The method will automatically quote the table name unless it contains some parenthesis
908
     * (which means the table is given as a sub-query or DB expression).
909
     *
910
     * Use an array to represent joining with a sub-query. The array must contain only one element.
911
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
912
     * represents the alias for the sub-query.
913
     *
914
     * @param string|array $on the join condition that should appear in the ON part.
915
     * Please refer to [[join()]] on how to specify this parameter.
916
     * @param array $params the parameters (name => value) to be bound to the query.
917
     * @return $this the query object itself
918
     */
919 3
    public function innerJoin($table, $on = '', $params = [])
920
    {
921 3
        $this->join[] = ['INNER JOIN', $table, $on];
922 3
        return $this->addParams($params);
923
    }
924
925
    /**
926
     * Appends a LEFT OUTER JOIN part to the query.
927
     * @param string|array $table the table to be joined.
928
     *
929
     * Use a string to represent the name of the table to be joined.
930
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
931
     * The method will automatically quote the table name unless it contains some parenthesis
932
     * (which means the table is given as a sub-query or DB expression).
933
     *
934
     * Use an array to represent joining with a sub-query. The array must contain only one element.
935
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
936
     * represents the alias for the sub-query.
937
     *
938
     * @param string|array $on the join condition that should appear in the ON part.
939
     * Please refer to [[join()]] on how to specify this parameter.
940
     * @param array $params the parameters (name => value) to be bound to the query
941
     * @return $this the query object itself
942
     */
943 3
    public function leftJoin($table, $on = '', $params = [])
944
    {
945 3
        $this->join[] = ['LEFT JOIN', $table, $on];
946 3
        return $this->addParams($params);
947
    }
948
949
    /**
950
     * Appends a RIGHT OUTER JOIN part to the query.
951
     * @param string|array $table the table to be joined.
952
     *
953
     * Use a string to represent the name of the table to be joined.
954
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
955
     * The method will automatically quote the table name unless it contains some parenthesis
956
     * (which means the table is given as a sub-query or DB expression).
957
     *
958
     * Use an array to represent joining with a sub-query. The array must contain only one element.
959
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
960
     * represents the alias for the sub-query.
961
     *
962
     * @param string|array $on the join condition that should appear in the ON part.
963
     * Please refer to [[join()]] on how to specify this parameter.
964
     * @param array $params the parameters (name => value) to be bound to the query
965
     * @return $this the query object itself
966
     */
967
    public function rightJoin($table, $on = '', $params = [])
968
    {
969
        $this->join[] = ['RIGHT JOIN', $table, $on];
970
        return $this->addParams($params);
971
    }
972
973
    /**
974
     * Sets the GROUP BY part of the query.
975
     * @param string|array|ExpressionInterface $columns the columns to be grouped by.
976
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
977
     * The method will automatically quote the column names unless a column contains some parenthesis
978
     * (which means the column contains a DB expression).
979
     *
980
     * Note that if your group-by is an expression containing commas, you should always use an array
981
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
982
     * the group-by columns.
983
     *
984
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
985
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
986
     * @return $this the query object itself
987
     * @see addGroupBy()
988
     */
989 24
    public function groupBy($columns)
990
    {
991 24
        if ($columns instanceof ExpressionInterface) {
992 3
            $columns = [$columns];
993 24
        } elseif (!is_array($columns)) {
994 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
995
        }
996 24
        $this->groupBy = $columns;
997 24
        return $this;
998
    }
999
1000
    /**
1001
     * Adds additional group-by columns to the existing ones.
1002
     * @param string|array $columns additional columns to be grouped by.
1003
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1004
     * The method will automatically quote the column names unless a column contains some parenthesis
1005
     * (which means the column contains a DB expression).
1006
     *
1007
     * Note that if your group-by is an expression containing commas, you should always use an array
1008
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1009
     * the group-by columns.
1010
     *
1011
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1012
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1013
     * @return $this the query object itself
1014
     * @see groupBy()
1015
     */
1016 3
    public function addGroupBy($columns)
1017
    {
1018 3
        if ($columns instanceof ExpressionInterface) {
1019
            $columns = [$columns];
1020 3
        } elseif (!is_array($columns)) {
1021 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1022
        }
1023 3
        if ($this->groupBy === null) {
1024
            $this->groupBy = $columns;
1025
        } else {
1026 3
            $this->groupBy = array_merge($this->groupBy, $columns);
1027
        }
1028
1029 3
        return $this;
1030
    }
1031
1032
    /**
1033
     * Sets the HAVING part of the query.
1034
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1035
     * Please refer to [[where()]] on how to specify this parameter.
1036
     * @param array $params the parameters (name => value) to be bound to the query.
1037
     * @return $this the query object itself
1038
     * @see andHaving()
1039
     * @see orHaving()
1040
     */
1041 10
    public function having($condition, $params = [])
1042
    {
1043 10
        $this->having = $condition;
1044 10
        $this->addParams($params);
1045 10
        return $this;
1046
    }
1047
1048
    /**
1049
     * Adds an additional HAVING condition to the existing one.
1050
     * The new condition and the existing one will be joined using the `AND` operator.
1051
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1052
     * on how to specify this parameter.
1053
     * @param array $params the parameters (name => value) to be bound to the query.
1054
     * @return $this the query object itself
1055
     * @see having()
1056
     * @see orHaving()
1057
     */
1058 3
    public function andHaving($condition, $params = [])
1059
    {
1060 3
        if ($this->having === null) {
1061
            $this->having = $condition;
1062
        } else {
1063 3
            $this->having = ['and', $this->having, $condition];
1064
        }
1065 3
        $this->addParams($params);
1066 3
        return $this;
1067
    }
1068
1069
    /**
1070
     * Adds an additional HAVING condition to the existing one.
1071
     * The new condition and the existing one will be joined using the `OR` operator.
1072
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1073
     * on how to specify this parameter.
1074
     * @param array $params the parameters (name => value) to be bound to the query.
1075
     * @return $this the query object itself
1076
     * @see having()
1077
     * @see andHaving()
1078
     */
1079 3
    public function orHaving($condition, $params = [])
1080
    {
1081 3
        if ($this->having === null) {
1082
            $this->having = $condition;
1083
        } else {
1084 3
            $this->having = ['or', $this->having, $condition];
1085
        }
1086 3
        $this->addParams($params);
1087 3
        return $this;
1088
    }
1089
1090
    /**
1091
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1092
     *
1093
     * This method is similar to [[having()]]. The main difference is that this method will
1094
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1095
     * for building query conditions based on filter values entered by users.
1096
     *
1097
     * The following code shows the difference between this method and [[having()]]:
1098
     *
1099
     * ```php
1100
     * // HAVING `age`=:age
1101
     * $query->filterHaving(['name' => null, 'age' => 20]);
1102
     * // HAVING `age`=:age
1103
     * $query->having(['age' => 20]);
1104
     * // HAVING `name` IS NULL AND `age`=:age
1105
     * $query->having(['name' => null, 'age' => 20]);
1106
     * ```
1107
     *
1108
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1109
     *
1110
     * @param array $condition the conditions that should be put in the HAVING part.
1111
     * See [[having()]] on how to specify this parameter.
1112
     * @return $this the query object itself
1113
     * @see having()
1114
     * @see andFilterHaving()
1115
     * @see orFilterHaving()
1116
     * @since 2.0.11
1117
     */
1118 6
    public function filterHaving(array $condition)
1119
    {
1120 6
        $condition = $this->filterCondition($condition);
1121 6
        if ($condition !== []) {
1122 6
            $this->having($condition);
1123
        }
1124
1125 6
        return $this;
1126
    }
1127
1128
    /**
1129
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1130
     * The new condition and the existing one will be joined using the `AND` operator.
1131
     *
1132
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1133
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1134
     * for building query conditions based on filter values entered by users.
1135
     *
1136
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1137
     * on how to specify this parameter.
1138
     * @return $this the query object itself
1139
     * @see filterHaving()
1140
     * @see orFilterHaving()
1141
     * @since 2.0.11
1142
     */
1143 6
    public function andFilterHaving(array $condition)
1144
    {
1145 6
        $condition = $this->filterCondition($condition);
1146 6
        if ($condition !== []) {
1147
            $this->andHaving($condition);
1148
        }
1149
1150 6
        return $this;
1151
    }
1152
1153
    /**
1154
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1155
     * The new condition and the existing one will be joined using the `OR` operator.
1156
     *
1157
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1158
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1159
     * for building query conditions based on filter values entered by users.
1160
     *
1161
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1162
     * on how to specify this parameter.
1163
     * @return $this the query object itself
1164
     * @see filterHaving()
1165
     * @see andFilterHaving()
1166
     * @since 2.0.11
1167
     */
1168 6
    public function orFilterHaving(array $condition)
1169
    {
1170 6
        $condition = $this->filterCondition($condition);
1171 6
        if ($condition !== []) {
1172
            $this->orHaving($condition);
1173
        }
1174
1175 6
        return $this;
1176
    }
1177
1178
    /**
1179
     * Appends a SQL statement using UNION operator.
1180
     * @param string|Query $sql the SQL statement to be appended using UNION
1181
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1182
     * @return $this the query object itself
1183
     */
1184 10
    public function union($sql, $all = false)
1185
    {
1186 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1187 10
        return $this;
1188
    }
1189
1190
    /**
1191
     * Sets the parameters to be bound to the query.
1192
     * @param array $params list of query parameter values indexed by parameter placeholders.
1193
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1194
     * @return $this the query object itself
1195
     * @see addParams()
1196
     */
1197 6
    public function params($params)
1198
    {
1199 6
        $this->params = $params;
1200 6
        return $this;
1201
    }
1202
1203
    /**
1204
     * Adds additional parameters to be bound to the query.
1205
     * @param array $params list of query parameter values indexed by parameter placeholders.
1206
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1207
     * @return $this the query object itself
1208
     * @see params()
1209
     */
1210 1011
    public function addParams($params)
1211
    {
1212 1011
        if (!empty($params)) {
1213 77
            if (empty($this->params)) {
1214 77
                $this->params = $params;
1215
            } else {
1216 6
                foreach ($params as $name => $value) {
1217 6
                    if (is_int($name)) {
1218
                        $this->params[] = $value;
1219
                    } else {
1220 6
                        $this->params[$name] = $value;
1221
                    }
1222
                }
1223
            }
1224
        }
1225
1226 1011
        return $this;
1227
    }
1228
1229
    /**
1230
     * Enables query cache for this Query.
1231
     * @param int|true $duration the number of seconds that query results can remain valid in cache.
1232
     * Use 0 to indicate that the cached data will never expire.
1233
     * Use a negative number to indicate that query cache should not be used.
1234
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1235
     * Defaults to `true`.
1236
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached result.
1237
     * @return $this the Query object itself
1238
     * @since 2.0.14
1239
     */
1240 3
    public function cache($duration = true, $dependency = null)
1241
    {
1242 3
        $this->queryCacheDuration = $duration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $duration can also be of type boolean. However, the property $queryCacheDuration is declared as type integer|object<yii\db\true>. 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...
1243 3
        $this->queryCacheDependency = $dependency;
1244 3
        return $this;
1245
    }
1246
1247
    /**
1248
     * Disables query cache for this Query.
1249
     * @return $this the Query object itself
1250
     * @since 2.0.14
1251
     */
1252 3
    public function noCache()
1253
    {
1254 3
        $this->queryCacheDuration = -1;
1255 3
        return $this;
1256
    }
1257
1258
    /**
1259
     * Sets $command cache, if this query has enabled caching.
1260
     *
1261
     * @param Command $command
1262
     * @return Command
1263
     * @since 2.0.14
1264
     */
1265 751
    protected function setCommandCache($command)
1266
    {
1267 751
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1268 3
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1269 3
            $command->cache($duration, $this->queryCacheDependency);
1270
        }
1271
1272 751
        return $command;
1273
    }
1274
1275
    /**
1276
     * Creates a new Query object and copies its property values from an existing one.
1277
     * The properties being copies are the ones to be used by query builders.
1278
     * @param Query $from the source query object
1279
     * @return Query the new Query object
1280
     */
1281 391
    public static function create($from)
1282
    {
1283 391
        return new self([
1284 391
            'where' => $from->where,
1285 391
            'limit' => $from->limit,
1286 391
            'offset' => $from->offset,
1287 391
            'orderBy' => $from->orderBy,
1288 391
            'indexBy' => $from->indexBy,
1289 391
            'select' => $from->select,
1290 391
            'selectOption' => $from->selectOption,
1291 391
            'distinct' => $from->distinct,
1292 391
            'from' => $from->from,
1293 391
            'groupBy' => $from->groupBy,
1294 391
            'join' => $from->join,
1295 391
            'having' => $from->having,
1296 391
            'union' => $from->union,
1297 391
            'params' => $from->params,
1298
        ]);
1299
    }
1300
1301
    /**
1302
     * Returns the SQL representation of Query
1303
     * @return string
1304
     */
1305
    public function __toString()
1306
    {
1307
        return serialize($this);
1308
    }
1309
}
1310