Completed
Push — master ( 488f98...48e2f5 )
by Carsten
48:59 queued 45:52
created

Query::column()   D

Complexity

Conditions 10
Paths 11

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10.0203

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 4.8196
c 0
b 0
f 0
ccs 16
cts 17
cp 0.9412
cc 10
eloc 19
nc 11
nop 1
crap 10.0203

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link 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
     * Creates a DB command that can be used to execute this query.
136
     * @param Connection $db the database connection used to generate the SQL statement.
137
     * If this parameter is not given, the `db` application component will be used.
138
     * @return Command the created DB command instance.
139
     */
140 363
    public function createCommand($db = null)
141
    {
142 363
        if ($db === null) {
143 34
            $db = Yii::$app->getDb();
144
        }
145 363
        list($sql, $params) = $db->getQueryBuilder()->build($this);
146
147 363
        $command = $db->createCommand($sql, $params);
148 363
        $this->setCommandCache($command);
149
150 363
        return $command;
151
    }
152
153
    /**
154
     * Prepares for building SQL.
155
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
156
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
157
     * @param QueryBuilder $builder
158
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
159
     */
160 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...
161
    {
162 775
        return $this;
163
    }
164
165
    /**
166
     * Starts a batch query.
167
     *
168
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
169
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
170
     * and can be traversed to retrieve the data in batches.
171
     *
172
     * For example,
173
     *
174
     * ```php
175
     * $query = (new Query)->from('user');
176
     * foreach ($query->batch() as $rows) {
177
     *     // $rows is an array of 100 or fewer rows from user table
178
     * }
179
     * ```
180
     *
181
     * @param int $batchSize the number of records to be fetched in each batch.
182
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
183
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
184
     * and can be traversed to retrieve the data in batches.
185
     */
186 6
    public function batch($batchSize = 100, $db = null)
187
    {
188 6
        return Yii::createObject([
189 6
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

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

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

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

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

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

Loading history...
218 3
            'query' => $this,
219 3
            'batchSize' => $batchSize,
220 3
            'db' => $db,
221
            'each' => true,
222
        ]);
223
    }
224
225
    /**
226
     * Executes the query and returns all results as an array.
227
     * @param Connection $db the database connection used to generate the SQL statement.
228
     * If this parameter is not given, the `db` application component will be used.
229
     * @return array the query results. If the query results in nothing, an empty array will be returned.
230
     */
231 424
    public function all($db = null)
232
    {
233 424
        if ($this->emulateExecution) {
234 9
            return [];
235
        }
236 418
        $rows = $this->createCommand($db)->queryAll();
237 418
        return $this->populate($rows);
238
    }
239
240
    /**
241
     * Converts the raw query results into the format as specified by this query.
242
     * This method is internally used to convert the data fetched from database
243
     * into the format as required by this query.
244
     * @param array $rows the raw query result from database
245
     * @return array the converted query result
246
     */
247 548
    public function populate($rows)
248
    {
249 548
        if ($this->indexBy === null) {
250 542
            return $rows;
251
        }
252 21
        $result = [];
253 21
        foreach ($rows as $row) {
254 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...
255
        }
256
257 21
        return $result;
258
    }
259
260
    /**
261
     * Executes the query and returns a single row of result.
262
     * @param Connection $db the database connection used to generate the SQL statement.
263
     * If this parameter is not given, the `db` application component will be used.
264
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
265
     * results in nothing.
266
     */
267 451
    public function one($db = null)
268
    {
269 451
        if ($this->emulateExecution) {
270 6
            return false;
271
        }
272
273 445
        return $this->createCommand($db)->queryOne();
274
    }
275
276
    /**
277
     * Returns the query result as a scalar value.
278
     * The value returned will be the first column in the first row of the query results.
279
     * @param Connection $db the database connection used to generate the SQL statement.
280
     * If this parameter is not given, the `db` application component will be used.
281
     * @return string|null|false the value of the first column in the first row of the query result.
282
     * False is returned if the query result is empty.
283
     */
284 30
    public function scalar($db = null)
285
    {
286 30
        if ($this->emulateExecution) {
287 6
            return null;
288
        }
289
290 24
        return $this->createCommand($db)->queryScalar();
291
    }
292
293
    /**
294
     * Executes the query and returns the first column of the result.
295
     * @param Connection $db the database connection used to generate the SQL statement.
296
     * If this parameter is not given, the `db` application component will be used.
297
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
298
     */
299 73
    public function column($db = null)
300
    {
301 73
        if ($this->emulateExecution) {
302 6
            return [];
303
        }
304
305 67
        if ($this->indexBy === null) {
306 61
            return $this->createCommand($db)->queryColumn();
307
        }
308
309 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
310 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
311 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
312
            } else {
313
                $this->select[] = $this->indexBy;
314
            }
315
        }
316 9
        $rows = $this->createCommand($db)->queryAll();
317 9
        $results = [];
318 9
        foreach ($rows as $row) {
319 9
            $value = reset($row);
320
321 9
            if ($this->indexBy instanceof \Closure) {
322 3
                $results[call_user_func($this->indexBy, $row)] = $value;
323
            } else {
324 9
                $results[$row[$this->indexBy]] = $value;
325
            }
326
        }
327
328 9
        return $results;
329
    }
330
331
    /**
332
     * Returns the number of records.
333
     * @param string $q the COUNT expression. Defaults to '*'.
334
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
335
     * @param Connection $db the database connection used to generate the SQL statement.
336
     * If this parameter is not given (or null), the `db` application component will be used.
337
     * @return int|string number of records. The result may be a string depending on the
338
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
339
     */
340 87
    public function count($q = '*', $db = null)
341
    {
342 87
        if ($this->emulateExecution) {
343 6
            return 0;
344
        }
345
346 87
        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 346 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...
347
    }
348
349
    /**
350
     * Returns the sum of the specified column values.
351
     * @param string $q the column name or expression.
352
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
353
     * @param Connection $db the database connection used to generate the SQL statement.
354
     * If this parameter is not given, the `db` application component will be used.
355
     * @return mixed the sum of the specified column values.
356
     */
357 9
    public function sum($q, $db = null)
358
    {
359 9
        if ($this->emulateExecution) {
360 6
            return 0;
361
        }
362
363 3
        return $this->queryScalar("SUM($q)", $db);
364
    }
365
366
    /**
367
     * Returns the average of the specified column values.
368
     * @param string $q the column name or expression.
369
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
370
     * @param Connection $db the database connection used to generate the SQL statement.
371
     * If this parameter is not given, the `db` application component will be used.
372
     * @return mixed the average of the specified column values.
373
     */
374 9
    public function average($q, $db = null)
375
    {
376 9
        if ($this->emulateExecution) {
377 6
            return 0;
378
        }
379
380 3
        return $this->queryScalar("AVG($q)", $db);
381
    }
382
383
    /**
384
     * Returns the minimum of the specified column values.
385
     * @param string $q the column name or expression.
386
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
387
     * @param Connection $db the database connection used to generate the SQL statement.
388
     * If this parameter is not given, the `db` application component will be used.
389
     * @return mixed the minimum of the specified column values.
390
     */
391 9
    public function min($q, $db = null)
392
    {
393 9
        return $this->queryScalar("MIN($q)", $db);
394
    }
395
396
    /**
397
     * Returns the maximum of the specified column values.
398
     * @param string $q the column name or expression.
399
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
400
     * @param Connection $db the database connection used to generate the SQL statement.
401
     * If this parameter is not given, the `db` application component will be used.
402
     * @return mixed the maximum of the specified column values.
403
     */
404 9
    public function max($q, $db = null)
405
    {
406 9
        return $this->queryScalar("MAX($q)", $db);
407
    }
408
409
    /**
410
     * Returns a value indicating whether the query result contains any row of data.
411
     * @param Connection $db the database connection used to generate the SQL statement.
412
     * If this parameter is not given, the `db` application component will be used.
413
     * @return bool whether the query result contains any row of data.
414
     */
415 73
    public function exists($db = null)
416
    {
417 73
        if ($this->emulateExecution) {
418 6
            return false;
419
        }
420 67
        $command = $this->createCommand($db);
421 67
        $params = $command->params;
422 67
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
423 67
        $command->bindValues($params);
424 67
        return (bool) $command->queryScalar();
425
    }
426
427
    /**
428
     * Queries a scalar value by setting [[select]] first.
429
     * Restores the value of select to make this query reusable.
430
     * @param string|ExpressionInterface $selectExpression
431
     * @param Connection|null $db
432
     * @return bool|string
433
     */
434 87
    protected function queryScalar($selectExpression, $db)
435
    {
436 87
        if ($this->emulateExecution) {
437 6
            return null;
438
        }
439
440
        if (
441 87
            !$this->distinct
442 87
            && empty($this->groupBy)
443 87
            && empty($this->having)
444 87
            && empty($this->union)
445
        ) {
446 86
            $select = $this->select;
447 86
            $order = $this->orderBy;
448 86
            $limit = $this->limit;
449 86
            $offset = $this->offset;
450
451 86
            $this->select = [$selectExpression];
452 86
            $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...
453 86
            $this->limit = null;
454 86
            $this->offset = null;
455 86
            $command = $this->createCommand($db);
456
457 86
            $this->select = $select;
458 86
            $this->orderBy = $order;
459 86
            $this->limit = $limit;
460 86
            $this->offset = $offset;
461
462 86
            return $command->queryScalar();
463
        }
464
465 7
        $command = (new self())
466 7
            ->select([$selectExpression])
467 7
            ->from(['c' => $this])
468 7
            ->createCommand($db);
469 7
        $this->setCommandCache($command);
470
471 7
        return $command->queryScalar();
472
    }
473
474
    /**
475
     * Returns table names used in [[from]] indexed by aliases.
476
     * Both aliases and names are enclosed into {{ and }}.
477
     * @return string[] table names indexed by aliases
478
     * @throws \yii\base\InvalidConfigException
479
     * @since 2.0.12
480
     */
481 69
    public function getTablesUsedInFrom()
482
    {
483 69
        if (empty($this->from)) {
484
            return [];
485
        }
486
487 69
        if (is_array($this->from)) {
488 33
            $tableNames = $this->from;
489 36
        } elseif (is_string($this->from)) {
490 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
491 12
        } elseif ($this->from instanceof Expression) {
492 6
            $tableNames = [$this->from];
493
        } else {
494 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
495
        }
496
497 63
        return $this->cleanUpTableNames($tableNames);
498
    }
499
500
    /**
501
     * Clean up table names and aliases
502
     * Both aliases and names are enclosed into {{ and }}.
503
     * @param array $tableNames non-empty array
504
     * @return string[] table names indexed by aliases
505
     * @since 2.0.14
506
     */
507 165
    protected function cleanUpTableNames($tableNames)
508
    {
509 165
        $cleanedUpTableNames = [];
510 165
        foreach ($tableNames as $alias => $tableName) {
511 165
            if (is_string($tableName) && !is_string($alias)) {
512
                $pattern = <<<PATTERN
513 144
~
514
^
515
\s*
516
(
517
(?:['"`\[]|{{)
518
.*?
519
(?:['"`\]]|}})
520
|
521
\(.*?\)
522
|
523
.*?
524
)
525
(?:
526
(?:
527
    \s+
528
    (?:as)?
529
    \s*
530
)
531
(
532
   (?:['"`\[]|{{)
533
    .*?
534
    (?:['"`\]]|}})
535
    |
536
    .*?
537
)
538
)?
539
\s*
540
$
541
~iux
542
PATTERN;
543 144
                if (preg_match($pattern, $tableName, $matches)) {
544 144
                    if (isset($matches[2])) {
545 18
                        list(, $tableName, $alias) = $matches;
546
                    } else {
547 138
                        $tableName = $alias = $matches[1];
548
                    }
549
                }
550
            }
551
552
553 165
            if ($tableName instanceof Expression) {
554 12
                if (!is_string($alias)) {
555 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
556
                }
557 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
558 153
            } elseif ($tableName instanceof self) {
559 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
560
            } else {
561 159
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
562
            }
563
        }
564
565 159
        return $cleanedUpTableNames;
566
    }
567
568
    /**
569
     * Ensures name is wrapped with {{ and }}
570
     * @param string $name
571
     * @return string
572
     */
573 159
    private function ensureNameQuoted($name)
574
    {
575 159
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
576 159
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
577 147
            return '{{' . $name . '}}';
578
        }
579
580 30
        return $name;
581
    }
582
583
    /**
584
     * Sets the SELECT part of the query.
585
     * @param string|array|ExpressionInterface $columns the columns to be selected.
586
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
587
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
588
     * The method will automatically quote the column names unless a column contains some parenthesis
589
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
590
     * an [[ExpressionInterface]] object.
591
     *
592
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
593
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
594
     *
595
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
596
     * does not need alias, do not use a string key).
597
     *
598
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
599
     * as a `Query` instance representing the sub-query.
600
     *
601
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
602
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
603
     * @return $this the query object itself
604
     */
605 399
    public function select($columns, $option = null)
606
    {
607 399
        if ($columns instanceof ExpressionInterface) {
608 3
            $columns = [$columns];
609 396
        } elseif (!is_array($columns)) {
610 107
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
611
        }
612 399
        $this->select = $this->getUniqueColumns($columns);
613 399
        $this->selectOption = $option;
614 399
        return $this;
615
    }
616
617
    /**
618
     * Add more columns to the SELECT part of the query.
619
     *
620
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
621
     * if you want to select all remaining columns too:
622
     *
623
     * ```php
624
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
625
     * ```
626
     *
627
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
628
     * details about the format of this parameter.
629
     * @return $this the query object itself
630
     * @see select()
631
     */
632 9
    public function addSelect($columns)
633
    {
634 9
        if ($columns instanceof ExpressionInterface) {
635 3
            $columns = [$columns];
636 9
        } elseif (!is_array($columns)) {
637 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
638
        }
639 9
        $columns = $this->getUniqueColumns($columns);
640 9
        if ($this->select === null) {
641 3
            $this->select = $columns;
642
        } else {
643 9
            $this->select = array_merge($this->select, $columns);
644
        }
645
646 9
        return $this;
647
    }
648
649
    /**
650
     * Returns unique column names excluding duplicates.
651
     * Columns to be removed:
652
     * - if column definition already present in SELECT part with same alias
653
     * - if column definition without alias already present in SELECT part without alias too
654
     * @param array $columns the columns to be merged to the select.
655
     * @since 2.0.14
656
     */
657 399
    protected function getUniqueColumns($columns)
658
    {
659 399
        $columns = array_unique($columns);
660 399
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
661
662 399
        foreach ($columns as $columnAlias => $columnDefinition) {
663 396
            if ($columnDefinition instanceof Query) {
664 3
                continue;
665
            }
666
667
            if (
668 396
                (is_string($columnAlias) && isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition)
669 396
                || (is_integer($columnAlias) && in_array($columnDefinition, $unaliasedColumns))
670
            ) {
671 396
                unset($columns[$columnAlias]);
672
            }
673
        }
674 399
        return $columns;
675
    }
676
677
    /**
678
     * @return array List of columns without aliases from SELECT statement.
679
     * @since 2.0.14
680
     */
681 399
    protected function getUnaliasedColumnsFromSelect()
682
    {
683 399
        $result = [];
684 399
        if (is_array($this->select)) {
685 9
            foreach ($this->select as $name => $value) {
686 9
                if (is_integer($name)) {
687 9
                    $result[] = $value;
688
                }
689
            }
690
        }
691 399
        return array_unique($result);
692
    }
693
694
    /**
695
     * Sets the value indicating whether to SELECT DISTINCT or not.
696
     * @param bool $value whether to SELECT DISTINCT or not.
697
     * @return $this the query object itself
698
     */
699 6
    public function distinct($value = true)
700
    {
701 6
        $this->distinct = $value;
702 6
        return $this;
703
    }
704
705
    /**
706
     * Sets the FROM part of the query.
707
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
708
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
709
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
710
     * The method will automatically quote the table names unless it contains some parenthesis
711
     * (which means the table is given as a sub-query or DB expression).
712
     *
713
     * When the tables are specified as an array, you may also use the array keys as the table aliases
714
     * (if a table does not need alias, do not use a string key).
715
     *
716
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
717
     * as the alias for the sub-query.
718
     *
719
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
720
     *
721
     * Here are some examples:
722
     *
723
     * ```php
724
     * // SELECT * FROM  `user` `u`, `profile`;
725
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
726
     *
727
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
728
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
729
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
730
     *
731
     * // subquery can also be a string with plain SQL wrapped in parenthesis
732
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
733
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
734
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
735
     * ```
736
     *
737
     * @return $this the query object itself
738
     */
739 438
    public function from($tables)
740
    {
741 438
        if ($tables instanceof Expression) {
742 6
            $tables = [$tables];
743
        }
744 438
        if (is_string($tables)) {
745 402
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
746
        }
747 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...
748 438
        return $this;
749
    }
750
751
    /**
752
     * Sets the WHERE part of the query.
753
     *
754
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
755
     * specifying the values to be bound to the query.
756
     *
757
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
758
     *
759
     * {@inheritdoc}
760
     *
761
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
762
     * @param array $params the parameters (name => value) to be bound to the query.
763
     * @return $this the query object itself
764
     * @see andWhere()
765
     * @see orWhere()
766
     * @see QueryInterface::where()
767
     */
768 747
    public function where($condition, $params = [])
769
    {
770 747
        $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...
771 747
        $this->addParams($params);
772 747
        return $this;
773
    }
774
775
    /**
776
     * Adds an additional WHERE condition to the existing one.
777
     * The new condition and the existing one will be joined using the `AND` operator.
778
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
779
     * on how to specify this parameter.
780
     * @param array $params the parameters (name => value) to be bound to the query.
781
     * @return $this the query object itself
782
     * @see where()
783
     * @see orWhere()
784
     */
785 341
    public function andWhere($condition, $params = [])
786
    {
787 341
        if ($this->where === null) {
788 286
            $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...
789 103
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
790 38
            $this->where[] = $condition;
791
        } else {
792 103
            $this->where = ['and', $this->where, $condition];
793
        }
794 341
        $this->addParams($params);
795 341
        return $this;
796
    }
797
798
    /**
799
     * Adds an additional WHERE condition to the existing one.
800
     * The new condition and the existing one will be joined using the `OR` operator.
801
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
802
     * on how to specify this parameter.
803
     * @param array $params the parameters (name => value) to be bound to the query.
804
     * @return $this the query object itself
805
     * @see where()
806
     * @see andWhere()
807
     */
808 7
    public function orWhere($condition, $params = [])
809
    {
810 7
        if ($this->where === null) {
811
            $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...
812
        } else {
813 7
            $this->where = ['or', $this->where, $condition];
814
        }
815 7
        $this->addParams($params);
816 7
        return $this;
817
    }
818
819
    /**
820
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
821
     *
822
     * It adds an additional WHERE condition for the given field and determines the comparison operator
823
     * based on the first few characters of the given value.
824
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
825
     * The new condition and the existing one will be joined using the `AND` operator.
826
     *
827
     * The comparison operator is intelligently determined based on the first few characters in the given value.
828
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
829
     *
830
     * - `<`: the column must be less than the given value.
831
     * - `>`: the column must be greater than the given value.
832
     * - `<=`: the column must be less than or equal to the given value.
833
     * - `>=`: the column must be greater than or equal to the given value.
834
     * - `<>`: the column must not be the same as the given value.
835
     * - `=`: the column must be equal to the given value.
836
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
837
     *
838
     * @param string $name the column name.
839
     * @param string $value the column value optionally prepended with the comparison operator.
840
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
841
     * Defaults to `=`, performing an exact match.
842
     * @return $this The query object itself
843
     * @since 2.0.8
844
     */
845 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
846
    {
847 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
848 3
            $operator = $matches[1];
849 3
            $value = substr($value, strlen($operator));
850
        } else {
851 3
            $operator = $defaultOperator;
852
        }
853
854 3
        return $this->andFilterWhere([$operator, $name, $value]);
855
    }
856
857
    /**
858
     * Appends a JOIN part to the query.
859
     * The first parameter specifies what type of join it is.
860
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
861
     * @param string|array $table the table to be joined.
862
     *
863
     * Use a string to represent the name of the table to be joined.
864
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
865
     * The method will automatically quote the table name unless it contains some parenthesis
866
     * (which means the table is given as a sub-query or DB expression).
867
     *
868
     * Use an array to represent joining with a sub-query. The array must contain only one element.
869
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
870
     * represents the alias for the sub-query.
871
     *
872
     * @param string|array $on the join condition that should appear in the ON part.
873
     * Please refer to [[where()]] on how to specify this parameter.
874
     *
875
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
876
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
877
     * match the `post.author_id` column value against the string `'user.id'`.
878
     * It is recommended to use the string syntax here which is more suited for a join:
879
     *
880
     * ```php
881
     * 'post.author_id = user.id'
882
     * ```
883
     *
884
     * @param array $params the parameters (name => value) to be bound to the query.
885
     * @return $this the query object itself
886
     */
887 48
    public function join($type, $table, $on = '', $params = [])
888
    {
889 48
        $this->join[] = [$type, $table, $on];
890 48
        return $this->addParams($params);
891
    }
892
893
    /**
894
     * Appends an INNER JOIN part to the query.
895
     * @param string|array $table the table to be joined.
896
     *
897
     * Use a string to represent the name of the table to be joined.
898
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
899
     * The method will automatically quote the table name unless it contains some parenthesis
900
     * (which means the table is given as a sub-query or DB expression).
901
     *
902
     * Use an array to represent joining with a sub-query. The array must contain only one element.
903
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
904
     * represents the alias for the sub-query.
905
     *
906
     * @param string|array $on the join condition that should appear in the ON part.
907
     * Please refer to [[join()]] on how to specify this parameter.
908
     * @param array $params the parameters (name => value) to be bound to the query.
909
     * @return $this the query object itself
910
     */
911 3
    public function innerJoin($table, $on = '', $params = [])
912
    {
913 3
        $this->join[] = ['INNER JOIN', $table, $on];
914 3
        return $this->addParams($params);
915
    }
916
917
    /**
918
     * Appends a LEFT OUTER JOIN part to the query.
919
     * @param string|array $table the table to be joined.
920
     *
921
     * Use a string to represent the name of the table to be joined.
922
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
923
     * The method will automatically quote the table name unless it contains some parenthesis
924
     * (which means the table is given as a sub-query or DB expression).
925
     *
926
     * Use an array to represent joining with a sub-query. The array must contain only one element.
927
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
928
     * represents the alias for the sub-query.
929
     *
930
     * @param string|array $on the join condition that should appear in the ON part.
931
     * Please refer to [[join()]] on how to specify this parameter.
932
     * @param array $params the parameters (name => value) to be bound to the query
933
     * @return $this the query object itself
934
     */
935 3
    public function leftJoin($table, $on = '', $params = [])
936
    {
937 3
        $this->join[] = ['LEFT JOIN', $table, $on];
938 3
        return $this->addParams($params);
939
    }
940
941
    /**
942
     * Appends a RIGHT OUTER JOIN part to the query.
943
     * @param string|array $table the table to be joined.
944
     *
945
     * Use a string to represent the name of the table to be joined.
946
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
947
     * The method will automatically quote the table name unless it contains some parenthesis
948
     * (which means the table is given as a sub-query or DB expression).
949
     *
950
     * Use an array to represent joining with a sub-query. The array must contain only one element.
951
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
952
     * represents the alias for the sub-query.
953
     *
954
     * @param string|array $on the join condition that should appear in the ON part.
955
     * Please refer to [[join()]] on how to specify this parameter.
956
     * @param array $params the parameters (name => value) to be bound to the query
957
     * @return $this the query object itself
958
     */
959
    public function rightJoin($table, $on = '', $params = [])
960
    {
961
        $this->join[] = ['RIGHT JOIN', $table, $on];
962
        return $this->addParams($params);
963
    }
964
965
    /**
966
     * Sets the GROUP BY part of the query.
967
     * @param string|array|ExpressionInterface $columns the columns to be grouped by.
968
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
969
     * The method will automatically quote the column names unless a column contains some parenthesis
970
     * (which means the column contains a DB expression).
971
     *
972
     * Note that if your group-by is an expression containing commas, you should always use an array
973
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
974
     * the group-by columns.
975
     *
976
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
977
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
978
     * @return $this the query object itself
979
     * @see addGroupBy()
980
     */
981 24
    public function groupBy($columns)
982
    {
983 24
        if ($columns instanceof ExpressionInterface) {
984 3
            $columns = [$columns];
985 24
        } elseif (!is_array($columns)) {
986 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
987
        }
988 24
        $this->groupBy = $columns;
989 24
        return $this;
990
    }
991
992
    /**
993
     * Adds additional group-by columns to the existing ones.
994
     * @param string|array $columns additional columns to be grouped by.
995
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
996
     * The method will automatically quote the column names unless a column contains some parenthesis
997
     * (which means the column contains a DB expression).
998
     *
999
     * Note that if your group-by is an expression containing commas, you should always use an array
1000
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1001
     * the group-by columns.
1002
     *
1003
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1004
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1005
     * @return $this the query object itself
1006
     * @see groupBy()
1007
     */
1008 3
    public function addGroupBy($columns)
1009
    {
1010 3
        if ($columns instanceof ExpressionInterface) {
1011
            $columns = [$columns];
1012 3
        } elseif (!is_array($columns)) {
1013 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1014
        }
1015 3
        if ($this->groupBy === null) {
1016
            $this->groupBy = $columns;
1017
        } else {
1018 3
            $this->groupBy = array_merge($this->groupBy, $columns);
1019
        }
1020
1021 3
        return $this;
1022
    }
1023
1024
    /**
1025
     * Sets the HAVING part of the query.
1026
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1027
     * Please refer to [[where()]] on how to specify this parameter.
1028
     * @param array $params the parameters (name => value) to be bound to the query.
1029
     * @return $this the query object itself
1030
     * @see andHaving()
1031
     * @see orHaving()
1032
     */
1033 10
    public function having($condition, $params = [])
1034
    {
1035 10
        $this->having = $condition;
1036 10
        $this->addParams($params);
1037 10
        return $this;
1038
    }
1039
1040
    /**
1041
     * Adds an additional HAVING condition to the existing one.
1042
     * The new condition and the existing one will be joined using the `AND` operator.
1043
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1044
     * on how to specify this parameter.
1045
     * @param array $params the parameters (name => value) to be bound to the query.
1046
     * @return $this the query object itself
1047
     * @see having()
1048
     * @see orHaving()
1049
     */
1050 3
    public function andHaving($condition, $params = [])
1051
    {
1052 3
        if ($this->having === null) {
1053
            $this->having = $condition;
1054
        } else {
1055 3
            $this->having = ['and', $this->having, $condition];
1056
        }
1057 3
        $this->addParams($params);
1058 3
        return $this;
1059
    }
1060
1061
    /**
1062
     * Adds an additional HAVING condition to the existing one.
1063
     * The new condition and the existing one will be joined using the `OR` operator.
1064
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1065
     * on how to specify this parameter.
1066
     * @param array $params the parameters (name => value) to be bound to the query.
1067
     * @return $this the query object itself
1068
     * @see having()
1069
     * @see andHaving()
1070
     */
1071 3
    public function orHaving($condition, $params = [])
1072
    {
1073 3
        if ($this->having === null) {
1074
            $this->having = $condition;
1075
        } else {
1076 3
            $this->having = ['or', $this->having, $condition];
1077
        }
1078 3
        $this->addParams($params);
1079 3
        return $this;
1080
    }
1081
1082
    /**
1083
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1084
     *
1085
     * This method is similar to [[having()]]. The main difference is that this method will
1086
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1087
     * for building query conditions based on filter values entered by users.
1088
     *
1089
     * The following code shows the difference between this method and [[having()]]:
1090
     *
1091
     * ```php
1092
     * // HAVING `age`=:age
1093
     * $query->filterHaving(['name' => null, 'age' => 20]);
1094
     * // HAVING `age`=:age
1095
     * $query->having(['age' => 20]);
1096
     * // HAVING `name` IS NULL AND `age`=:age
1097
     * $query->having(['name' => null, 'age' => 20]);
1098
     * ```
1099
     *
1100
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1101
     *
1102
     * @param array $condition the conditions that should be put in the HAVING part.
1103
     * See [[having()]] on how to specify this parameter.
1104
     * @return $this the query object itself
1105
     * @see having()
1106
     * @see andFilterHaving()
1107
     * @see orFilterHaving()
1108
     * @since 2.0.11
1109
     */
1110 6
    public function filterHaving(array $condition)
1111
    {
1112 6
        $condition = $this->filterCondition($condition);
1113 6
        if ($condition !== []) {
1114 6
            $this->having($condition);
1115
        }
1116
1117 6
        return $this;
1118
    }
1119
1120
    /**
1121
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1122
     * The new condition and the existing one will be joined using the `AND` operator.
1123
     *
1124
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1125
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1126
     * for building query conditions based on filter values entered by users.
1127
     *
1128
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1129
     * on how to specify this parameter.
1130
     * @return $this the query object itself
1131
     * @see filterHaving()
1132
     * @see orFilterHaving()
1133
     * @since 2.0.11
1134
     */
1135 6
    public function andFilterHaving(array $condition)
1136
    {
1137 6
        $condition = $this->filterCondition($condition);
1138 6
        if ($condition !== []) {
1139
            $this->andHaving($condition);
1140
        }
1141
1142 6
        return $this;
1143
    }
1144
1145
    /**
1146
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1147
     * The new condition and the existing one will be joined using the `OR` operator.
1148
     *
1149
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1150
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1151
     * for building query conditions based on filter values entered by users.
1152
     *
1153
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1154
     * on how to specify this parameter.
1155
     * @return $this the query object itself
1156
     * @see filterHaving()
1157
     * @see andFilterHaving()
1158
     * @since 2.0.11
1159
     */
1160 6
    public function orFilterHaving(array $condition)
1161
    {
1162 6
        $condition = $this->filterCondition($condition);
1163 6
        if ($condition !== []) {
1164
            $this->orHaving($condition);
1165
        }
1166
1167 6
        return $this;
1168
    }
1169
1170
    /**
1171
     * Appends a SQL statement using UNION operator.
1172
     * @param string|Query $sql the SQL statement to be appended using UNION
1173
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1174
     * @return $this the query object itself
1175
     */
1176 10
    public function union($sql, $all = false)
1177
    {
1178 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1179 10
        return $this;
1180
    }
1181
1182
    /**
1183
     * Sets the parameters to be bound to the query.
1184
     * @param array $params list of query parameter values indexed by parameter placeholders.
1185
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1186
     * @return $this the query object itself
1187
     * @see addParams()
1188
     */
1189 6
    public function params($params)
1190
    {
1191 6
        $this->params = $params;
1192 6
        return $this;
1193
    }
1194
1195
    /**
1196
     * Adds additional parameters to be bound to the query.
1197
     * @param array $params list of query parameter values indexed by parameter placeholders.
1198
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1199
     * @return $this the query object itself
1200
     * @see params()
1201
     */
1202 1001
    public function addParams($params)
1203
    {
1204 1001
        if (!empty($params)) {
1205 74
            if (empty($this->params)) {
1206 74
                $this->params = $params;
1207
            } else {
1208 6
                foreach ($params as $name => $value) {
1209 6
                    if (is_int($name)) {
1210
                        $this->params[] = $value;
1211
                    } else {
1212 6
                        $this->params[$name] = $value;
1213
                    }
1214
                }
1215
            }
1216
        }
1217
1218 1001
        return $this;
1219
    }
1220
1221
    /**
1222
     * Enables query cache for this Query.
1223
     * @param int|true $duration the number of seconds that query results can remain valid in cache.
1224
     * Use 0 to indicate that the cached data will never expire.
1225
     * Use a negative number to indicate that query cache should not be used.
1226
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1227
     * Defaults to `true`.
1228
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached result.
1229
     * @return $this the Query object itself
1230
     * @since 2.0.14
1231
     */
1232 3
    public function cache($duration = true, $dependency = null)
1233
    {
1234 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...
1235 3
        $this->queryCacheDependency = $dependency;
1236 3
        return $this;
1237
    }
1238
1239
    /**
1240
     * Disables query cache for this Query.
1241
     * @return $this the Query object itself
1242
     * @since 2.0.14
1243
     */
1244 3
    public function noCache()
1245
    {
1246 3
        $this->queryCacheDuration = -1;
1247 3
        return $this;
1248
    }
1249
1250
    /**
1251
     * Sets $command cache, if this query has enabled caching.
1252
     *
1253
     * @param Command $command
1254
     * @return Command
1255
     * @since 2.0.14
1256
     */
1257 744
    protected function setCommandCache($command)
1258
    {
1259 744
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1260 3
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1261 3
            $command->cache($duration, $this->queryCacheDependency);
1262
        }
1263
1264 744
        return $command;
1265
    }
1266
1267
    /**
1268
     * Creates a new Query object and copies its property values from an existing one.
1269
     * The properties being copies are the ones to be used by query builders.
1270
     * @param Query $from the source query object
1271
     * @return Query the new Query object
1272
     */
1273 384
    public static function create($from)
1274
    {
1275 384
        return new self([
1276 384
            'where' => $from->where,
1277 384
            'limit' => $from->limit,
1278 384
            'offset' => $from->offset,
1279 384
            'orderBy' => $from->orderBy,
1280 384
            'indexBy' => $from->indexBy,
1281 384
            'select' => $from->select,
1282 384
            'selectOption' => $from->selectOption,
1283 384
            'distinct' => $from->distinct,
1284 384
            'from' => $from->from,
1285 384
            'groupBy' => $from->groupBy,
1286 384
            'join' => $from->join,
1287 384
            'having' => $from->having,
1288 384
            'union' => $from->union,
1289 384
            'params' => $from->params,
1290
        ]);
1291
    }
1292
1293
    /**
1294
     * Returns the SQL representation of Query
1295
     * @return string
1296
     */
1297
    public function __toString()
1298
    {
1299
        return serialize($this);
1300
    }
1301
}
1302