Completed
Push — activequery-alias2 ( d7e45e...ce3573 )
by Carsten
39:33 queued 33:21
created

Query::column()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0106
Metric Value
dl 0
loc 19
rs 8.8571
ccs 14
cts 15
cp 0.9333
cc 6
eloc 13
nc 7
nop 1
crap 6.0106
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 boolean 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 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 119
    public function createCommand($db = null)
122
    {
123 119
        if ($db === null) {
124 7
            $db = Yii::$app->getDb();
125 7
        }
126 119
        list ($sql, $params) = $db->getQueryBuilder()->build($this);
127
128 119
        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 393
    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 393
        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 10 or fewer rows from user table
156
     * }
157
     * ```
158
     *
159
     * @param integer $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 2
    public function batch($batchSize = 100, $db = null)
165
    {
166 2
        return Yii::createObject([
167 2
            'class' => BatchQueryResult::className(),
168 2
            'query' => $this,
169 2
            'batchSize' => $batchSize,
170 2
            'db' => $db,
171 2
            'each' => false,
172 2
        ]);
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 integer $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 1
    public function each($batchSize = 100, $db = null)
192
    {
193 1
        return Yii::createObject([
194 1
            'class' => BatchQueryResult::className(),
195 1
            'query' => $this,
196 1
            'batchSize' => $batchSize,
197 1
            'db' => $db,
198 1
            'each' => true,
199 1
        ]);
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 214
    public function all($db = null)
209
    {
210 214
        $rows = $this->createCommand($db)->queryAll();
211 214
        return $this->populate($rows);
212
    }
213
214
    /**
215
     * Converts the raw query results into the format as specified by this query.
216
     * This method is internally used to convert the data fetched from database
217
     * into the format as required by this query.
218
     * @param array $rows the raw query result from database
219
     * @return array the converted query result
220
     */
221 74
    public function populate($rows)
222
    {
223 74
        if ($this->indexBy === null) {
224 74
            return $rows;
225
        }
226 1
        $result = [];
227 1
        foreach ($rows as $row) {
228 1
            if (is_string($this->indexBy)) {
229 1
                $key = $row[$this->indexBy];
230 1
            } else {
231
                $key = call_user_func($this->indexBy, $row);
232
            }
233 1
            $result[$key] = $row;
234 1
        }
235 1
        return $result;
236
    }
237
238
    /**
239
     * Executes the query and returns a single row of result.
240
     * @param Connection $db the database connection used to generate the SQL statement.
241
     * If this parameter is not given, the `db` application component will be used.
242
     * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
243
     * results in nothing.
244
     */
245 191
    public function one($db = null)
246
    {
247 191
        return $this->createCommand($db)->queryOne();
248
    }
249
250
    /**
251
     * Returns the query result as a scalar value.
252
     * The value returned will be the first column in the first row of the query results.
253
     * @param Connection $db the database connection used to generate the SQL statement.
254
     * If this parameter is not given, the `db` application component will be used.
255
     * @return string|boolean the value of the first column in the first row of the query result.
256
     * False is returned if the query result is empty.
257
     */
258 8
    public function scalar($db = null)
259
    {
260 8
        return $this->createCommand($db)->queryScalar();
261
    }
262
263
    /**
264
     * Executes the query and returns the first column of the result.
265
     * @param Connection $db the database connection used to generate the SQL statement.
266
     * If this parameter is not given, the `db` application component will be used.
267
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
268
     */
269 17
    public function column($db = null)
270
    {
271 17
        if (!is_string($this->indexBy)) {
272 17
            return $this->createCommand($db)->queryColumn();
273
        }
274 3
        if (is_array($this->select) && count($this->select) === 1) {
275 3
            $this->select[] = $this->indexBy;
276 3
        }
277 3
        $rows = $this->createCommand($db)->queryAll();
278 3
        $results = [];
279 3
        foreach ($rows as $row) {
280 3
            if (array_key_exists($this->indexBy, $row)) {
281 3
                $results[$row[$this->indexBy]] = reset($row);
282 3
            } else {
283
                $results[] = reset($row);
284
            }
285 3
        }
286 3
        return $results;
287
    }
288
289
    /**
290
     * Returns the number of records.
291
     * @param string $q the COUNT expression. Defaults to '*'.
292
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
293
     * @param Connection $db the database connection used to generate the SQL statement.
294
     * If this parameter is not given (or null), the `db` application component will be used.
295
     * @return integer|string number of records. The result may be a string depending on the
296
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
297
     */
298 66
    public function count($q = '*', $db = null)
299
    {
300 66
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->queryScalar("COUNT({$q})", $db); of type string|null|false adds false to the return on line 300 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...
301
    }
302
303
    /**
304
     * Returns the sum of the specified column values.
305
     * @param string $q the column name or expression.
306
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
307
     * @param Connection $db the database connection used to generate the SQL statement.
308
     * If this parameter is not given, the `db` application component will be used.
309
     * @return mixed the sum of the specified column values.
310
     */
311 3
    public function sum($q, $db = null)
312
    {
313 3
        return $this->queryScalar("SUM($q)", $db);
314
    }
315
316
    /**
317
     * Returns the average of the specified column values.
318
     * @param string $q the column name or expression.
319
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
320
     * @param Connection $db the database connection used to generate the SQL statement.
321
     * If this parameter is not given, the `db` application component will be used.
322
     * @return mixed the average of the specified column values.
323
     */
324 3
    public function average($q, $db = null)
325
    {
326 3
        return $this->queryScalar("AVG($q)", $db);
327
    }
328
329
    /**
330
     * Returns the minimum of the specified column values.
331
     * @param string $q the column name or expression.
332
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
333
     * @param Connection $db the database connection used to generate the SQL statement.
334
     * If this parameter is not given, the `db` application component will be used.
335
     * @return mixed the minimum of the specified column values.
336
     */
337 3
    public function min($q, $db = null)
338
    {
339 3
        return $this->queryScalar("MIN($q)", $db);
340
    }
341
342
    /**
343
     * Returns the maximum of the specified column values.
344
     * @param string $q the column name or expression.
345
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
346
     * @param Connection $db the database connection used to generate the SQL statement.
347
     * If this parameter is not given, the `db` application component will be used.
348
     * @return mixed the maximum of the specified column values.
349
     */
350 3
    public function max($q, $db = null)
351
    {
352 3
        return $this->queryScalar("MAX($q)", $db);
353
    }
354
355
    /**
356
     * Returns a value indicating whether the query result contains any row of data.
357
     * @param Connection $db the database connection used to generate the SQL statement.
358
     * If this parameter is not given, the `db` application component will be used.
359
     * @return boolean whether the query result contains any row of data.
360
     */
361 36
    public function exists($db = null)
362
    {
363 36
        $select = $this->select;
364 36
        $this->select = [new Expression('1')];
365 36
        $command = $this->createCommand($db);
366 36
        $this->select = $select;
367 36
        return $command->queryScalar() !== false;
368
    }
369
370
    /**
371
     * Queries a scalar value by setting [[select]] first.
372
     * Restores the value of select to make this query reusable.
373
     * @param string|Expression $selectExpression
374
     * @param Connection|null $db
375
     * @return bool|string
376
     */
377 63
    protected function queryScalar($selectExpression, $db)
378
    {
379 63
        $select = $this->select;
380 63
        $limit = $this->limit;
381 63
        $offset = $this->offset;
382
383 63
        $this->select = [$selectExpression];
384 63
        $this->limit = null;
385 63
        $this->offset = null;
386 63
        $command = $this->createCommand($db);
387
388 63
        $this->select = $select;
389 63
        $this->limit = $limit;
390 63
        $this->offset = $offset;
391
392 63
        if (empty($this->groupBy) && empty($this->having) && empty($this->union) && !$this->distinct) {
393 62
            return $command->queryScalar();
394
        } else {
395 7
            return (new Query)->select([$selectExpression])
396 7
                ->from(['c' => $this])
397 7
                ->createCommand($command->db)
398 7
                ->queryScalar();
399
        }
400
    }
401
402
    /**
403
     * Sets the SELECT part of the query.
404
     * @param string|array|Expression $columns the columns to be selected.
405
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
406
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
407
     * The method will automatically quote the column names unless a column contains some parenthesis
408
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
409
     * an [[Expression]] object.
410
     *
411
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
412
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
413
     *
414
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
415
     * does not need alias, do not use a string key).
416
     *
417
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
418
     * as a `Query` instance representing the sub-query.
419
     *
420
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
421
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
422
     * @return $this the query object itself
423
     */
424 150
    public function select($columns, $option = null)
425
    {
426 150
        if ($columns instanceof Expression) {
427 3
            $columns = [$columns];
428 150
        } elseif (!is_array($columns)) {
429 65
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
430 65
        }
431 150
        $this->select = $columns;
432 150
        $this->selectOption = $option;
433 150
        return $this;
434
    }
435
436
    /**
437
     * Add more columns to the SELECT part of the query.
438
     *
439
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
440
     * if you want to select all remaining columns too:
441
     *
442
     * ```php
443
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
444
     * ```
445
     *
446
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
447
     * details about the format of this parameter.
448
     * @return $this the query object itself
449
     * @see select()
450
     */
451 9
    public function addSelect($columns)
452
    {
453 9
        if ($columns instanceof Expression) {
454 3
            $columns = [$columns];
455 9
        } elseif (!is_array($columns)) {
456 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
457 3
        }
458 9
        if ($this->select === null) {
459 3
            $this->select = $columns;
460 3
        } else {
461 9
            $this->select = array_merge($this->select, $columns);
462
        }
463 9
        return $this;
464
    }
465
466
    /**
467
     * Sets the value indicating whether to SELECT DISTINCT or not.
468
     * @param boolean $value whether to SELECT DISTINCT or not.
469
     * @return $this the query object itself
470
     */
471 6
    public function distinct($value = true)
472
    {
473 6
        $this->distinct = $value;
474 6
        return $this;
475
    }
476
477
    /**
478
     * Sets the FROM part of the query.
479
     * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
480
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
481
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
482
     * The method will automatically quote the table names unless it contains some parenthesis
483
     * (which means the table is given as a sub-query or DB expression).
484
     *
485
     * When the tables are specified as an array, you may also use the array keys as the table aliases
486
     * (if a table does not need alias, do not use a string key).
487
     *
488
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
489
     * as the alias for the sub-query.
490
     *
491
     * Here are some examples:
492
     *
493
     * ```php
494
     * // SELECT * FROM  `user` `u`, `profile`;
495
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
496
     *
497
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
498
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
499
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
500
     *
501
     * // subquery can also be a string with plain SQL wrapped in parenthesis
502
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
503
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
504
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
505
     * ```
506
     *
507
     * @return $this the query object itself
508
     */
509 161
    public function from($tables)
510
    {
511 161
        if (!is_array($tables)) {
512 142
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
513 142
        }
514 161
        $this->from = $tables;
515 161
        return $this;
516
    }
517
518
    /**
519
     * Sets the WHERE part of the query.
520
     *
521
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
522
     * specifying the values to be bound to the query.
523
     *
524
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
525
     *
526
     * @inheritdoc
527
     *
528
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
529
     * @param array $params the parameters (name => value) to be bound to the query.
530
     * @return $this the query object itself
531
     * @see andWhere()
532
     * @see orWhere()
533
     * @see QueryInterface::where()
534
     */
535 392
    public function where($condition, $params = [])
536
    {
537 392
        $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...
538 392
        $this->addParams($params);
539 392
        return $this;
540
    }
541
542
    /**
543
     * Adds an additional WHERE condition to the existing one.
544
     * The new condition and the existing one will be joined using the 'AND' operator.
545
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
546
     * on how to specify this parameter.
547
     * @param array $params the parameters (name => value) to be bound to the query.
548
     * @return $this the query object itself
549
     * @see where()
550
     * @see orWhere()
551
     */
552 199
    public function andWhere($condition, $params = [])
553
    {
554 199
        if ($this->where === null) {
555 173
            $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...
556 173
        } else {
557 62
            $this->where = ['and', $this->where, $condition];
558
        }
559 199
        $this->addParams($params);
560 199
        return $this;
561
    }
562
563
    /**
564
     * Adds an additional WHERE condition to the existing one.
565
     * The new condition and the existing one will be joined using the 'OR' operator.
566
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
567
     * on how to specify this parameter.
568
     * @param array $params the parameters (name => value) to be bound to the query.
569
     * @return $this the query object itself
570
     * @see where()
571
     * @see andWhere()
572
     */
573 3
    public function orWhere($condition, $params = [])
574
    {
575 3
        if ($this->where === null) {
576
            $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...
577
        } else {
578 3
            $this->where = ['or', $this->where, $condition];
579
        }
580 3
        $this->addParams($params);
581 3
        return $this;
582
    }
583
584
    /**
585
     * Appends a JOIN part to the query.
586
     * The first parameter specifies what type of join it is.
587
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
588
     * @param string|array $table the table to be joined.
589
     *
590
     * Use a string to represent the name of the table to be joined.
591
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
592
     * The method will automatically quote the table name unless it contains some parenthesis
593
     * (which means the table is given as a sub-query or DB expression).
594
     *
595
     * Use an array to represent joining with a sub-query. The array must contain only one element.
596
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
597
     * represents the alias for the sub-query.
598
     *
599
     * @param string|array $on the join condition that should appear in the ON part.
600
     * Please refer to [[where()]] on how to specify this parameter.
601
     * @param array $params the parameters (name => value) to be bound to the query.
602
     * @return $this the query object itself
603
     */
604 18
    public function join($type, $table, $on = '', $params = [])
605
    {
606 18
        $this->join[] = [$type, $table, $on];
607 18
        return $this->addParams($params);
608
    }
609
610
    /**
611
     * Appends an INNER JOIN part to the query.
612
     * @param string|array $table the table to be joined.
613
     *
614
     * Use a string to represent the name of the table to be joined.
615
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
616
     * The method will automatically quote the table name unless it contains some parenthesis
617
     * (which means the table is given as a sub-query or DB expression).
618
     *
619
     * Use an array to represent joining with a sub-query. The array must contain only one element.
620
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
621
     * represents the alias for the sub-query.
622
     *
623
     * @param string|array $on the join condition that should appear in the ON part.
624
     * Please refer to [[where()]] on how to specify this parameter.
625
     * @param array $params the parameters (name => value) to be bound to the query.
626
     * @return $this the query object itself
627
     */
628
    public function innerJoin($table, $on = '', $params = [])
629
    {
630
        $this->join[] = ['INNER JOIN', $table, $on];
631
        return $this->addParams($params);
632
    }
633
634
    /**
635
     * Appends a LEFT OUTER JOIN part to the query.
636
     * @param string|array $table the table to be joined.
637
     *
638
     * Use a string to represent the name of the table to be joined.
639
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
640
     * The method will automatically quote the table name unless it contains some parenthesis
641
     * (which means the table is given as a sub-query or DB expression).
642
     *
643
     * Use an array to represent joining with a sub-query. The array must contain only one element.
644
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
645
     * represents the alias for the sub-query.
646
     *
647
     * @param string|array $on the join condition that should appear in the ON part.
648
     * Please refer to [[where()]] on how to specify this parameter.
649
     * @param array $params the parameters (name => value) to be bound to the query
650
     * @return $this the query object itself
651
     */
652
    public function leftJoin($table, $on = '', $params = [])
653
    {
654
        $this->join[] = ['LEFT JOIN', $table, $on];
655
        return $this->addParams($params);
656
    }
657
658
    /**
659
     * Appends a RIGHT OUTER JOIN part to the query.
660
     * @param string|array $table the table to be joined.
661
     *
662
     * Use a string to represent the name of the table to be joined.
663
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
664
     * The method will automatically quote the table name unless it contains some parenthesis
665
     * (which means the table is given as a sub-query or DB expression).
666
     *
667
     * Use an array to represent joining with a sub-query. The array must contain only one element.
668
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
669
     * represents the alias for the sub-query.
670
     *
671
     * @param string|array $on the join condition that should appear in the ON part.
672
     * Please refer to [[where()]] on how to specify this parameter.
673
     * @param array $params the parameters (name => value) to be bound to the query
674
     * @return $this the query object itself
675
     */
676
    public function rightJoin($table, $on = '', $params = [])
677
    {
678
        $this->join[] = ['RIGHT JOIN', $table, $on];
679
        return $this->addParams($params);
680
    }
681
682
    /**
683
     * Sets the GROUP BY part of the query.
684
     * @param string|array|Expression $columns the columns to be grouped by.
685
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
686
     * The method will automatically quote the column names unless a column contains some parenthesis
687
     * (which means the column contains a DB expression).
688
     *
689
     * Note that if your group-by is an expression containing commas, you should always use an array
690
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
691
     * the group-by columns.
692
     *
693
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
694
     * @return $this the query object itself
695
     * @see addGroupBy()
696
     */
697 12
    public function groupBy($columns)
698
    {
699 12
        if ($columns instanceof Expression) {
700 3
            $columns = [$columns];
701 12
        } elseif (!is_array($columns)) {
702 12
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
703 12
        }
704 12
        $this->groupBy = $columns;
705 12
        return $this;
706
    }
707
708
    /**
709
     * Adds additional group-by columns to the existing ones.
710
     * @param string|array $columns additional columns to be grouped by.
711
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
712
     * The method will automatically quote the column names unless a column contains some parenthesis
713
     * (which means the column contains a DB expression).
714
     *
715
     * Note that if your group-by is an expression containing commas, you should always use an array
716
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
717
     * the group-by columns.
718
     *
719
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
720
     * @return $this the query object itself
721
     * @see groupBy()
722
     */
723 3
    public function addGroupBy($columns)
724
    {
725 3
        if ($columns instanceof Expression) {
726
            $columns = [$columns];
727 3
        } elseif (!is_array($columns)) {
728 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
729 3
        }
730 3
        if ($this->groupBy === null) {
731
            $this->groupBy = $columns;
732
        } else {
733 3
            $this->groupBy = array_merge($this->groupBy, $columns);
734
        }
735 3
        return $this;
736
    }
737
738
    /**
739
     * Sets the HAVING part of the query.
740
     * @param string|array|Expression $condition the conditions to be put after HAVING.
741
     * Please refer to [[where()]] on how to specify this parameter.
742
     * @param array $params the parameters (name => value) to be bound to the query.
743
     * @return $this the query object itself
744
     * @see andHaving()
745
     * @see orHaving()
746
     */
747 4
    public function having($condition, $params = [])
748
    {
749 4
        $this->having = $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 $having 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...
750 4
        $this->addParams($params);
751 4
        return $this;
752
    }
753
754
    /**
755
     * Adds an additional HAVING condition to the existing one.
756
     * The new condition and the existing one will be joined using the 'AND' operator.
757
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
758
     * on how to specify this parameter.
759
     * @param array $params the parameters (name => value) to be bound to the query.
760
     * @return $this the query object itself
761
     * @see having()
762
     * @see orHaving()
763
     */
764 3
    public function andHaving($condition, $params = [])
765
    {
766 3
        if ($this->having === null) {
767
            $this->having = $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 $having 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...
768
        } else {
769 3
            $this->having = ['and', $this->having, $condition];
770
        }
771 3
        $this->addParams($params);
772 3
        return $this;
773
    }
774
775
    /**
776
     * Adds an additional HAVING condition to the existing one.
777
     * The new condition and the existing one will be joined using the 'OR' operator.
778
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
779
     * on how to specify this parameter.
780
     * @param array $params the parameters (name => value) to be bound to the query.
781
     * @return $this the query object itself
782
     * @see having()
783
     * @see andHaving()
784
     */
785 3
    public function orHaving($condition, $params = [])
786
    {
787 3
        if ($this->having === null) {
788
            $this->having = $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 $having is declared as type string|array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
789
        } else {
790 3
            $this->having = ['or', $this->having, $condition];
791
        }
792 3
        $this->addParams($params);
793 3
        return $this;
794
    }
795
796
    /**
797
     * Appends a SQL statement using UNION operator.
798
     * @param string|Query $sql the SQL statement to be appended using UNION
799
     * @param boolean $all TRUE if using UNION ALL and FALSE if using UNION
800
     * @return $this the query object itself
801
     */
802 10
    public function union($sql, $all = false)
803
    {
804 10
        $this->union[] = ['query' => $sql, 'all' => $all];
805 10
        return $this;
806
    }
807
808
    /**
809
     * Sets the parameters to be bound to the query.
810
     * @param array $params list of query parameter values indexed by parameter placeholders.
811
     * For example, `[':name' => 'Dan', ':age' => 31]`.
812
     * @return $this the query object itself
813
     * @see addParams()
814
     */
815 6
    public function params($params)
816
    {
817 6
        $this->params = $params;
818 6
        return $this;
819
    }
820
821
    /**
822
     * Adds additional parameters to be bound to the query.
823
     * @param array $params list of query parameter values indexed by parameter placeholders.
824
     * For example, `[':name' => 'Dan', ':age' => 31]`.
825
     * @return $this the query object itself
826
     * @see params()
827
     */
828 524
    public function addParams($params)
829
    {
830 524
        if (!empty($params)) {
831 29
            if (empty($this->params)) {
832 29
                $this->params = $params;
833 29
            } else {
834 6
                foreach ($params as $name => $value) {
835 6
                    if (is_int($name)) {
836
                        $this->params[] = $value;
837
                    } else {
838 6
                        $this->params[$name] = $value;
839
                    }
840 6
                }
841
            }
842 29
        }
843 524
        return $this;
844
    }
845
846
    /**
847
     * Creates a new Query object and copies its property values from an existing one.
848
     * The properties being copies are the ones to be used by query builders.
849
     * @param Query $from the source query object
850
     * @return Query the new Query object
851
     */
852 223
    public static function create($from)
853
    {
854 223
        return new self([
855 223
            'where' => $from->where,
856 223
            'limit' => $from->limit,
857 223
            'offset' => $from->offset,
858 223
            'orderBy' => $from->orderBy,
859 223
            'indexBy' => $from->indexBy,
860 223
            'select' => $from->select,
861 223
            'selectOption' => $from->selectOption,
862 223
            'distinct' => $from->distinct,
863 223
            'from' => $from->from,
864 223
            'groupBy' => $from->groupBy,
865 223
            'join' => $from->join,
866 223
            'having' => $from->having,
867 223
            'union' => $from->union,
868 223
            'params' => $from->params,
869 223
        ]);
870
    }
871
}
872