Passed
Push — master ( 1ed6ec...54b3d6 )
by Alexander
14:36
created

Query::normalizeSelect()   B

Complexity

Conditions 9
Paths 18

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 18
nop 1
dl 0
loc 33
ccs 20
cts 20
cp 1
crap 9
rs 8.0555
c 0
b 0
f 0
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 370
    public function createCommand($db = null)
142
    {
143 370
        if ($db === null) {
144 37
            $db = Yii::$app->getDb();
145
        }
146 370
        list($sql, $params) = $db->getQueryBuilder()->build($this);
147
148 370
        $command = $db->createCommand($sql, $params);
149 370
        $this->setCommandCache($command);
150
151 370
        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 790
    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

161
    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...
162
    {
163 790
        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::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

190
            '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...
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::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

218
            '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...
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 441
    public function all($db = null)
233
    {
234 441
        if ($this->emulateExecution) {
235 9
            return [];
236
        }
237 435
        $rows = $this->createCommand($db)->queryAll();
238 435
        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 575
    public function populate($rows)
249
    {
250 575
        if ($this->indexBy === null) {
251 569
            return $rows;
252
        }
253 24
        $result = [];
254 24
        foreach ($rows as $row) {
255 24
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
256
        }
257
258 24
        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 467
    public function one($db = null)
269
    {
270 467
        if ($this->emulateExecution) {
271 6
            return false;
272
        }
273
274 461
        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 33
    public function scalar($db = null)
286
    {
287 33
        if ($this->emulateExecution) {
288 6
            return null;
289
        }
290
291 27
        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 76
    public function column($db = null)
301
    {
302 76
        if ($this->emulateExecution) {
303 6
            return [];
304
        }
305
306 70
        if ($this->indexBy === null) {
307 64
            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 87
    public function count($q = '*', $db = null)
342
    {
343 87
        if ($this->emulateExecution) {
344 6
            return 0;
345
        }
346
347 87
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->queryScalar('COUNT('.$q.')', $db) returns the type string which is incompatible with the return type mandated by yii\db\QueryInterface::count() of integer.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
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 87
    protected function queryScalar($selectExpression, $db)
436
    {
437 87
        if ($this->emulateExecution) {
438 6
            return null;
439
        }
440
441
        if (
442 87
            !$this->distinct
443 87
            && empty($this->groupBy)
444 87
            && empty($this->having)
445 87
            && empty($this->union)
446
        ) {
447 86
            $select = $this->select;
448 86
            $order = $this->orderBy;
449 86
            $limit = $this->limit;
450 86
            $offset = $this->offset;
451
452 86
            $this->select = [$selectExpression];
453 86
            $this->orderBy = null;
454 86
            $this->limit = null;
455 86
            $this->offset = null;
456 86
            $command = $this->createCommand($db);
457
458 86
            $this->select = $select;
459 86
            $this->orderBy = $order;
460 86
            $this->limit = $limit;
461 86
            $this->offset = $offset;
462
463 86
            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 120
    public function getTablesUsedInFrom()
483
    {
484 120
        if (empty($this->from)) {
485
            return [];
486
        }
487
488 120
        if (is_array($this->from)) {
0 ignored issues
show
introduced by
The condition is_array($this->from) is always true.
Loading history...
489 84
            $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 114
        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 272
    protected function cleanUpTableNames($tableNames)
509
    {
510 272
        $cleanedUpTableNames = [];
511 272
        foreach ($tableNames as $alias => $tableName) {
512 272
            if (is_string($tableName) && !is_string($alias)) {
513
                $pattern = <<<PATTERN
514 212
~
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 212
                if (preg_match($pattern, $tableName, $matches)) {
545 212
                    if (isset($matches[2])) {
546 18
                        list(, $tableName, $alias) = $matches;
547
                    } else {
548 206
                        $tableName = $alias = $matches[1];
549
                    }
550
                }
551
            }
552
553
554 272
            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 260
            } elseif ($tableName instanceof self) {
560 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
561
            } else {
562 266
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
563
            }
564
        }
565
566 266
        return $cleanedUpTableNames;
567
    }
568
569
    /**
570
     * Ensures name is wrapped with {{ and }}
571
     * @param string $name
572
     * @return string
573
     */
574 266
    private function ensureNameQuoted($name)
575
    {
576 266
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
577 266
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
578 254
            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 406
    public function select($columns, $option = null)
607
    {
608 406
        $this->select = $this->normalizeSelect($columns);
609 406
        $this->selectOption = $option;
610 406
        return $this;
611
    }
612
613
    /**
614
     * Add more columns to the SELECT part of the query.
615
     *
616
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
617
     * if you want to select all remaining columns too:
618
     *
619
     * ```php
620
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
621
     * ```
622
     *
623
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
624
     * details about the format of this parameter.
625
     * @return $this the query object itself
626
     * @see select()
627
     */
628 9
    public function addSelect($columns)
629
    {
630 9
        if ($this->select === null) {
631 3
            return $this->select($columns);
632
        }
633 9
        if (!is_array($this->select)) {
0 ignored issues
show
introduced by
The condition is_array($this->select) is always true.
Loading history...
634
            $this->select = $this->normalizeSelect($this->select);
635
        }
636 9
        $this->select = array_merge($this->select, $this->normalizeSelect($columns));
637
638 9
        return $this;
639
    }
640
641
    /**
642
     * Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]].
643
     *
644
     * @param string|array|ExpressionInterface $columns
645
     * @return array
646
     * @since 2.0.21
647
     */
648 406
    protected function normalizeSelect($columns)
649
    {
650 406
        if ($columns instanceof ExpressionInterface) {
651 3
            $columns = [$columns];
652 406
        } elseif (!is_array($columns)) {
653 107
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
654
        }
655 406
        $select = [];
656 406
        foreach ($columns as $columnAlias => $columnDefinition) {
657 403
            if (is_string($columnAlias)) {
658
                // Already in the normalized format, good for them
659 52
                $select[$columnAlias] = $columnDefinition;
660 52
                continue;
661
            }
662 398
            if (is_string($columnDefinition)) {
663
                if (
664 395
                    preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
665 395
                    !preg_match('/^\d+$/', $matches[2])
666
                ) {
667
                    // Using "columnName as alias" or "columnName alias" syntax
668 15
                    $select[$matches[2]] = $matches[1];
669 15
                    continue;
670
                }
671 389
                if (strpos($columnDefinition, '(') === false) {
672
                    // Normal column name, just alias it to itself to ensure it's not selected twice
673 379
                    $select[$columnDefinition] = $columnDefinition;
674 379
                    continue;
675
                }
676
            }
677
            // Either a string calling a function, DB expression, or sub-query
678 33
            $select[] = $columnDefinition;
679
        }
680 406
        return $select;
681
    }
682
683
    /**
684
     * Returns unique column names excluding duplicates.
685
     * Columns to be removed:
686
     * - if column definition already present in SELECT part with same alias
687
     * - if column definition without alias already present in SELECT part without alias too
688
     * @param array $columns the columns to be merged to the select.
689
     * @since 2.0.14
690
     * @deprecated in 2.0.21
691
     */
692
    protected function getUniqueColumns($columns)
693
    {
694
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
0 ignored issues
show
Deprecated Code introduced by
The function yii\db\Query::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

694
        $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...
695
696
        $result = [];
697
        foreach ($columns as $columnAlias => $columnDefinition) {
698
            if (!$columnDefinition instanceof Query) {
699
                if (is_string($columnAlias)) {
700
                    $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
701
                    if ($existsInSelect) {
702
                        continue;
703
                    }
704
                } elseif (is_int($columnAlias)) {
705
                    $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
706
                    $existsInResultSet = in_array($columnDefinition, $result, true);
707
                    if ($existsInSelect || $existsInResultSet) {
708
                        continue;
709
                    }
710
                }
711
            }
712
713
            $result[$columnAlias] = $columnDefinition;
714
        }
715
        return $result;
716
    }
717
718
    /**
719
     * @return array List of columns without aliases from SELECT statement.
720
     * @since 2.0.14
721
     * @deprecated in 2.0.21
722
     */
723
    protected function getUnaliasedColumnsFromSelect()
724
    {
725
        $result = [];
726
        if (is_array($this->select)) {
0 ignored issues
show
introduced by
The condition is_array($this->select) is always true.
Loading history...
727
            foreach ($this->select as $name => $value) {
728
                if (is_int($name)) {
729
                    $result[] = $value;
730
                }
731
            }
732
        }
733
        return array_unique($result);
734
    }
735
736
    /**
737
     * Sets the value indicating whether to SELECT DISTINCT or not.
738
     * @param bool $value whether to SELECT DISTINCT or not.
739
     * @return $this the query object itself
740
     */
741 6
    public function distinct($value = true)
742
    {
743 6
        $this->distinct = $value;
744 6
        return $this;
745
    }
746
747
    /**
748
     * Sets the FROM part of the query.
749
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
750
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
751
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
752
     * The method will automatically quote the table names unless it contains some parenthesis
753
     * (which means the table is given as a sub-query or DB expression).
754
     *
755
     * When the tables are specified as an array, you may also use the array keys as the table aliases
756
     * (if a table does not need alias, do not use a string key).
757
     *
758
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
759
     * as the alias for the sub-query.
760
     *
761
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
762
     *
763
     * Here are some examples:
764
     *
765
     * ```php
766
     * // SELECT * FROM  `user` `u`, `profile`;
767
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
768
     *
769
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
770
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
771
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
772
     *
773
     * // subquery can also be a string with plain SQL wrapped in parenthesis
774
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
775
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
776
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
777
     * ```
778
     *
779
     * @return $this the query object itself
780
     */
781 463
    public function from($tables)
782
    {
783 463
        if ($tables instanceof ExpressionInterface) {
784 6
            $tables = [$tables];
785
        }
786 463
        if (is_string($tables)) {
787 412
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
788
        }
789 463
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type false or string. 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...
790 463
        return $this;
791
    }
792
793
    /**
794
     * Sets the WHERE part of the query.
795
     *
796
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
797
     * specifying the values to be bound to the query.
798
     *
799
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
800
     *
801
     * {@inheritdoc}
802
     *
803
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
804
     * @param array $params the parameters (name => value) to be bound to the query.
805
     * @return $this the query object itself
806
     * @see andWhere()
807
     * @see orWhere()
808
     * @see QueryInterface::where()
809
     */
810 766
    public function where($condition, $params = [])
811
    {
812 766
        $this->where = $condition;
813 766
        $this->addParams($params);
814 766
        return $this;
815
    }
816
817
    /**
818
     * Adds an additional WHERE condition to the existing one.
819
     * The new condition and the existing one will be joined using the `AND` operator.
820
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
821
     * on how to specify this parameter.
822
     * @param array $params the parameters (name => value) to be bound to the query.
823
     * @return $this the query object itself
824
     * @see where()
825
     * @see orWhere()
826
     */
827 399
    public function andWhere($condition, $params = [])
828
    {
829 399
        if ($this->where === null) {
830 344
            $this->where = $condition;
831 109
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
832 38
            $this->where[] = $condition;
833
        } else {
834 109
            $this->where = ['and', $this->where, $condition];
835
        }
836 399
        $this->addParams($params);
837 399
        return $this;
838
    }
839
840
    /**
841
     * Adds an additional WHERE condition to the existing one.
842
     * The new condition and the existing one will be joined using the `OR` operator.
843
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
844
     * on how to specify this parameter.
845
     * @param array $params the parameters (name => value) to be bound to the query.
846
     * @return $this the query object itself
847
     * @see where()
848
     * @see andWhere()
849
     */
850 7
    public function orWhere($condition, $params = [])
851
    {
852 7
        if ($this->where === null) {
853
            $this->where = $condition;
854
        } else {
855 7
            $this->where = ['or', $this->where, $condition];
856
        }
857 7
        $this->addParams($params);
858 7
        return $this;
859
    }
860
861
    /**
862
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
863
     *
864
     * It adds an additional WHERE condition for the given field and determines the comparison operator
865
     * based on the first few characters of the given value.
866
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
867
     * The new condition and the existing one will be joined using the `AND` operator.
868
     *
869
     * The comparison operator is intelligently determined based on the first few characters in the given value.
870
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
871
     *
872
     * - `<`: the column must be less than the given value.
873
     * - `>`: the column must be greater than the given value.
874
     * - `<=`: the column must be less than or equal to the given value.
875
     * - `>=`: the column must be greater than or equal to the given value.
876
     * - `<>`: the column must not be the same as the given value.
877
     * - `=`: the column must be equal to the given value.
878
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
879
     *
880
     * @param string $name the column name.
881
     * @param string $value the column value optionally prepended with the comparison operator.
882
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
883
     * Defaults to `=`, performing an exact match.
884
     * @return $this The query object itself
885
     * @since 2.0.8
886
     */
887 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
888
    {
889 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
890 3
            $operator = $matches[1];
891 3
            $value = substr($value, strlen($operator));
892
        } else {
893 3
            $operator = $defaultOperator;
894
        }
895
896 3
        return $this->andFilterWhere([$operator, $name, $value]);
897
    }
898
899
    /**
900
     * Appends a JOIN part to the query.
901
     * The first parameter specifies what type of join it is.
902
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
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 [[where()]] on how to specify this parameter.
916
     *
917
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
918
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
919
     * match the `post.author_id` column value against the string `'user.id'`.
920
     * It is recommended to use the string syntax here which is more suited for a join:
921
     *
922
     * ```php
923
     * 'post.author_id = user.id'
924
     * ```
925
     *
926
     * @param array $params the parameters (name => value) to be bound to the query.
927
     * @return $this the query object itself
928
     */
929 51
    public function join($type, $table, $on = '', $params = [])
930
    {
931 51
        $this->join[] = [$type, $table, $on];
932 51
        return $this->addParams($params);
933
    }
934
935
    /**
936
     * Appends an INNER JOIN part to the query.
937
     * @param string|array $table the table to be joined.
938
     *
939
     * Use a string to represent the name of the table to be joined.
940
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
941
     * The method will automatically quote the table name unless it contains some parenthesis
942
     * (which means the table is given as a sub-query or DB expression).
943
     *
944
     * Use an array to represent joining with a sub-query. The array must contain only one element.
945
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
946
     * represents the alias for the sub-query.
947
     *
948
     * @param string|array $on the join condition that should appear in the ON part.
949
     * Please refer to [[join()]] on how to specify this parameter.
950
     * @param array $params the parameters (name => value) to be bound to the query.
951
     * @return $this the query object itself
952
     */
953 3
    public function innerJoin($table, $on = '', $params = [])
954
    {
955 3
        $this->join[] = ['INNER JOIN', $table, $on];
956 3
        return $this->addParams($params);
957
    }
958
959
    /**
960
     * Appends a LEFT OUTER JOIN part to the query.
961
     * @param string|array $table the table to be joined.
962
     *
963
     * Use a string to represent the name of the table to be joined.
964
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
965
     * The method will automatically quote the table name unless it contains some parenthesis
966
     * (which means the table is given as a sub-query or DB expression).
967
     *
968
     * Use an array to represent joining with a sub-query. The array must contain only one element.
969
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
970
     * represents the alias for the sub-query.
971
     *
972
     * @param string|array $on the join condition that should appear in the ON part.
973
     * Please refer to [[join()]] on how to specify this parameter.
974
     * @param array $params the parameters (name => value) to be bound to the query
975
     * @return $this the query object itself
976
     */
977 3
    public function leftJoin($table, $on = '', $params = [])
978
    {
979 3
        $this->join[] = ['LEFT JOIN', $table, $on];
980 3
        return $this->addParams($params);
981
    }
982
983
    /**
984
     * Appends a RIGHT OUTER JOIN part to the query.
985
     * @param string|array $table the table to be joined.
986
     *
987
     * Use a string to represent the name of the table to be joined.
988
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
989
     * The method will automatically quote the table name unless it contains some parenthesis
990
     * (which means the table is given as a sub-query or DB expression).
991
     *
992
     * Use an array to represent joining with a sub-query. The array must contain only one element.
993
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
994
     * represents the alias for the sub-query.
995
     *
996
     * @param string|array $on the join condition that should appear in the ON part.
997
     * Please refer to [[join()]] on how to specify this parameter.
998
     * @param array $params the parameters (name => value) to be bound to the query
999
     * @return $this the query object itself
1000
     */
1001
    public function rightJoin($table, $on = '', $params = [])
1002
    {
1003
        $this->join[] = ['RIGHT JOIN', $table, $on];
1004
        return $this->addParams($params);
1005
    }
1006
1007
    /**
1008
     * Sets the GROUP BY part of the query.
1009
     * @param string|array|ExpressionInterface $columns the columns to be grouped by.
1010
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1011
     * The method will automatically quote the column names unless a column contains some parenthesis
1012
     * (which means the column contains a DB expression).
1013
     *
1014
     * Note that if your group-by is an expression containing commas, you should always use an array
1015
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1016
     * the group-by columns.
1017
     *
1018
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1019
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1020
     * @return $this the query object itself
1021
     * @see addGroupBy()
1022
     */
1023 26
    public function groupBy($columns)
1024
    {
1025 26
        if ($columns instanceof ExpressionInterface) {
1026 3
            $columns = [$columns];
1027 26
        } elseif (!is_array($columns)) {
1028 26
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1029
        }
1030 26
        $this->groupBy = $columns;
0 ignored issues
show
Documentation Bug introduced by
It seems like $columns can also be of type false. However, the property $groupBy 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...
1031 26
        return $this;
1032
    }
1033
1034
    /**
1035
     * Adds additional group-by columns to the existing ones.
1036
     * @param string|array|ExpressionInterface $columns additional columns to be grouped by.
1037
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1038
     * The method will automatically quote the column names unless a column contains some parenthesis
1039
     * (which means the column contains a DB expression).
1040
     *
1041
     * Note that if your group-by is an expression containing commas, you should always use an array
1042
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1043
     * the group-by columns.
1044
     *
1045
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1046
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1047
     * @return $this the query object itself
1048
     * @see groupBy()
1049
     */
1050 3
    public function addGroupBy($columns)
1051
    {
1052 3
        if ($columns instanceof ExpressionInterface) {
1053
            $columns = [$columns];
1054 3
        } elseif (!is_array($columns)) {
1055 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1056
        }
1057 3
        if ($this->groupBy === null) {
1058
            $this->groupBy = $columns;
0 ignored issues
show
Documentation Bug introduced by
It seems like $columns can also be of type false. However, the property $groupBy 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...
1059
        } else {
1060 3
            $this->groupBy = array_merge($this->groupBy, $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; however, parameter $array2 of array_merge() does only seem to accept array|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

1060
            $this->groupBy = array_merge($this->groupBy, /** @scrutinizer ignore-type */ $columns);
Loading history...
1061
        }
1062
1063 3
        return $this;
1064
    }
1065
1066
    /**
1067
     * Sets the HAVING part of the query.
1068
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1069
     * Please refer to [[where()]] on how to specify this parameter.
1070
     * @param array $params the parameters (name => value) to be bound to the query.
1071
     * @return $this the query object itself
1072
     * @see andHaving()
1073
     * @see orHaving()
1074
     */
1075 10
    public function having($condition, $params = [])
1076
    {
1077 10
        $this->having = $condition;
1078 10
        $this->addParams($params);
1079 10
        return $this;
1080
    }
1081
1082
    /**
1083
     * Adds an additional HAVING condition to the existing one.
1084
     * The new condition and the existing one will be joined using the `AND` operator.
1085
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1086
     * on how to specify this parameter.
1087
     * @param array $params the parameters (name => value) to be bound to the query.
1088
     * @return $this the query object itself
1089
     * @see having()
1090
     * @see orHaving()
1091
     */
1092 3
    public function andHaving($condition, $params = [])
1093
    {
1094 3
        if ($this->having === null) {
1095
            $this->having = $condition;
1096
        } else {
1097 3
            $this->having = ['and', $this->having, $condition];
1098
        }
1099 3
        $this->addParams($params);
1100 3
        return $this;
1101
    }
1102
1103
    /**
1104
     * Adds an additional HAVING condition to the existing one.
1105
     * The new condition and the existing one will be joined using the `OR` operator.
1106
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1107
     * on how to specify this parameter.
1108
     * @param array $params the parameters (name => value) to be bound to the query.
1109
     * @return $this the query object itself
1110
     * @see having()
1111
     * @see andHaving()
1112
     */
1113 3
    public function orHaving($condition, $params = [])
1114
    {
1115 3
        if ($this->having === null) {
1116
            $this->having = $condition;
1117
        } else {
1118 3
            $this->having = ['or', $this->having, $condition];
1119
        }
1120 3
        $this->addParams($params);
1121 3
        return $this;
1122
    }
1123
1124
    /**
1125
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1126
     *
1127
     * This method is similar to [[having()]]. The main difference is that this method will
1128
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1129
     * for building query conditions based on filter values entered by users.
1130
     *
1131
     * The following code shows the difference between this method and [[having()]]:
1132
     *
1133
     * ```php
1134
     * // HAVING `age`=:age
1135
     * $query->filterHaving(['name' => null, 'age' => 20]);
1136
     * // HAVING `age`=:age
1137
     * $query->having(['age' => 20]);
1138
     * // HAVING `name` IS NULL AND `age`=:age
1139
     * $query->having(['name' => null, 'age' => 20]);
1140
     * ```
1141
     *
1142
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1143
     *
1144
     * @param array $condition the conditions that should be put in the HAVING part.
1145
     * See [[having()]] on how to specify this parameter.
1146
     * @return $this the query object itself
1147
     * @see having()
1148
     * @see andFilterHaving()
1149
     * @see orFilterHaving()
1150
     * @since 2.0.11
1151
     */
1152 6
    public function filterHaving(array $condition)
1153
    {
1154 6
        $condition = $this->filterCondition($condition);
1155 6
        if ($condition !== []) {
1156 6
            $this->having($condition);
1157
        }
1158
1159 6
        return $this;
1160
    }
1161
1162
    /**
1163
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1164
     * The new condition and the existing one will be joined using the `AND` operator.
1165
     *
1166
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1167
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1168
     * for building query conditions based on filter values entered by users.
1169
     *
1170
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1171
     * on how to specify this parameter.
1172
     * @return $this the query object itself
1173
     * @see filterHaving()
1174
     * @see orFilterHaving()
1175
     * @since 2.0.11
1176
     */
1177 6
    public function andFilterHaving(array $condition)
1178
    {
1179 6
        $condition = $this->filterCondition($condition);
1180 6
        if ($condition !== []) {
1181
            $this->andHaving($condition);
1182
        }
1183
1184 6
        return $this;
1185
    }
1186
1187
    /**
1188
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1189
     * The new condition and the existing one will be joined using the `OR` operator.
1190
     *
1191
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1192
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1193
     * for building query conditions based on filter values entered by users.
1194
     *
1195
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1196
     * on how to specify this parameter.
1197
     * @return $this the query object itself
1198
     * @see filterHaving()
1199
     * @see andFilterHaving()
1200
     * @since 2.0.11
1201
     */
1202 6
    public function orFilterHaving(array $condition)
1203
    {
1204 6
        $condition = $this->filterCondition($condition);
1205 6
        if ($condition !== []) {
1206
            $this->orHaving($condition);
1207
        }
1208
1209 6
        return $this;
1210
    }
1211
1212
    /**
1213
     * Appends a SQL statement using UNION operator.
1214
     * @param string|Query $sql the SQL statement to be appended using UNION
1215
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1216
     * @return $this the query object itself
1217
     */
1218 10
    public function union($sql, $all = false)
1219
    {
1220 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1221 10
        return $this;
1222
    }
1223
1224
    /**
1225
     * Sets the parameters to be bound to the query.
1226
     * @param array $params list of query parameter values indexed by parameter placeholders.
1227
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1228
     * @return $this the query object itself
1229
     * @see addParams()
1230
     */
1231 6
    public function params($params)
1232
    {
1233 6
        $this->params = $params;
1234 6
        return $this;
1235
    }
1236
1237
    /**
1238
     * Adds additional parameters to be bound to the query.
1239
     * @param array $params list of query parameter values indexed by parameter placeholders.
1240
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1241
     * @return $this the query object itself
1242
     * @see params()
1243
     */
1244 1077
    public function addParams($params)
1245
    {
1246 1077
        if (!empty($params)) {
1247 82
            if (empty($this->params)) {
1248 82
                $this->params = $params;
1249
            } else {
1250 6
                foreach ($params as $name => $value) {
1251 6
                    if (is_int($name)) {
1252
                        $this->params[] = $value;
1253
                    } else {
1254 6
                        $this->params[$name] = $value;
1255
                    }
1256
                }
1257
            }
1258
        }
1259
1260 1077
        return $this;
1261
    }
1262
1263
    /**
1264
     * Enables query cache for this Query.
1265
     * @param int|true $duration the number of seconds that query results can remain valid in cache.
1266
     * Use 0 to indicate that the cached data will never expire.
1267
     * Use a negative number to indicate that query cache should not be used.
1268
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1269
     * Defaults to `true`.
1270
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached result.
1271
     * @return $this the Query object itself
1272
     * @since 2.0.14
1273
     */
1274 3
    public function cache($duration = true, $dependency = null)
1275
    {
1276 3
        $this->queryCacheDuration = $duration;
1277 3
        $this->queryCacheDependency = $dependency;
1278 3
        return $this;
1279
    }
1280
1281
    /**
1282
     * Disables query cache for this Query.
1283
     * @return $this the Query object itself
1284
     * @since 2.0.14
1285
     */
1286 3
    public function noCache()
1287
    {
1288 3
        $this->queryCacheDuration = -1;
1289 3
        return $this;
1290
    }
1291
1292
    /**
1293
     * Sets $command cache, if this query has enabled caching.
1294
     *
1295
     * @param Command $command
1296
     * @return Command
1297
     * @since 2.0.14
1298
     */
1299 776
    protected function setCommandCache($command)
1300
    {
1301 776
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1302 3
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1303 3
            $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, 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

1303
            $command->cache(/** @scrutinizer ignore-type */ $duration, $this->queryCacheDependency);
Loading history...
1304
        }
1305
1306 776
        return $command;
1307
    }
1308
1309
    /**
1310
     * Creates a new Query object and copies its property values from an existing one.
1311
     * The properties being copies are the ones to be used by query builders.
1312
     * @param Query $from the source query object
1313
     * @return Query the new Query object
1314
     */
1315 445
    public static function create($from)
1316
    {
1317 445
        return new self([
1318 445
            'where' => $from->where,
1319 445
            'limit' => $from->limit,
1320 445
            'offset' => $from->offset,
1321 445
            'orderBy' => $from->orderBy,
1322 445
            'indexBy' => $from->indexBy,
1323 445
            'select' => $from->select,
1324 445
            'selectOption' => $from->selectOption,
1325 445
            'distinct' => $from->distinct,
1326 445
            'from' => $from->from,
1327 445
            'groupBy' => $from->groupBy,
1328 445
            'join' => $from->join,
1329 445
            'having' => $from->having,
1330 445
            'union' => $from->union,
1331 445
            'params' => $from->params,
1332
        ]);
1333
    }
1334
1335
    /**
1336
     * Returns the SQL representation of Query
1337
     * @return string
1338
     */
1339
    public function __toString()
1340
    {
1341
        return serialize($this);
1342
    }
1343
}
1344