Completed
Push — fix-numbervalidator-comma-deci... ( 08054b...a7f0a3 )
by Alexander
40:41 queued 37:41
created

Query::addParams()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0909

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
ccs 11
cts 13
cp 0.8462
cc 5
eloc 11
nc 3
nop 1
crap 5.0909
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
13
/**
14
 * Query represents a SELECT SQL statement in a way that is independent of DBMS.
15
 *
16
 * Query provides a set of methods to facilitate the specification of different clauses
17
 * in a SELECT statement. These methods can be chained together.
18
 *
19
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
20
 * used to perform/execute the DB query against a database.
21
 *
22
 * For example,
23
 *
24
 * ```php
25
 * $query = new Query;
26
 * // compose the query
27
 * $query->select('id, name')
28
 *     ->from('user')
29
 *     ->limit(10);
30
 * // build and execute the query
31
 * $rows = $query->all();
32
 * // alternatively, you can create DB command and execute it
33
 * $command = $query->createCommand();
34
 * // $command->sql returns the actual SQL
35
 * $rows = $command->queryAll();
36
 * ```
37
 *
38
 * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
39
 *
40
 * 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).
41
 *
42
 * @author Qiang Xue <[email protected]>
43
 * @author Carsten Brandt <[email protected]>
44
 * @since 2.0
45
 */
46
class Query extends Component implements QueryInterface
47
{
48
    use QueryTrait;
49
50
    /**
51
     * @var array the columns being selected. For example, `['id', 'name']`.
52
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
53
     * @see select()
54
     */
55
    public $select;
56
    /**
57
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
58
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
59
     */
60
    public $selectOption;
61
    /**
62
     * @var bool whether to select distinct rows of data only. If this is set true,
63
     * the SELECT clause would be changed to SELECT DISTINCT.
64
     */
65
    public $distinct;
66
    /**
67
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
68
     * This is used to construct the FROM clause in a SQL statement.
69
     * @see from()
70
     */
71
    public $from;
72
    /**
73
     * @var array how to group the query results. For example, `['company', 'department']`.
74
     * This is used to construct the GROUP BY clause in a SQL statement.
75
     */
76
    public $groupBy;
77
    /**
78
     * @var array how to join with other tables. Each array element represents the specification
79
     * of one join which has the following structure:
80
     *
81
     * ```php
82
     * [$joinType, $tableName, $joinCondition]
83
     * ```
84
     *
85
     * For example,
86
     *
87
     * ```php
88
     * [
89
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
90
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
91
     * ]
92
     * ```
93
     */
94
    public $join;
95
    /**
96
     * @var string|array|Expression the condition to be applied in the GROUP BY clause.
97
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
98
     */
99
    public $having;
100
    /**
101
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
102
     * Each array element is an array of the following structure:
103
     *
104
     * - `query`: either a string or a [[Query]] object representing a query
105
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
106
     */
107
    public $union;
108
    /**
109
     * @var array list of query parameter values indexed by parameter placeholders.
110
     * For example, `[':name' => 'Dan', ':age' => 31]`.
111
     */
112
    public $params = [];
113
114
115
    /**
116
     * Creates a DB command that can be used to execute this query.
117
     * @param Connection $db the database connection used to generate the SQL statement.
118
     * If this parameter is not given, the `db` application component will be used.
119
     * @return Command the created DB command instance.
120
     */
121 161
    public function createCommand($db = null)
122
    {
123 161
        if ($db === null) {
124 13
            $db = Yii::$app->getDb();
125 13
        }
126 161
        list ($sql, $params) = $db->getQueryBuilder()->build($this);
127
128 161
        return $db->createCommand($sql, $params);
129
    }
130
131
    /**
132
     * Prepares for building SQL.
133
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
134
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
135
     * @param QueryBuilder $builder
136
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
137
     */
138 465
    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...
139
    {
140 465
        return $this;
141
    }
142
143
    /**
144
     * Starts a batch query.
145
     *
146
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
147
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
148
     * and can be traversed to retrieve the data in batches.
149
     *
150
     * For example,
151
     *
152
     * ```php
153
     * $query = (new Query)->from('user');
154
     * foreach ($query->batch() as $rows) {
155
     *     // $rows is an array of 100 or fewer rows from user table
156
     * }
157
     * ```
158
     *
159
     * @param int $batchSize the number of records to be fetched in each batch.
160
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
161
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
162
     * and can be traversed to retrieve the data in batches.
163
     */
164 6
    public function batch($batchSize = 100, $db = null)
165
    {
166 6
        return Yii::createObject([
167 6
            'class' => BatchQueryResult::className(),
168 6
            'query' => $this,
169 6
            'batchSize' => $batchSize,
170 6
            'db' => $db,
171 6
            'each' => false,
172 6
        ]);
173
    }
174
175
    /**
176
     * Starts a batch query and retrieves data row by row.
177
     * This method is similar to [[batch()]] except that in each iteration of the result,
178
     * only one row of data is returned. For example,
179
     *
180
     * ```php
181
     * $query = (new Query)->from('user');
182
     * foreach ($query->each() as $row) {
183
     * }
184
     * ```
185
     *
186
     * @param int $batchSize the number of records to be fetched in each batch.
187
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
188
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
189
     * and can be traversed to retrieve the data in batches.
190
     */
191 3
    public function each($batchSize = 100, $db = null)
192
    {
193 3
        return Yii::createObject([
194 3
            'class' => BatchQueryResult::className(),
195 3
            'query' => $this,
196 3
            'batchSize' => $batchSize,
197 3
            'db' => $db,
198 3
            'each' => true,
199 3
        ]);
200
    }
201
202
    /**
203
     * Executes the query and returns all results as an array.
204
     * @param Connection $db the database connection used to generate the SQL statement.
205
     * If this parameter is not given, the `db` application component will be used.
206
     * @return array the query results. If the query results in nothing, an empty array will be returned.
207
     */
208 280
    public function all($db = null)
209
    {
210 280
        if ($this->emulateExecution) {
211 9
            return [];
212
        }
213 274
        $rows = $this->createCommand($db)->queryAll();
214 274
        return $this->populate($rows);
215
    }
216
217
    /**
218
     * Converts the raw query results into the format as specified by this query.
219
     * This method is internally used to convert the data fetched from database
220
     * into the format as required by this query.
221
     * @param array $rows the raw query result from database
222
     * @return array the converted query result
223
     */
224 107
    public function populate($rows)
225
    {
226 107
        if ($this->indexBy === null) {
227 107
            return $rows;
228
        }
229 3
        $result = [];
230 3
        foreach ($rows as $row) {
231 3
            if (is_string($this->indexBy)) {
232 3
                $key = $row[$this->indexBy];
233 3
            } else {
234
                $key = call_user_func($this->indexBy, $row);
235
            }
236 3
            $result[$key] = $row;
237 3
        }
238 3
        return $result;
239
    }
240
241
    /**
242
     * Executes the query and returns a single row of result.
243
     * @param Connection $db the database connection used to generate the SQL statement.
244
     * If this parameter is not given, the `db` application component will be used.
245
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
246
     * results in nothing.
247
     */
248 303
    public function one($db = null)
249
    {
250 303
        if ($this->emulateExecution) {
251 6
            return false;
252
        }
253 297
        return $this->createCommand($db)->queryOne();
254
    }
255
256
    /**
257
     * Returns the query result as a scalar value.
258
     * The value returned will be the first column in the first row of the query results.
259
     * @param Connection $db the database connection used to generate the SQL statement.
260
     * If this parameter is not given, the `db` application component will be used.
261
     * @return string|null|false the value of the first column in the first row of the query result.
262
     * False is returned if the query result is empty.
263
     */
264 14
    public function scalar($db = null)
265
    {
266 14
        if ($this->emulateExecution) {
267 6
            return null;
268
        }
269 8
        return $this->createCommand($db)->queryScalar();
270
    }
271
272
    /**
273
     * Executes the query and returns the first column of the result.
274
     * @param Connection $db the database connection used to generate the SQL statement.
275
     * If this parameter is not given, the `db` application component will be used.
276
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
277
     */
278 24
    public function column($db = null)
279
    {
280 24
        if ($this->emulateExecution) {
281 6
            return [];
282
        }
283
284 18
        if ($this->indexBy === null) {
285 18
            return $this->createCommand($db)->queryColumn();
286
        }
287
288 3
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
289 3
            $this->select[] = $this->indexBy;
290 3
        }
291 3
        $rows = $this->createCommand($db)->queryAll();
292 3
        $results = [];
293 3
        foreach ($rows as $row) {
294 3
            $value = reset($row);
295
296 3
            if ($this->indexBy instanceof \Closure) {
297 3
                $results[call_user_func($this->indexBy, $row)] = $value;
298 3
            } else {
299 3
                $results[$row[$this->indexBy]] = $value;
300
            }
301 3
        }
302 3
        return $results;
303
    }
304
305
    /**
306
     * Returns the number of records.
307
     * @param string $q the COUNT expression. Defaults to '*'.
308
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
309
     * @param Connection $db the database connection used to generate the SQL statement.
310
     * If this parameter is not given (or null), the `db` application component will be used.
311
     * @return int|string number of records. The result may be a string depending on the
312
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
313
     */
314 78
    public function count($q = '*', $db = null)
315
    {
316 78
        if ($this->emulateExecution) {
317 6
            return 0;
318
        }
319 78
        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 319 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...
320
    }
321
322
    /**
323
     * Returns the sum of the specified column values.
324
     * @param string $q the column name or expression.
325
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
326
     * @param Connection $db the database connection used to generate the SQL statement.
327
     * If this parameter is not given, the `db` application component will be used.
328
     * @return mixed the sum of the specified column values.
329
     */
330 9
    public function sum($q, $db = null)
331
    {
332 9
        if ($this->emulateExecution) {
333 6
            return 0;
334
        }
335 3
        return $this->queryScalar("SUM($q)", $db);
336
    }
337
338
    /**
339
     * Returns the average of the specified column values.
340
     * @param string $q the column name or expression.
341
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
342
     * @param Connection $db the database connection used to generate the SQL statement.
343
     * If this parameter is not given, the `db` application component will be used.
344
     * @return mixed the average of the specified column values.
345
     */
346 9
    public function average($q, $db = null)
347
    {
348 9
        if ($this->emulateExecution) {
349 6
            return 0;
350
        }
351 3
        return $this->queryScalar("AVG($q)", $db);
352
    }
353
354
    /**
355
     * Returns the minimum of the specified column values.
356
     * @param string $q the column name or expression.
357
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
358
     * @param Connection $db the database connection used to generate the SQL statement.
359
     * If this parameter is not given, the `db` application component will be used.
360
     * @return mixed the minimum of the specified column values.
361
     */
362 9
    public function min($q, $db = null)
363
    {
364 9
        return $this->queryScalar("MIN($q)", $db);
365
    }
366
367
    /**
368
     * Returns the maximum 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 maximum of the specified column values.
374
     */
375 9
    public function max($q, $db = null)
376
    {
377 9
        return $this->queryScalar("MAX($q)", $db);
378
    }
379
380
    /**
381
     * Returns a value indicating whether the query result contains any row of data.
382
     * @param Connection $db the database connection used to generate the SQL statement.
383
     * If this parameter is not given, the `db` application component will be used.
384
     * @return bool whether the query result contains any row of data.
385
     */
386 57
    public function exists($db = null)
387
    {
388 57
        if ($this->emulateExecution) {
389 6
            return false;
390
        }
391 51
        $command = $this->createCommand($db);
392 51
        $params = $command->params;
393 51
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
394 51
        $command->bindValues($params);
395 51
        return (bool) $command->queryScalar();
396
    }
397
398
    /**
399
     * Queries a scalar value by setting [[select]] first.
400
     * Restores the value of select to make this query reusable.
401
     * @param string|Expression $selectExpression
402
     * @param Connection|null $db
403
     * @return bool|string
404
     */
405 78
    protected function queryScalar($selectExpression, $db)
406
    {
407 78
        if ($this->emulateExecution) {
408 6
            return null;
409
        }
410
411 78
        $select = $this->select;
412 78
        $limit = $this->limit;
413 78
        $offset = $this->offset;
414
415 78
        $this->select = [$selectExpression];
416 78
        $this->limit = null;
417 78
        $this->offset = null;
418 78
        $command = $this->createCommand($db);
419
420 78
        $this->select = $select;
421 78
        $this->limit = $limit;
422 78
        $this->offset = $offset;
423
424 78
        if (empty($this->groupBy) && empty($this->having) && empty($this->union) && !$this->distinct) {
425 77
            return $command->queryScalar();
426
        } else {
427 7
            return (new Query)->select([$selectExpression])
428 7
                ->from(['c' => $this])
429 7
                ->createCommand($command->db)
430 7
                ->queryScalar();
431
        }
432
    }
433
434
    /**
435
     * Sets the SELECT part of the query.
436
     * @param string|array|Expression $columns the columns to be selected.
437
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
438
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
439
     * The method will automatically quote the column names unless a column contains some parenthesis
440
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
441
     * an [[Expression]] object.
442
     *
443
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
444
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
445
     *
446
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
447
     * does not need alias, do not use a string key).
448
     *
449
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
450
     * as a `Query` instance representing the sub-query.
451
     *
452
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
453
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
454
     * @return $this the query object itself
455
     */
456 209
    public function select($columns, $option = null)
457
    {
458 209
        if ($columns instanceof Expression) {
459 3
            $columns = [$columns];
460 209
        } elseif (!is_array($columns)) {
461 68
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
462 68
        }
463 209
        $this->select = $columns;
464 209
        $this->selectOption = $option;
465 209
        return $this;
466
    }
467
468
    /**
469
     * Add more columns to the SELECT part of the query.
470
     *
471
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
472
     * if you want to select all remaining columns too:
473
     *
474
     * ```php
475
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
476
     * ```
477
     *
478
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
479
     * details about the format of this parameter.
480
     * @return $this the query object itself
481
     * @see select()
482
     */
483 9
    public function addSelect($columns)
484
    {
485 9
        if ($columns instanceof Expression) {
486 3
            $columns = [$columns];
487 9
        } elseif (!is_array($columns)) {
488 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
489 3
        }
490 9
        if ($this->select === null) {
491 3
            $this->select = $columns;
492 3
        } else {
493 9
            $this->select = array_merge($this->select, $columns);
494
        }
495 9
        return $this;
496
    }
497
498
    /**
499
     * Sets the value indicating whether to SELECT DISTINCT or not.
500
     * @param bool $value whether to SELECT DISTINCT or not.
501
     * @return $this the query object itself
502
     */
503 6
    public function distinct($value = true)
504
    {
505 6
        $this->distinct = $value;
506 6
        return $this;
507
    }
508
509
    /**
510
     * Sets the FROM part of the query.
511
     * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
512
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
513
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
514
     * The method will automatically quote the table names unless it contains some parenthesis
515
     * (which means the table is given as a sub-query or DB expression).
516
     *
517
     * When the tables are specified as an array, you may also use the array keys as the table aliases
518
     * (if a table does not need alias, do not use a string key).
519
     *
520
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
521
     * as the alias for the sub-query.
522
     *
523
     * Here are some examples:
524
     *
525
     * ```php
526
     * // SELECT * FROM  `user` `u`, `profile`;
527
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
528
     *
529
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
530
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
531
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
532
     *
533
     * // subquery can also be a string with plain SQL wrapped in parenthesis
534
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
535
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
536
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
537
     * ```
538
     *
539
     * @return $this the query object itself
540
     */
541 206
    public function from($tables)
542
    {
543 206
        if (!is_array($tables)) {
544 187
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
545 187
        }
546 206
        $this->from = $tables;
547 206
        return $this;
548
    }
549
550
    /**
551
     * Sets the WHERE part of the query.
552
     *
553
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
554
     * specifying the values to be bound to the query.
555
     *
556
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
557
     *
558
     * @inheritdoc
559
     *
560
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
561
     * @param array $params the parameters (name => value) to be bound to the query.
562
     * @return $this the query object itself
563
     * @see andWhere()
564
     * @see orWhere()
565
     * @see QueryInterface::where()
566
     */
567 470
    public function where($condition, $params = [])
568
    {
569 470
        $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. 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...
570 470
        $this->addParams($params);
571 470
        return $this;
572
    }
573
574
    /**
575
     * Adds an additional WHERE condition to the existing one.
576
     * The new condition and the existing one will be joined using the `AND` operator.
577
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
578
     * on how to specify this parameter.
579
     * @param array $params the parameters (name => value) to be bound to the query.
580
     * @return $this the query object itself
581
     * @see where()
582
     * @see orWhere()
583
     */
584 263
    public function andWhere($condition, $params = [])
585
    {
586 263
        if ($this->where === null) {
587 237
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. 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...
588 263
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
589 15
            $this->where[] = $condition;
590 15
        } else {
591 74
            $this->where = ['and', $this->where, $condition];
592
        }
593 263
        $this->addParams($params);
594 263
        return $this;
595
    }
596
597
    /**
598
     * Adds an additional WHERE condition to the existing one.
599
     * The new condition and the existing one will be joined using the `OR` operator.
600
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
601
     * on how to specify this parameter.
602
     * @param array $params the parameters (name => value) to be bound to the query.
603
     * @return $this the query object itself
604
     * @see where()
605
     * @see andWhere()
606
     */
607 6
    public function orWhere($condition, $params = [])
608
    {
609 6
        if ($this->where === null) {
610
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\Expression>. 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...
611
        } else {
612 6
            $this->where = ['or', $this->where, $condition];
613
        }
614 6
        $this->addParams($params);
615 6
        return $this;
616
    }
617
618
    /**
619
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
620
     *
621
     * It adds an additional WHERE condition for the given field and determines the comparison operator
622
     * based on the first few characters of the given value.
623
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
624
     * The new condition and the existing one will be joined using the `AND` operator.
625
     *
626
     * The comparison operator is intelligently determined based on the first few characters in the given value.
627
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
628
     *
629
     * - `<`: the column must be less than the given value.
630
     * - `>`: the column must be greater than the given value.
631
     * - `<=`: the column must be less than or equal to the given value.
632
     * - `>=`: the column must be greater than or equal to the given value.
633
     * - `<>`: the column must not be the same as the given value.
634
     * - `=`: the column must be equal to the given value.
635
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
636
     *
637
     * @param string $name the column name.
638
     * @param string $value the column value optionally prepended with the comparison operator.
639
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
640
     * Defaults to `=`, performing an exact match.
641
     * @return $this The query object itself
642
     * @since 2.0.8
643
     */
644 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
645
    {
646 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
647 3
            $operator = $matches[1];
648 3
            $value = substr($value, strlen($operator));
649 3
        } else {
650 3
            $operator = $defaultOperator;
651
        }
652 3
        return $this->andFilterWhere([$operator, $name, $value]);
653
    }
654
655
    /**
656
     * Appends a JOIN part to the query.
657
     * The first parameter specifies what type of join it is.
658
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
659
     * @param string|array $table the table to be joined.
660
     *
661
     * Use a string to represent the name of the table to be joined.
662
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
663
     * The method will automatically quote the table name unless it contains some parenthesis
664
     * (which means the table is given as a sub-query or DB expression).
665
     *
666
     * Use an array to represent joining with a sub-query. The array must contain only one element.
667
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
668
     * represents the alias for the sub-query.
669
     *
670
     * @param string|array $on the join condition that should appear in the ON part.
671
     * Please refer to [[where()]] on how to specify this parameter.
672
     *
673
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
674
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
675
     * match the `post.author_id` column value against the string `'user.id'`.
676
     * It is recommended to use the string syntax here which is more suited for a join:
677
     *
678
     * ```php
679
     * 'post.author_id = user.id'
680
     * ```
681
     *
682
     * @param array $params the parameters (name => value) to be bound to the query.
683
     * @return $this the query object itself
684
     */
685 36
    public function join($type, $table, $on = '', $params = [])
686
    {
687 36
        $this->join[] = [$type, $table, $on];
688 36
        return $this->addParams($params);
689
    }
690
691
    /**
692
     * Appends an INNER JOIN part to the query.
693
     * @param string|array $table the table to be joined.
694
     *
695
     * Use a string to represent the name of the table to be joined.
696
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
697
     * The method will automatically quote the table name unless it contains some parenthesis
698
     * (which means the table is given as a sub-query or DB expression).
699
     *
700
     * Use an array to represent joining with a sub-query. The array must contain only one element.
701
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
702
     * represents the alias for the sub-query.
703
     *
704
     * @param string|array $on the join condition that should appear in the ON part.
705
     * Please refer to [[join()]] on how to specify this parameter.
706
     * @param array $params the parameters (name => value) to be bound to the query.
707
     * @return $this the query object itself
708
     */
709
    public function innerJoin($table, $on = '', $params = [])
710
    {
711
        $this->join[] = ['INNER JOIN', $table, $on];
712
        return $this->addParams($params);
713
    }
714
715
    /**
716
     * Appends a LEFT OUTER JOIN part to the query.
717
     * @param string|array $table the table to be joined.
718
     *
719
     * Use a string to represent the name of the table to be joined.
720
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
721
     * The method will automatically quote the table name unless it contains some parenthesis
722
     * (which means the table is given as a sub-query or DB expression).
723
     *
724
     * Use an array to represent joining with a sub-query. The array must contain only one element.
725
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
726
     * represents the alias for the sub-query.
727
     *
728
     * @param string|array $on the join condition that should appear in the ON part.
729
     * Please refer to [[join()]] on how to specify this parameter.
730
     * @param array $params the parameters (name => value) to be bound to the query
731
     * @return $this the query object itself
732
     */
733 3
    public function leftJoin($table, $on = '', $params = [])
734
    {
735 3
        $this->join[] = ['LEFT JOIN', $table, $on];
736 3
        return $this->addParams($params);
737
    }
738
739
    /**
740
     * Appends a RIGHT OUTER JOIN part to the query.
741
     * @param string|array $table the table to be joined.
742
     *
743
     * Use a string to represent the name of the table to be joined.
744
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
745
     * The method will automatically quote the table name unless it contains some parenthesis
746
     * (which means the table is given as a sub-query or DB expression).
747
     *
748
     * Use an array to represent joining with a sub-query. The array must contain only one element.
749
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
750
     * represents the alias for the sub-query.
751
     *
752
     * @param string|array $on the join condition that should appear in the ON part.
753
     * Please refer to [[join()]] on how to specify this parameter.
754
     * @param array $params the parameters (name => value) to be bound to the query
755
     * @return $this the query object itself
756
     */
757
    public function rightJoin($table, $on = '', $params = [])
758
    {
759
        $this->join[] = ['RIGHT JOIN', $table, $on];
760
        return $this->addParams($params);
761
    }
762
763
    /**
764
     * Sets the GROUP BY part of the query.
765
     * @param string|array|Expression $columns the columns to be grouped by.
766
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
767
     * The method will automatically quote the column names unless a column contains some parenthesis
768
     * (which means the column contains a DB expression).
769
     *
770
     * Note that if your group-by is an expression containing commas, you should always use an array
771
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
772
     * the group-by columns.
773
     *
774
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
775
     * @return $this the query object itself
776
     * @see addGroupBy()
777
     */
778 12
    public function groupBy($columns)
779
    {
780 12
        if ($columns instanceof Expression) {
781 3
            $columns = [$columns];
782 12
        } elseif (!is_array($columns)) {
783 12
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
784 12
        }
785 12
        $this->groupBy = $columns;
786 12
        return $this;
787
    }
788
789
    /**
790
     * Adds additional group-by columns to the existing ones.
791
     * @param string|array $columns additional columns to be grouped by.
792
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
793
     * The method will automatically quote the column names unless a column contains some parenthesis
794
     * (which means the column contains a DB expression).
795
     *
796
     * Note that if your group-by is an expression containing commas, you should always use an array
797
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
798
     * the group-by columns.
799
     *
800
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
801
     * @return $this the query object itself
802
     * @see groupBy()
803
     */
804 3
    public function addGroupBy($columns)
805
    {
806 3
        if ($columns instanceof Expression) {
807
            $columns = [$columns];
808 3
        } elseif (!is_array($columns)) {
809 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
810 3
        }
811 3
        if ($this->groupBy === null) {
812
            $this->groupBy = $columns;
813
        } else {
814 3
            $this->groupBy = array_merge($this->groupBy, $columns);
815
        }
816 3
        return $this;
817
    }
818
819
    /**
820
     * Sets the HAVING part of the query.
821
     * @param string|array|Expression $condition the conditions to be put after HAVING.
822
     * Please refer to [[where()]] on how to specify this parameter.
823
     * @param array $params the parameters (name => value) to be bound to the query.
824
     * @return $this the query object itself
825
     * @see andHaving()
826
     * @see orHaving()
827
     */
828 10
    public function having($condition, $params = [])
829
    {
830 10
        $this->having = $condition;
831 10
        $this->addParams($params);
832 10
        return $this;
833
    }
834
835
    /**
836
     * Adds an additional HAVING condition to the existing one.
837
     * The new condition and the existing one will be joined using the `AND` operator.
838
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
839
     * on how to specify this parameter.
840
     * @param array $params the parameters (name => value) to be bound to the query.
841
     * @return $this the query object itself
842
     * @see having()
843
     * @see orHaving()
844
     */
845 3
    public function andHaving($condition, $params = [])
846
    {
847 3
        if ($this->having === null) {
848
            $this->having = $condition;
849
        } else {
850 3
            $this->having = ['and', $this->having, $condition];
851
        }
852 3
        $this->addParams($params);
853 3
        return $this;
854
    }
855
856
    /**
857
     * Adds an additional HAVING condition to the existing one.
858
     * The new condition and the existing one will be joined using the `OR` operator.
859
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
860
     * on how to specify this parameter.
861
     * @param array $params the parameters (name => value) to be bound to the query.
862
     * @return $this the query object itself
863
     * @see having()
864
     * @see andHaving()
865
     */
866 3
    public function orHaving($condition, $params = [])
867
    {
868 3
        if ($this->having === null) {
869
            $this->having = $condition;
870
        } else {
871 3
            $this->having = ['or', $this->having, $condition];
872
        }
873 3
        $this->addParams($params);
874 3
        return $this;
875
    }
876
877
    /**
878
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
879
     *
880
     * This method is similar to [[having()]]. The main difference is that this method will
881
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
882
     * for building query conditions based on filter values entered by users.
883
     *
884
     * The following code shows the difference between this method and [[having()]]:
885
     *
886
     * ```php
887
     * // HAVING `age`=:age
888
     * $query->filterHaving(['name' => null, 'age' => 20]);
889
     * // HAVING `age`=:age
890
     * $query->having(['age' => 20]);
891
     * // HAVING `name` IS NULL AND `age`=:age
892
     * $query->having(['name' => null, 'age' => 20]);
893
     * ```
894
     *
895
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
896
     *
897
     * @param array $condition the conditions that should be put in the HAVING part.
898
     * See [[having()]] on how to specify this parameter.
899
     * @return $this the query object itself
900
     * @see having()
901
     * @see andFilterHaving()
902
     * @see orFilterHaving()
903
     * @since 2.0.11
904
     */
905 6
    public function filterHaving(array $condition)
906
    {
907 6
        $condition = $this->filterCondition($condition);
908 6
        if ($condition !== []) {
909 6
            $this->having($condition);
910 6
        }
911 6
        return $this;
912
    }
913
914
    /**
915
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
916
     * The new condition and the existing one will be joined using the `AND` operator.
917
     *
918
     * This method is similar to [[andHaving()]]. The main difference is that this method will
919
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
920
     * for building query conditions based on filter values entered by users.
921
     *
922
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
923
     * on how to specify this parameter.
924
     * @return $this the query object itself
925
     * @see filterHaving()
926
     * @see orFilterHaving()
927
     * @since 2.0.11
928
     */
929 6
    public function andFilterHaving(array $condition)
930
    {
931 6
        $condition = $this->filterCondition($condition);
932 6
        if ($condition !== []) {
933
            $this->andHaving($condition);
934
        }
935 6
        return $this;
936
    }
937
938
    /**
939
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
940
     * The new condition and the existing one will be joined using the `OR` operator.
941
     *
942
     * This method is similar to [[orHaving()]]. The main difference is that this method will
943
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
944
     * for building query conditions based on filter values entered by users.
945
     *
946
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
947
     * on how to specify this parameter.
948
     * @return $this the query object itself
949
     * @see filterHaving()
950
     * @see andFilterHaving()
951
     * @since 2.0.11
952
     */
953 6
    public function orFilterHaving(array $condition)
954
    {
955 6
        $condition = $this->filterCondition($condition);
956 6
        if ($condition !== []) {
957
            $this->orHaving($condition);
958
        }
959 6
        return $this;
960
    }
961
962
    /**
963
     * Appends a SQL statement using UNION operator.
964
     * @param string|Query $sql the SQL statement to be appended using UNION
965
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
966
     * @return $this the query object itself
967
     */
968 10
    public function union($sql, $all = false)
969
    {
970 10
        $this->union[] = ['query' => $sql, 'all' => $all];
971 10
        return $this;
972
    }
973
974
    /**
975
     * Sets the parameters to be bound to the query.
976
     * @param array $params list of query parameter values indexed by parameter placeholders.
977
     * For example, `[':name' => 'Dan', ':age' => 31]`.
978
     * @return $this the query object itself
979
     * @see addParams()
980
     */
981 6
    public function params($params)
982
    {
983 6
        $this->params = $params;
984 6
        return $this;
985
    }
986
987
    /**
988
     * Adds additional parameters to be bound to the query.
989
     * @param array $params list of query parameter values indexed by parameter placeholders.
990
     * For example, `[':name' => 'Dan', ':age' => 31]`.
991
     * @return $this the query object itself
992
     * @see params()
993
     */
994 675
    public function addParams($params)
995
    {
996 675
        if (!empty($params)) {
997 44
            if (empty($this->params)) {
998 44
                $this->params = $params;
999 44
            } else {
1000 6
                foreach ($params as $name => $value) {
1001 6
                    if (is_int($name)) {
1002
                        $this->params[] = $value;
1003
                    } else {
1004 6
                        $this->params[$name] = $value;
1005
                    }
1006 6
                }
1007
            }
1008 44
        }
1009 675
        return $this;
1010
    }
1011
1012
    /**
1013
     * Creates a new Query object and copies its property values from an existing one.
1014
     * The properties being copies are the ones to be used by query builders.
1015
     * @param Query $from the source query object
1016
     * @return Query the new Query object
1017
     */
1018 312
    public static function create($from)
1019
    {
1020 312
        return new self([
1021 312
            'where' => $from->where,
1022 312
            'limit' => $from->limit,
1023 312
            'offset' => $from->offset,
1024 312
            'orderBy' => $from->orderBy,
1025 312
            'indexBy' => $from->indexBy,
1026 312
            'select' => $from->select,
1027 312
            'selectOption' => $from->selectOption,
1028 312
            'distinct' => $from->distinct,
1029 312
            'from' => $from->from,
1030 312
            'groupBy' => $from->groupBy,
1031 312
            'join' => $from->join,
1032 312
            'having' => $from->having,
1033 312
            'union' => $from->union,
1034 312
            'params' => $from->params,
1035 312
        ]);
1036
    }
1037
}
1038