Completed
Push — php7-remove-phpunit-compat ( b957db...533a50 )
by Alexander
11:13
created

Query::exists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
14
/**
15
 * Query represents a SELECT SQL statement in a way that is independent of DBMS.
16
 *
17
 * Query provides a set of methods to facilitate the specification of different clauses
18
 * in a SELECT statement. These methods can be chained together.
19
 *
20
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
21
 * used to perform/execute the DB query against a database.
22
 *
23
 * For example,
24
 *
25
 * ```php
26
 * $query = new Query;
27
 * // compose the query
28
 * $query->select('id, name')
29
 *     ->from('user')
30
 *     ->limit(10);
31
 * // build and execute the query
32
 * $rows = $query->all();
33
 * // alternatively, you can create DB command and execute it
34
 * $command = $query->createCommand();
35
 * // $command->sql returns the actual SQL
36
 * $rows = $command->queryAll();
37
 * ```
38
 *
39
 * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
40
 *
41
 * 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).
42
 *
43
 * @author Qiang Xue <[email protected]>
44
 * @author Carsten Brandt <[email protected]>
45
 * @since 2.0
46
 */
47
class Query extends Component implements QueryInterface
48
{
49
    use QueryTrait;
50
51
    /**
52
     * @var array the columns being selected. For example, `['id', 'name']`.
53
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
54
     * @see select()
55
     */
56
    public $select;
57
    /**
58
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
59
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
60
     */
61
    public $selectOption;
62
    /**
63
     * @var bool whether to select distinct rows of data only. If this is set true,
64
     * the SELECT clause would be changed to SELECT DISTINCT.
65
     */
66
    public $distinct;
67
    /**
68
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
69
     * This is used to construct the FROM clause in a SQL statement.
70
     * @see from()
71
     */
72
    public $from;
73
    /**
74
     * @var array how to group the query results. For example, `['company', 'department']`.
75
     * This is used to construct the GROUP BY clause in a SQL statement.
76
     */
77
    public $groupBy;
78
    /**
79
     * @var array how to join with other tables. Each array element represents the specification
80
     * of one join which has the following structure:
81
     *
82
     * ```php
83
     * [$joinType, $tableName, $joinCondition]
84
     * ```
85
     *
86
     * For example,
87
     *
88
     * ```php
89
     * [
90
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
91
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
92
     * ]
93
     * ```
94
     */
95
    public $join;
96
    /**
97
     * @var string|array|Expression the condition to be applied in the GROUP BY clause.
98
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
99
     */
100
    public $having;
101
    /**
102
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
103
     * Each array element is an array of the following structure:
104
     *
105
     * - `query`: either a string or a [[Query]] object representing a query
106
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
107
     */
108
    public $union;
109
    /**
110
     * @var array list of query parameter values indexed by parameter placeholders.
111
     * For example, `[':name' => 'Dan', ':age' => 31]`.
112
     */
113
    public $params = [];
114
115
116
    /**
117
     * Creates a DB command that can be used to execute this query.
118
     * @param Connection $db the database connection used to generate the SQL statement.
119
     * If this parameter is not given, the `db` application component will be used.
120
     * @return Command the created DB command instance.
121
     */
122 226
    public function createCommand($db = null)
123
    {
124 226
        if ($db === null) {
125 15
            $db = Yii::$app->getDb();
126
        }
127 226
        [$sql, $params] = $db->getQueryBuilder()->build($this);
0 ignored issues
show
Bug introduced by
The variable $sql does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $params does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
128
129 226
        return $db->createCommand($sql, $params);
130
    }
131
132
    /**
133
     * Prepares for building SQL.
134
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
135
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
136
     * @param QueryBuilder $builder
137
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
138
     */
139 545
    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...
140
    {
141 545
        return $this;
142
    }
143
144
    /**
145
     * Starts a batch query.
146
     *
147
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
148
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
149
     * and can be traversed to retrieve the data in batches.
150
     *
151
     * For example,
152
     *
153
     * ```php
154
     * $query = (new Query)->from('user');
155
     * foreach ($query->batch() as $rows) {
156
     *     // $rows is an array of 100 or fewer rows from user table
157
     * }
158
     * ```
159
     *
160
     * @param int $batchSize the number of records to be fetched in each batch.
161
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
162
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
163
     * and can be traversed to retrieve the data in batches.
164
     */
165 6
    public function batch($batchSize = 100, $db = null)
166
    {
167 6
        return Yii::createObject([
168 6
            'class' => BatchQueryResult::class,
169 6
            'query' => $this,
170 6
            'batchSize' => $batchSize,
171 6
            'db' => $db,
172
            'each' => false,
173
        ]);
174
    }
175
176
    /**
177
     * Starts a batch query and retrieves data row by row.
178
     * This method is similar to [[batch()]] except that in each iteration of the result,
179
     * only one row of data is returned. For example,
180
     *
181
     * ```php
182
     * $query = (new Query)->from('user');
183
     * foreach ($query->each() as $row) {
184
     * }
185
     * ```
186
     *
187
     * @param int $batchSize the number of records to be fetched in each batch.
188
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
189
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
190
     * and can be traversed to retrieve the data in batches.
191
     */
192 3
    public function each($batchSize = 100, $db = null)
193
    {
194 3
        return Yii::createObject([
195 3
            'class' => BatchQueryResult::class,
196 3
            'query' => $this,
197 3
            'batchSize' => $batchSize,
198 3
            'db' => $db,
199
            'each' => true,
200
        ]);
201
    }
202
203
    /**
204
     * Executes the query and returns all results as an array.
205
     * @param Connection $db the database connection used to generate the SQL statement.
206
     * If this parameter is not given, the `db` application component will be used.
207
     * @return array the query results. If the query results in nothing, an empty array will be returned.
208
     */
209 334
    public function all($db = null)
210
    {
211 334
        if ($this->emulateExecution) {
212 9
            return [];
213
        }
214 328
        $rows = $this->createCommand($db)->queryAll();
215 328
        return $this->populate($rows);
216
    }
217
218
    /**
219
     * Converts the raw query results into the format as specified by this query.
220
     * This method is internally used to convert the data fetched from database
221
     * into the format as required by this query.
222
     * @param array $rows the raw query result from database
223
     * @return array the converted query result
224
     */
225 154
    public function populate($rows)
226
    {
227 154
        if ($this->indexBy === null) {
228 154
            return $rows;
229
        }
230 3
        $result = [];
231 3
        foreach ($rows as $row) {
232 3
            if (is_string($this->indexBy)) {
233 3
                $key = $row[$this->indexBy];
234
            } else {
235
                $key = call_user_func($this->indexBy, $row);
236
            }
237 3
            $result[$key] = $row;
238
        }
239 3
        return $result;
240
    }
241
242
    /**
243
     * Executes the query and returns a single row of result.
244
     * @param Connection $db the database connection used to generate the SQL statement.
245
     * If this parameter is not given, the `db` application component will be used.
246
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
247
     * results in nothing.
248
     */
249 344
    public function one($db = null)
250
    {
251 344
        if ($this->emulateExecution) {
252 6
            return false;
253
        }
254 338
        return $this->createCommand($db)->queryOne();
255
    }
256
257
    /**
258
     * Returns the query result as a scalar value.
259
     * The value returned will be the first column in the first row of the query results.
260
     * @param Connection $db the database connection used to generate the SQL statement.
261
     * If this parameter is not given, the `db` application component will be used.
262
     * @return string|null|false the value of the first column in the first row of the query result.
263
     * False is returned if the query result is empty.
264
     */
265 14
    public function scalar($db = null)
266
    {
267 14
        if ($this->emulateExecution) {
268 6
            return null;
269
        }
270 8
        return $this->createCommand($db)->queryScalar();
271
    }
272
273
    /**
274
     * Executes the query and returns the first column of the result.
275
     * @param Connection $db the database connection used to generate the SQL statement.
276
     * If this parameter is not given, the `db` application component will be used.
277
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
278
     */
279 37
    public function column($db = null)
280
    {
281 37
        if ($this->emulateExecution) {
282 6
            return [];
283
        }
284
285 31
        if ($this->indexBy === null) {
286 25
            return $this->createCommand($db)->queryColumn();
287
        }
288
289 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
290 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
291 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
292
            } else {
293
                $this->select[] = $this->indexBy;
294
            }
295
        }
296 9
        $rows = $this->createCommand($db)->queryAll();
297 9
        $results = [];
298 9
        foreach ($rows as $row) {
299 9
            $value = reset($row);
300
301 9
            if ($this->indexBy instanceof \Closure) {
302 3
                $results[call_user_func($this->indexBy, $row)] = $value;
303
            } else {
304 9
                $results[$row[$this->indexBy]] = $value;
305
            }
306
        }
307 9
        return $results;
308
    }
309
310
    /**
311
     * Returns the number of records.
312
     * @param string $q the COUNT expression. Defaults to '*'.
313
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
314
     * @param Connection $db the database connection used to generate the SQL statement.
315
     * If this parameter is not given (or null), the `db` application component will be used.
316
     * @return int|string number of records. The result may be a string depending on the
317
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
318
     */
319 87
    public function count($q = '*', $db = null)
320
    {
321 87
        if ($this->emulateExecution) {
322 6
            return 0;
323
        }
324 87
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->queryScalar("COUNT({$q})", $db); of type null|string|false adds false to the return on line 324 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...
325
    }
326
327
    /**
328
     * Returns the sum of the specified column values.
329
     * @param string $q the column name or expression.
330
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
331
     * @param Connection $db the database connection used to generate the SQL statement.
332
     * If this parameter is not given, the `db` application component will be used.
333
     * @return mixed the sum of the specified column values.
334
     */
335 9
    public function sum($q, $db = null)
336
    {
337 9
        if ($this->emulateExecution) {
338 6
            return 0;
339
        }
340 3
        return $this->queryScalar("SUM($q)", $db);
341
    }
342
343
    /**
344
     * Returns the average of the specified column values.
345
     * @param string $q the column name or expression.
346
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
347
     * @param Connection $db the database connection used to generate the SQL statement.
348
     * If this parameter is not given, the `db` application component will be used.
349
     * @return mixed the average of the specified column values.
350
     */
351 9
    public function average($q, $db = null)
352
    {
353 9
        if ($this->emulateExecution) {
354 6
            return 0;
355
        }
356 3
        return $this->queryScalar("AVG($q)", $db);
357
    }
358
359
    /**
360
     * Returns the minimum of the specified column values.
361
     * @param string $q the column name or expression.
362
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
363
     * @param Connection $db the database connection used to generate the SQL statement.
364
     * If this parameter is not given, the `db` application component will be used.
365
     * @return mixed the minimum of the specified column values.
366
     */
367 9
    public function min($q, $db = null)
368
    {
369 9
        return $this->queryScalar("MIN($q)", $db);
370
    }
371
372
    /**
373
     * Returns the maximum of the specified column values.
374
     * @param string $q the column name or expression.
375
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
376
     * @param Connection $db the database connection used to generate the SQL statement.
377
     * If this parameter is not given, the `db` application component will be used.
378
     * @return mixed the maximum of the specified column values.
379
     */
380 9
    public function max($q, $db = null)
381
    {
382 9
        return $this->queryScalar("MAX($q)", $db);
383
    }
384
385
    /**
386
     * Returns a value indicating whether the query result contains any row of data.
387
     * @param Connection $db the database connection used to generate the SQL statement.
388
     * If this parameter is not given, the `db` application component will be used.
389
     * @return bool whether the query result contains any row of data.
390
     */
391 69
    public function exists($db = null)
392
    {
393 69
        if ($this->emulateExecution) {
394 6
            return false;
395
        }
396 63
        $command = $this->createCommand($db);
397 63
        $params = $command->params;
398 63
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
399 63
        $command->bindValues($params);
400 63
        return (bool) $command->queryScalar();
401
    }
402
403
    /**
404
     * Queries a scalar value by setting [[select]] first.
405
     * Restores the value of select to make this query reusable.
406
     * @param string|Expression $selectExpression
407
     * @param Connection|null $db
408
     * @return bool|string
409
     */
410 87
    protected function queryScalar($selectExpression, $db)
411
    {
412 87
        if ($this->emulateExecution) {
413 6
            return null;
414
        }
415
416
        if (
417 87
            !$this->distinct
418 87
            && empty($this->groupBy)
419 87
            && empty($this->having)
420 87
            && empty($this->union)
421
        ) {
422 86
            $select = $this->select;
423 86
            $order = $this->orderBy;
424 86
            $limit = $this->limit;
425 86
            $offset = $this->offset;
426
427 86
            $this->select = [$selectExpression];
428 86
            $this->orderBy = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $orderBy.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

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