Completed
Push — cache-closure ( 7d9053...380edd )
by Dmitry
35:54
created

Query::queryScalar()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 24
cts 24
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 25
nc 3
nop 2
crap 7
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 162
    public function createCommand($db = null)
122
    {
123 162
        if ($db === null) {
124 13
            $db = Yii::$app->getDb();
125 13
        }
126 162
        list ($sql, $params) = $db->getQueryBuilder()->build($this);
127
128 162
        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 466
    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 466
        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
        if (
425 78
            !$this->distinct
426 78
            && empty($this->groupBy)
427 78
            && empty($this->having)
428 78
            && empty($this->union)
429 78
            && empty($this->orderBy)
430 78
        ) {
431 77
            return $command->queryScalar();
432
        } else {
433 7
            return (new Query)->select([$selectExpression])
434 7
                ->from(['c' => $this])
435 7
                ->createCommand($command->db)
436 7
                ->queryScalar();
437
        }
438
    }
439
440
    /**
441
     * Sets the SELECT part of the query.
442
     * @param string|array|Expression $columns the columns to be selected.
443
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
444
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
445
     * The method will automatically quote the column names unless a column contains some parenthesis
446
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
447
     * an [[Expression]] object.
448
     *
449
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
450
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
451
     *
452
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
453
     * does not need alias, do not use a string key).
454
     *
455
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
456
     * as a `Query` instance representing the sub-query.
457
     *
458
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
459
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
460
     * @return $this the query object itself
461
     */
462 210
    public function select($columns, $option = null)
463
    {
464 210
        if ($columns instanceof Expression) {
465 3
            $columns = [$columns];
466 210
        } elseif (!is_array($columns)) {
467 68
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
468 68
        }
469 210
        $this->select = $columns;
470 210
        $this->selectOption = $option;
471 210
        return $this;
472
    }
473
474
    /**
475
     * Add more columns to the SELECT part of the query.
476
     *
477
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
478
     * if you want to select all remaining columns too:
479
     *
480
     * ```php
481
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
482
     * ```
483
     *
484
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
485
     * details about the format of this parameter.
486
     * @return $this the query object itself
487
     * @see select()
488
     */
489 9
    public function addSelect($columns)
490
    {
491 9
        if ($columns instanceof Expression) {
492 3
            $columns = [$columns];
493 9
        } elseif (!is_array($columns)) {
494 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
495 3
        }
496 9
        if ($this->select === null) {
497 3
            $this->select = $columns;
498 3
        } else {
499 9
            $this->select = array_merge($this->select, $columns);
500
        }
501 9
        return $this;
502
    }
503
504
    /**
505
     * Sets the value indicating whether to SELECT DISTINCT or not.
506
     * @param bool $value whether to SELECT DISTINCT or not.
507
     * @return $this the query object itself
508
     */
509 6
    public function distinct($value = true)
510
    {
511 6
        $this->distinct = $value;
512 6
        return $this;
513
    }
514
515
    /**
516
     * Sets the FROM part of the query.
517
     * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
518
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
519
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
520
     * The method will automatically quote the table names unless it contains some parenthesis
521
     * (which means the table is given as a sub-query or DB expression).
522
     *
523
     * When the tables are specified as an array, you may also use the array keys as the table aliases
524
     * (if a table does not need alias, do not use a string key).
525
     *
526
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
527
     * as the alias for the sub-query.
528
     *
529
     * Here are some examples:
530
     *
531
     * ```php
532
     * // SELECT * FROM  `user` `u`, `profile`;
533
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
534
     *
535
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
536
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
537
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
538
     *
539
     * // subquery can also be a string with plain SQL wrapped in parenthesis
540
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
541
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
542
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
543
     * ```
544
     *
545
     * @return $this the query object itself
546
     */
547 207
    public function from($tables)
548
    {
549 207
        if (!is_array($tables)) {
550 188
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
551 188
        }
552 207
        $this->from = $tables;
553 207
        return $this;
554
    }
555
556
    /**
557
     * Sets the WHERE part of the query.
558
     *
559
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
560
     * specifying the values to be bound to the query.
561
     *
562
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
563
     *
564
     * @inheritdoc
565
     *
566
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
567
     * @param array $params the parameters (name => value) to be bound to the query.
568
     * @return $this the query object itself
569
     * @see andWhere()
570
     * @see orWhere()
571
     * @see QueryInterface::where()
572
     */
573 471
    public function where($condition, $params = [])
574
    {
575 471
        $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...
576 471
        $this->addParams($params);
577 471
        return $this;
578
    }
579
580
    /**
581
     * Adds an additional WHERE condition to the existing one.
582
     * The new condition and the existing one will be joined using the `AND` operator.
583
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
584
     * on how to specify this parameter.
585
     * @param array $params the parameters (name => value) to be bound to the query.
586
     * @return $this the query object itself
587
     * @see where()
588
     * @see orWhere()
589
     */
590 264
    public function andWhere($condition, $params = [])
591
    {
592 264
        if ($this->where === null) {
593 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...
594 264
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
595 15
            $this->where[] = $condition;
596 15
        } else {
597 75
            $this->where = ['and', $this->where, $condition];
598
        }
599 264
        $this->addParams($params);
600 264
        return $this;
601
    }
602
603
    /**
604
     * Adds an additional WHERE condition to the existing one.
605
     * The new condition and the existing one will be joined using the `OR` operator.
606
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
607
     * on how to specify this parameter.
608
     * @param array $params the parameters (name => value) to be bound to the query.
609
     * @return $this the query object itself
610
     * @see where()
611
     * @see andWhere()
612
     */
613 6
    public function orWhere($condition, $params = [])
614
    {
615 6
        if ($this->where === null) {
616
            $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...
617
        } else {
618 6
            $this->where = ['or', $this->where, $condition];
619
        }
620 6
        $this->addParams($params);
621 6
        return $this;
622
    }
623
624
    /**
625
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
626
     *
627
     * It adds an additional WHERE condition for the given field and determines the comparison operator
628
     * based on the first few characters of the given value.
629
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
630
     * The new condition and the existing one will be joined using the `AND` operator.
631
     *
632
     * The comparison operator is intelligently determined based on the first few characters in the given value.
633
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
634
     *
635
     * - `<`: the column must be less than the given value.
636
     * - `>`: the column must be greater than the given value.
637
     * - `<=`: the column must be less than or equal to the given value.
638
     * - `>=`: the column must be greater than or equal to the given value.
639
     * - `<>`: the column must not be the same as the given value.
640
     * - `=`: the column must be equal to the given value.
641
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
642
     *
643
     * @param string $name the column name.
644
     * @param string $value the column value optionally prepended with the comparison operator.
645
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
646
     * Defaults to `=`, performing an exact match.
647
     * @return $this The query object itself
648
     * @since 2.0.8
649
     */
650 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
651
    {
652 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
653 3
            $operator = $matches[1];
654 3
            $value = substr($value, strlen($operator));
655 3
        } else {
656 3
            $operator = $defaultOperator;
657
        }
658 3
        return $this->andFilterWhere([$operator, $name, $value]);
659
    }
660
661
    /**
662
     * Appends a JOIN part to the query.
663
     * The first parameter specifies what type of join it is.
664
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
665
     * @param string|array $table the table to be joined.
666
     *
667
     * Use a string to represent the name of the table to be joined.
668
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
669
     * The method will automatically quote the table name unless it contains some parenthesis
670
     * (which means the table is given as a sub-query or DB expression).
671
     *
672
     * Use an array to represent joining with a sub-query. The array must contain only one element.
673
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
674
     * represents the alias for the sub-query.
675
     *
676
     * @param string|array $on the join condition that should appear in the ON part.
677
     * Please refer to [[where()]] on how to specify this parameter.
678
     *
679
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
680
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
681
     * match the `post.author_id` column value against the string `'user.id'`.
682
     * It is recommended to use the string syntax here which is more suited for a join:
683
     *
684
     * ```php
685
     * 'post.author_id = user.id'
686
     * ```
687
     *
688
     * @param array $params the parameters (name => value) to be bound to the query.
689
     * @return $this the query object itself
690
     */
691 36
    public function join($type, $table, $on = '', $params = [])
692
    {
693 36
        $this->join[] = [$type, $table, $on];
694 36
        return $this->addParams($params);
695
    }
696
697
    /**
698
     * Appends an INNER JOIN part to the query.
699
     * @param string|array $table the table to be joined.
700
     *
701
     * Use a string to represent the name of the table to be joined.
702
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
703
     * The method will automatically quote the table name unless it contains some parenthesis
704
     * (which means the table is given as a sub-query or DB expression).
705
     *
706
     * Use an array to represent joining with a sub-query. The array must contain only one element.
707
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
708
     * represents the alias for the sub-query.
709
     *
710
     * @param string|array $on the join condition that should appear in the ON part.
711
     * Please refer to [[join()]] on how to specify this parameter.
712
     * @param array $params the parameters (name => value) to be bound to the query.
713
     * @return $this the query object itself
714
     */
715
    public function innerJoin($table, $on = '', $params = [])
716
    {
717
        $this->join[] = ['INNER JOIN', $table, $on];
718
        return $this->addParams($params);
719
    }
720
721
    /**
722
     * Appends a LEFT OUTER JOIN part to the query.
723
     * @param string|array $table the table to be joined.
724
     *
725
     * Use a string to represent the name of the table to be joined.
726
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
727
     * The method will automatically quote the table name unless it contains some parenthesis
728
     * (which means the table is given as a sub-query or DB expression).
729
     *
730
     * Use an array to represent joining with a sub-query. The array must contain only one element.
731
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
732
     * represents the alias for the sub-query.
733
     *
734
     * @param string|array $on the join condition that should appear in the ON part.
735
     * Please refer to [[join()]] on how to specify this parameter.
736
     * @param array $params the parameters (name => value) to be bound to the query
737
     * @return $this the query object itself
738
     */
739 3
    public function leftJoin($table, $on = '', $params = [])
740
    {
741 3
        $this->join[] = ['LEFT JOIN', $table, $on];
742 3
        return $this->addParams($params);
743
    }
744
745
    /**
746
     * Appends a RIGHT OUTER JOIN part to the query.
747
     * @param string|array $table the table to be joined.
748
     *
749
     * Use a string to represent the name of the table to be joined.
750
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
751
     * The method will automatically quote the table name unless it contains some parenthesis
752
     * (which means the table is given as a sub-query or DB expression).
753
     *
754
     * Use an array to represent joining with a sub-query. The array must contain only one element.
755
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
756
     * represents the alias for the sub-query.
757
     *
758
     * @param string|array $on the join condition that should appear in the ON part.
759
     * Please refer to [[join()]] on how to specify this parameter.
760
     * @param array $params the parameters (name => value) to be bound to the query
761
     * @return $this the query object itself
762
     */
763
    public function rightJoin($table, $on = '', $params = [])
764
    {
765
        $this->join[] = ['RIGHT JOIN', $table, $on];
766
        return $this->addParams($params);
767
    }
768
769
    /**
770
     * Sets the GROUP BY part of the query.
771
     * @param string|array|Expression $columns the columns to be grouped by.
772
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
773
     * The method will automatically quote the column names unless a column contains some parenthesis
774
     * (which means the column contains a DB expression).
775
     *
776
     * Note that if your group-by is an expression containing commas, you should always use an array
777
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
778
     * the group-by columns.
779
     *
780
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
781
     * @return $this the query object itself
782
     * @see addGroupBy()
783
     */
784 12
    public function groupBy($columns)
785
    {
786 12
        if ($columns instanceof Expression) {
787 3
            $columns = [$columns];
788 12
        } elseif (!is_array($columns)) {
789 12
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
790 12
        }
791 12
        $this->groupBy = $columns;
792 12
        return $this;
793
    }
794
795
    /**
796
     * Adds additional group-by columns to the existing ones.
797
     * @param string|array $columns additional columns to be grouped by.
798
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
799
     * The method will automatically quote the column names unless a column contains some parenthesis
800
     * (which means the column contains a DB expression).
801
     *
802
     * Note that if your group-by is an expression containing commas, you should always use an array
803
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
804
     * the group-by columns.
805
     *
806
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
807
     * @return $this the query object itself
808
     * @see groupBy()
809
     */
810 3
    public function addGroupBy($columns)
811
    {
812 3
        if ($columns instanceof Expression) {
813
            $columns = [$columns];
814 3
        } elseif (!is_array($columns)) {
815 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
816 3
        }
817 3
        if ($this->groupBy === null) {
818
            $this->groupBy = $columns;
819
        } else {
820 3
            $this->groupBy = array_merge($this->groupBy, $columns);
821
        }
822 3
        return $this;
823
    }
824
825
    /**
826
     * Sets the HAVING part of the query.
827
     * @param string|array|Expression $condition the conditions to be put after HAVING.
828
     * Please refer to [[where()]] on how to specify this parameter.
829
     * @param array $params the parameters (name => value) to be bound to the query.
830
     * @return $this the query object itself
831
     * @see andHaving()
832
     * @see orHaving()
833
     */
834 10
    public function having($condition, $params = [])
835
    {
836 10
        $this->having = $condition;
837 10
        $this->addParams($params);
838 10
        return $this;
839
    }
840
841
    /**
842
     * Adds an additional HAVING condition to the existing one.
843
     * The new condition and the existing one will be joined using the `AND` operator.
844
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
845
     * on how to specify this parameter.
846
     * @param array $params the parameters (name => value) to be bound to the query.
847
     * @return $this the query object itself
848
     * @see having()
849
     * @see orHaving()
850
     */
851 3
    public function andHaving($condition, $params = [])
852
    {
853 3
        if ($this->having === null) {
854
            $this->having = $condition;
855
        } else {
856 3
            $this->having = ['and', $this->having, $condition];
857
        }
858 3
        $this->addParams($params);
859 3
        return $this;
860
    }
861
862
    /**
863
     * Adds an additional HAVING condition to the existing one.
864
     * The new condition and the existing one will be joined using the `OR` operator.
865
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
866
     * on how to specify this parameter.
867
     * @param array $params the parameters (name => value) to be bound to the query.
868
     * @return $this the query object itself
869
     * @see having()
870
     * @see andHaving()
871
     */
872 3
    public function orHaving($condition, $params = [])
873
    {
874 3
        if ($this->having === null) {
875
            $this->having = $condition;
876
        } else {
877 3
            $this->having = ['or', $this->having, $condition];
878
        }
879 3
        $this->addParams($params);
880 3
        return $this;
881
    }
882
883
    /**
884
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
885
     *
886
     * This method is similar to [[having()]]. The main difference is that this method will
887
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
888
     * for building query conditions based on filter values entered by users.
889
     *
890
     * The following code shows the difference between this method and [[having()]]:
891
     *
892
     * ```php
893
     * // HAVING `age`=:age
894
     * $query->filterHaving(['name' => null, 'age' => 20]);
895
     * // HAVING `age`=:age
896
     * $query->having(['age' => 20]);
897
     * // HAVING `name` IS NULL AND `age`=:age
898
     * $query->having(['name' => null, 'age' => 20]);
899
     * ```
900
     *
901
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
902
     *
903
     * @param array $condition the conditions that should be put in the HAVING part.
904
     * See [[having()]] on how to specify this parameter.
905
     * @return $this the query object itself
906
     * @see having()
907
     * @see andFilterHaving()
908
     * @see orFilterHaving()
909
     * @since 2.0.11
910
     */
911 6
    public function filterHaving(array $condition)
912
    {
913 6
        $condition = $this->filterCondition($condition);
914 6
        if ($condition !== []) {
915 6
            $this->having($condition);
916 6
        }
917 6
        return $this;
918
    }
919
920
    /**
921
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
922
     * The new condition and the existing one will be joined using the `AND` operator.
923
     *
924
     * This method is similar to [[andHaving()]]. The main difference is that this method will
925
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
926
     * for building query conditions based on filter values entered by users.
927
     *
928
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
929
     * on how to specify this parameter.
930
     * @return $this the query object itself
931
     * @see filterHaving()
932
     * @see orFilterHaving()
933
     * @since 2.0.11
934
     */
935 6
    public function andFilterHaving(array $condition)
936
    {
937 6
        $condition = $this->filterCondition($condition);
938 6
        if ($condition !== []) {
939
            $this->andHaving($condition);
940
        }
941 6
        return $this;
942
    }
943
944
    /**
945
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
946
     * The new condition and the existing one will be joined using the `OR` operator.
947
     *
948
     * This method is similar to [[orHaving()]]. The main difference is that this method will
949
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
950
     * for building query conditions based on filter values entered by users.
951
     *
952
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
953
     * on how to specify this parameter.
954
     * @return $this the query object itself
955
     * @see filterHaving()
956
     * @see andFilterHaving()
957
     * @since 2.0.11
958
     */
959 6
    public function orFilterHaving(array $condition)
960
    {
961 6
        $condition = $this->filterCondition($condition);
962 6
        if ($condition !== []) {
963
            $this->orHaving($condition);
964
        }
965 6
        return $this;
966
    }
967
968
    /**
969
     * Appends a SQL statement using UNION operator.
970
     * @param string|Query $sql the SQL statement to be appended using UNION
971
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
972
     * @return $this the query object itself
973
     */
974 10
    public function union($sql, $all = false)
975
    {
976 10
        $this->union[] = ['query' => $sql, 'all' => $all];
977 10
        return $this;
978
    }
979
980
    /**
981
     * Sets the parameters to be bound to the query.
982
     * @param array $params list of query parameter values indexed by parameter placeholders.
983
     * For example, `[':name' => 'Dan', ':age' => 31]`.
984
     * @return $this the query object itself
985
     * @see addParams()
986
     */
987 6
    public function params($params)
988
    {
989 6
        $this->params = $params;
990 6
        return $this;
991
    }
992
993
    /**
994
     * Adds additional parameters to be bound to the query.
995
     * @param array $params list of query parameter values indexed by parameter placeholders.
996
     * For example, `[':name' => 'Dan', ':age' => 31]`.
997
     * @return $this the query object itself
998
     * @see params()
999
     */
1000 676
    public function addParams($params)
1001
    {
1002 676
        if (!empty($params)) {
1003 45
            if (empty($this->params)) {
1004 45
                $this->params = $params;
1005 45
            } else {
1006 6
                foreach ($params as $name => $value) {
1007 6
                    if (is_int($name)) {
1008
                        $this->params[] = $value;
1009
                    } else {
1010 6
                        $this->params[$name] = $value;
1011
                    }
1012 6
                }
1013
            }
1014 45
        }
1015 676
        return $this;
1016
    }
1017
1018
    /**
1019
     * Creates a new Query object and copies its property values from an existing one.
1020
     * The properties being copies are the ones to be used by query builders.
1021
     * @param Query $from the source query object
1022
     * @return Query the new Query object
1023
     */
1024 312
    public static function create($from)
1025
    {
1026 312
        return new self([
1027 312
            'where' => $from->where,
1028 312
            'limit' => $from->limit,
1029 312
            'offset' => $from->offset,
1030 312
            'orderBy' => $from->orderBy,
1031 312
            'indexBy' => $from->indexBy,
1032 312
            'select' => $from->select,
1033 312
            'selectOption' => $from->selectOption,
1034 312
            'distinct' => $from->distinct,
1035 312
            'from' => $from->from,
1036 312
            'groupBy' => $from->groupBy,
1037 312
            'join' => $from->join,
1038 312
            'having' => $from->having,
1039 312
            'union' => $from->union,
1040 312
            'params' => $from->params,
1041 312
        ]);
1042
    }
1043
}
1044