Completed
Push — 15356-query-getTablesUsedInFro... ( f22f4a...7e8a4c )
by Alexander
08:26
created

Query::getTablesUsedInFrom()   D

Complexity

Conditions 14
Paths 113

Size

Total Lines 78
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 14.008

Importance

Changes 0
Metric Value
dl 0
loc 78
ccs 28
cts 29
cp 0.9655
rs 4.9153
c 0
b 0
f 0
cc 14
eloc 34
nc 113
nop 0
crap 14.008

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\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
 * @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only.
44
 *
45
 * @author Qiang Xue <[email protected]>
46
 * @author Carsten Brandt <[email protected]>
47
 * @since 2.0
48
 */
49
class Query extends Component implements QueryInterface
50
{
51
    use QueryTrait;
52
53
    /**
54
     * @var array the columns being selected. For example, `['id', 'name']`.
55
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
56
     * @see select()
57
     */
58
    public $select;
59
    /**
60
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
61
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
62
     */
63
    public $selectOption;
64
    /**
65
     * @var bool whether to select distinct rows of data only. If this is set true,
66
     * the SELECT clause would be changed to SELECT DISTINCT.
67
     */
68
    public $distinct;
69
    /**
70
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
71
     * This is used to construct the FROM clause in a SQL statement.
72
     * @see from()
73
     */
74
    public $from;
75
    /**
76
     * @var array how to group the query results. For example, `['company', 'department']`.
77
     * This is used to construct the GROUP BY clause in a SQL statement.
78
     */
79
    public $groupBy;
80
    /**
81
     * @var array how to join with other tables. Each array element represents the specification
82
     * of one join which has the following structure:
83
     *
84
     * ```php
85
     * [$joinType, $tableName, $joinCondition]
86
     * ```
87
     *
88
     * For example,
89
     *
90
     * ```php
91
     * [
92
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
93
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
94
     * ]
95
     * ```
96
     */
97
    public $join;
98
    /**
99
     * @var string|array|Expression the condition to be applied in the GROUP BY clause.
100
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
101
     */
102
    public $having;
103
    /**
104
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
105
     * Each array element is an array of the following structure:
106
     *
107
     * - `query`: either a string or a [[Query]] object representing a query
108
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
109
     */
110
    public $union;
111
    /**
112
     * @var array list of query parameter values indexed by parameter placeholders.
113
     * For example, `[':name' => 'Dan', ':age' => 31]`.
114
     */
115
    public $params = [];
116
117
118
    /**
119
     * Creates a DB command that can be used to execute this query.
120
     * @param Connection $db the database connection used to generate the SQL statement.
121
     * If this parameter is not given, the `db` application component will be used.
122
     * @return Command the created DB command instance.
123
     */
124 333
    public function createCommand($db = null)
125
    {
126 333
        if ($db === null) {
127 28
            $db = Yii::$app->getDb();
128
        }
129 333
        list($sql, $params) = $db->getQueryBuilder()->build($this);
130
131 333
        return $db->createCommand($sql, $params);
132
    }
133
134
    /**
135
     * Prepares for building SQL.
136
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
137
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
138
     * @param QueryBuilder $builder
139
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
140
     */
141 655
    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...
142
    {
143 655
        return $this;
144
    }
145
146
    /**
147
     * Starts a batch query.
148
     *
149
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
150
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
151
     * and can be traversed to retrieve the data in batches.
152
     *
153
     * For example,
154
     *
155
     * ```php
156
     * $query = (new Query)->from('user');
157
     * foreach ($query->batch() as $rows) {
158
     *     // $rows is an array of 100 or fewer rows from user table
159
     * }
160
     * ```
161
     *
162
     * @param int $batchSize the number of records to be fetched in each batch.
163
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
164
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
165
     * and can be traversed to retrieve the data in batches.
166
     */
167 6
    public function batch($batchSize = 100, $db = null)
168
    {
169 6
        return Yii::createObject([
170 6
            'class' => BatchQueryResult::className(),
171 6
            'query' => $this,
172 6
            'batchSize' => $batchSize,
173 6
            'db' => $db,
174
            'each' => false,
175
        ]);
176
    }
177
178
    /**
179
     * Starts a batch query and retrieves data row by row.
180
     *
181
     * This method is similar to [[batch()]] except that in each iteration of the result,
182
     * only one row of data is returned. For example,
183
     *
184
     * ```php
185
     * $query = (new Query)->from('user');
186
     * foreach ($query->each() as $row) {
187
     * }
188
     * ```
189
     *
190
     * @param int $batchSize the number of records to be fetched in each batch.
191
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
192
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
193
     * and can be traversed to retrieve the data in batches.
194
     */
195 3
    public function each($batchSize = 100, $db = null)
196
    {
197 3
        return Yii::createObject([
198 3
            'class' => BatchQueryResult::className(),
199 3
            'query' => $this,
200 3
            'batchSize' => $batchSize,
201 3
            'db' => $db,
202
            'each' => true,
203
        ]);
204
    }
205
206
    /**
207
     * Executes the query and returns all results as an array.
208
     * @param Connection $db the database connection used to generate the SQL statement.
209
     * If this parameter is not given, the `db` application component will be used.
210
     * @return array the query results. If the query results in nothing, an empty array will be returned.
211
     */
212 409
    public function all($db = null)
213
    {
214 409
        if ($this->emulateExecution) {
215 9
            return [];
216
        }
217 403
        $rows = $this->createCommand($db)->queryAll();
218 403
        return $this->populate($rows);
219
    }
220
221
    /**
222
     * Converts the raw query results into the format as specified by this query.
223
     * This method is internally used to convert the data fetched from database
224
     * into the format as required by this query.
225
     * @param array $rows the raw query result from database
226
     * @return array the converted query result
227
     */
228 223
    public function populate($rows)
229
    {
230 223
        if ($this->indexBy === null) {
231 223
            return $rows;
232
        }
233 3
        $result = [];
234 3
        foreach ($rows as $row) {
235 3
            if (is_string($this->indexBy)) {
236 3
                $key = $row[$this->indexBy];
237
            } else {
238
                $key = call_user_func($this->indexBy, $row);
239
            }
240 3
            $result[$key] = $row;
241
        }
242
243 3
        return $result;
244
    }
245
246
    /**
247
     * Executes the query and returns a single row of result.
248
     * @param Connection $db the database connection used to generate the SQL statement.
249
     * If this parameter is not given, the `db` application component will be used.
250
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
251
     * results in nothing.
252
     */
253 395
    public function one($db = null)
254
    {
255 395
        if ($this->emulateExecution) {
256 6
            return false;
257
        }
258
259 389
        return $this->createCommand($db)->queryOne();
260
    }
261
262
    /**
263
     * Returns the query result as a scalar value.
264
     * The value returned will be the first column in the first row of the query results.
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 string|null|false the value of the first column in the first row of the query result.
268
     * False is returned if the query result is empty.
269
     */
270 24
    public function scalar($db = null)
271
    {
272 24
        if ($this->emulateExecution) {
273 6
            return null;
274
        }
275
276 18
        return $this->createCommand($db)->queryScalar();
277
    }
278
279
    /**
280
     * Executes the query and returns the first column of the result.
281
     * @param Connection $db the database connection used to generate the SQL statement.
282
     * If this parameter is not given, the `db` application component will be used.
283
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
284
     */
285 67
    public function column($db = null)
286
    {
287 67
        if ($this->emulateExecution) {
288 6
            return [];
289
        }
290
291 61
        if ($this->indexBy === null) {
292 55
            return $this->createCommand($db)->queryColumn();
293
        }
294
295 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
296 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
297 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
298
            } else {
299
                $this->select[] = $this->indexBy;
300
            }
301
        }
302 9
        $rows = $this->createCommand($db)->queryAll();
303 9
        $results = [];
304 9
        foreach ($rows as $row) {
305 9
            $value = reset($row);
306
307 9
            if ($this->indexBy instanceof \Closure) {
308 3
                $results[call_user_func($this->indexBy, $row)] = $value;
309
            } else {
310 9
                $results[$row[$this->indexBy]] = $value;
311
            }
312
        }
313
314 9
        return $results;
315
    }
316
317
    /**
318
     * Returns the number of records.
319
     * @param string $q the COUNT expression. Defaults to '*'.
320
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
321
     * @param Connection $db the database connection used to generate the SQL statement.
322
     * If this parameter is not given (or null), the `db` application component will be used.
323
     * @return int|string number of records. The result may be a string depending on the
324
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
325
     */
326 87
    public function count($q = '*', $db = null)
327
    {
328 87
        if ($this->emulateExecution) {
329 6
            return 0;
330
        }
331
332 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 332 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...
333
    }
334
335
    /**
336
     * Returns the sum of the specified column values.
337
     * @param string $q the column name or expression.
338
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
339
     * @param Connection $db the database connection used to generate the SQL statement.
340
     * If this parameter is not given, the `db` application component will be used.
341
     * @return mixed the sum of the specified column values.
342
     */
343 9
    public function sum($q, $db = null)
344
    {
345 9
        if ($this->emulateExecution) {
346 6
            return 0;
347
        }
348
349 3
        return $this->queryScalar("SUM($q)", $db);
350
    }
351
352
    /**
353
     * Returns the average of the specified column values.
354
     * @param string $q the column name or expression.
355
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
356
     * @param Connection $db the database connection used to generate the SQL statement.
357
     * If this parameter is not given, the `db` application component will be used.
358
     * @return mixed the average of the specified column values.
359
     */
360 9
    public function average($q, $db = null)
361
    {
362 9
        if ($this->emulateExecution) {
363 6
            return 0;
364
        }
365
366 3
        return $this->queryScalar("AVG($q)", $db);
367
    }
368
369
    /**
370
     * Returns the minimum of the specified column values.
371
     * @param string $q the column name or expression.
372
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
373
     * @param Connection $db the database connection used to generate the SQL statement.
374
     * If this parameter is not given, the `db` application component will be used.
375
     * @return mixed the minimum of the specified column values.
376
     */
377 9
    public function min($q, $db = null)
378
    {
379 9
        return $this->queryScalar("MIN($q)", $db);
380
    }
381
382
    /**
383
     * Returns the maximum of the specified column values.
384
     * @param string $q the column name or expression.
385
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
386
     * @param Connection $db the database connection used to generate the SQL statement.
387
     * If this parameter is not given, the `db` application component will be used.
388
     * @return mixed the maximum of the specified column values.
389
     */
390 9
    public function max($q, $db = null)
391
    {
392 9
        return $this->queryScalar("MAX($q)", $db);
393
    }
394
395
    /**
396
     * Returns a value indicating whether the query result contains any row of data.
397
     * @param Connection $db the database connection used to generate the SQL statement.
398
     * If this parameter is not given, the `db` application component will be used.
399
     * @return bool whether the query result contains any row of data.
400
     */
401 67
    public function exists($db = null)
402
    {
403 67
        if ($this->emulateExecution) {
404 6
            return false;
405
        }
406 61
        $command = $this->createCommand($db);
407 61
        $params = $command->params;
408 61
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
409 61
        $command->bindValues($params);
410 61
        return (bool) $command->queryScalar();
411
    }
412
413
    /**
414
     * Queries a scalar value by setting [[select]] first.
415
     * Restores the value of select to make this query reusable.
416
     * @param string|Expression $selectExpression
417
     * @param Connection|null $db
418
     * @return bool|string
419
     */
420 87
    protected function queryScalar($selectExpression, $db)
421
    {
422 87
        if ($this->emulateExecution) {
423 6
            return null;
424
        }
425
426
        if (
427 87
            !$this->distinct
428 87
            && empty($this->groupBy)
429 87
            && empty($this->having)
430 87
            && empty($this->union)
431
        ) {
432 86
            $select = $this->select;
433 86
            $order = $this->orderBy;
434 86
            $limit = $this->limit;
435 86
            $offset = $this->offset;
436
437 86
            $this->select = [$selectExpression];
438 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...
439 86
            $this->limit = null;
440 86
            $this->offset = null;
441 86
            $command = $this->createCommand($db);
442
443 86
            $this->select = $select;
444 86
            $this->orderBy = $order;
445 86
            $this->limit = $limit;
446 86
            $this->offset = $offset;
447
448 86
            return $command->queryScalar();
449
        }
450
451 7
        return (new self())
452 7
            ->select([$selectExpression])
453 7
            ->from(['c' => $this])
454 7
            ->createCommand($db)
455 7
            ->queryScalar();
456
    }
457
458
    /**
459
     * Returns table names used in [[from]] indexed by aliases.
460
     * Both aliases and names are enclosed into {{ and }}.
461
     * @return string[] table names indexed by aliases
462
     * @throws \yii\base\InvalidConfigException
463
     * @since 2.0.12
464
     */
465 137
    public function getTablesUsedInFrom()
466
    {
467 137
        if (empty($this->from)) {
468
            return [];
469
        }
470
471 137
        if (is_array($this->from)) {
472 101
            $tableNames = $this->from;
473 36
        } elseif (is_string($this->from)) {
474 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
475 12
        } elseif ($this->from instanceof Expression) {
476 6
            $tableNames = [$this->from];
477
        } else {
478 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
479
        }
480
481
        // Clean up table names and aliases
482 131
        $cleanedUpTableNames = [];
483 131
        foreach ($tableNames as $alias => $tableName) {
484 131
            $tableNameString = null;
485 131
            if (is_string($tableName)) {
486 113
                $tableNameString = $tableName;
487 18
            } elseif ($tableName instanceof Expression) {
488 12
                $tableNameString = $tableName->expression;
489
            }
490
491 131
            if (!is_string($alias) && $tableNameString !== null) {
492
                $pattern = <<<PATTERN
493 119
~
494
^
495
\s*
496
(
497
    (?:['"`\[]|{{)
498
    .*?
499
    (?:['"`\]]|}})
500
    |
501
    \(.*?\)
502
    |
503
    .*?
504
)
505
(?:
506
    (?:
507
        \s+
508
        (?:as)?
509
        \s*
510
    )
511
    (
512
       (?:['"`\[]|{{)
513
        .*?
514
        (?:['"`\]]|}})
515
        |
516
        .*?
517
    )
518
)?
519
\s*
520
$
521
~iux
522
PATTERN;
523 119
                if (preg_match($pattern, $tableNameString, $matches)) {
524 119
                    if (isset($matches[2])) {
525 24
                        list(, $tableNameString, $alias) = $matches;
526
                    } else {
527 107
                        $tableNameString = $alias = $matches[1];
528
                    }
529
                }
530
            }
531
532 131
            if ($tableName instanceof Expression) {
533 12
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableNameString;
534 119
            } elseif ($tableName instanceof self) {
535 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
536
            } else {
537 131
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableNameString);
538
            }
539
        }
540
541 131
        return $cleanedUpTableNames;
542
    }
543
544
    /**
545
     * Ensures name is wrapped with {{ and }}
546
     * @param string $name
547
     * @return string
548
     */
549 131
    private function ensureNameQuoted($name)
550
    {
551 131
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
552 131
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
553 119
            return '{{' . $name . '}}';
554
        }
555
556 30
        return $name;
557
    }
558
559
    /**
560
     * Sets the SELECT part of the query.
561
     * @param string|array|Expression $columns the columns to be selected.
562
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
563
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
564
     * The method will automatically quote the column names unless a column contains some parenthesis
565
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
566
     * an [[Expression]] object.
567
     *
568
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
569
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
570
     *
571
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
572
     * does not need alias, do not use a string key).
573
     *
574
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
575
     * as a `Query` instance representing the sub-query.
576
     *
577
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
578
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
579
     * @return $this the query object itself
580
     */
581 366
    public function select($columns, $option = null)
582
    {
583 366
        if ($columns instanceof Expression) {
584 3
            $columns = [$columns];
585 363
        } elseif (!is_array($columns)) {
586 104
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
587
        }
588 366
        $this->select = $columns;
589 366
        $this->selectOption = $option;
590 366
        return $this;
591
    }
592
593
    /**
594
     * Add more columns to the SELECT part of the query.
595
     *
596
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
597
     * if you want to select all remaining columns too:
598
     *
599
     * ```php
600
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
601
     * ```
602
     *
603
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
604
     * details about the format of this parameter.
605
     * @return $this the query object itself
606
     * @see select()
607
     */
608 9
    public function addSelect($columns)
609
    {
610 9
        if ($columns instanceof Expression) {
611 3
            $columns = [$columns];
612 9
        } elseif (!is_array($columns)) {
613 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
614
        }
615 9
        if ($this->select === null) {
616 3
            $this->select = $columns;
617
        } else {
618 9
            $this->select = array_merge($this->select, $columns);
619
        }
620
621 9
        return $this;
622
    }
623
624
    /**
625
     * Sets the value indicating whether to SELECT DISTINCT or not.
626
     * @param bool $value whether to SELECT DISTINCT or not.
627
     * @return $this the query object itself
628
     */
629 6
    public function distinct($value = true)
630
    {
631 6
        $this->distinct = $value;
632 6
        return $this;
633
    }
634
635
    /**
636
     * Sets the FROM part of the query.
637
     * @param string|array|Expression $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
638
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
639
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
640
     * The method will automatically quote the table names unless it contains some parenthesis
641
     * (which means the table is given as a sub-query or DB expression).
642
     *
643
     * When the tables are specified as an array, you may also use the array keys as the table aliases
644
     * (if a table does not need alias, do not use a string key).
645
     *
646
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
647
     * as the alias for the sub-query.
648
     *
649
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[Expression]].
650
     *
651
     * Here are some examples:
652
     *
653
     * ```php
654
     * // SELECT * FROM  `user` `u`, `profile`;
655
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
656
     *
657
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
658
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
659
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
660
     *
661
     * // subquery can also be a string with plain SQL wrapped in parenthesis
662
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
663
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
664
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
665
     * ```
666
     *
667
     * @return $this the query object itself
668
     */
669 402
    public function from($tables)
670
    {
671 402
        if (is_string($tables)) {
672 369
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
673
        }
674 402
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type object<yii\db\Expression>. However, the property $from is declared as type array. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
675 402
        return $this;
676
    }
677
678
    /**
679
     * Sets the WHERE part of the query.
680
     *
681
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
682
     * specifying the values to be bound to the query.
683
     *
684
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
685
     *
686
     * @inheritdoc
687
     *
688
     * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
689
     * @param array $params the parameters (name => value) to be bound to the query.
690
     * @return $this the query object itself
691
     * @see andWhere()
692
     * @see orWhere()
693
     * @see QueryInterface::where()
694
     */
695 638
    public function where($condition, $params = [])
696
    {
697 638
        $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...
698 638
        $this->addParams($params);
699 638
        return $this;
700
    }
701
702
    /**
703
     * Adds an additional WHERE condition to the existing one.
704
     * The new condition and the existing one will be joined using the `AND` operator.
705
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
706
     * on how to specify this parameter.
707
     * @param array $params the parameters (name => value) to be bound to the query.
708
     * @return $this the query object itself
709
     * @see where()
710
     * @see orWhere()
711
     */
712 322
    public function andWhere($condition, $params = [])
713
    {
714 322
        if ($this->where === null) {
715 270
            $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...
716 100
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
717 38
            $this->where[] = $condition;
718
        } else {
719 100
            $this->where = ['and', $this->where, $condition];
720
        }
721 322
        $this->addParams($params);
722 322
        return $this;
723
    }
724
725
    /**
726
     * Adds an additional WHERE condition to the existing one.
727
     * The new condition and the existing one will be joined using the `OR` operator.
728
     * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
729
     * on how to specify this parameter.
730
     * @param array $params the parameters (name => value) to be bound to the query.
731
     * @return $this the query object itself
732
     * @see where()
733
     * @see andWhere()
734
     */
735 7
    public function orWhere($condition, $params = [])
736
    {
737 7
        if ($this->where === null) {
738
            $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...
739
        } else {
740 7
            $this->where = ['or', $this->where, $condition];
741
        }
742 7
        $this->addParams($params);
743 7
        return $this;
744
    }
745
746
    /**
747
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
748
     *
749
     * It adds an additional WHERE condition for the given field and determines the comparison operator
750
     * based on the first few characters of the given value.
751
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
752
     * The new condition and the existing one will be joined using the `AND` operator.
753
     *
754
     * The comparison operator is intelligently determined based on the first few characters in the given value.
755
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
756
     *
757
     * - `<`: the column must be less than the given value.
758
     * - `>`: the column must be greater than the given value.
759
     * - `<=`: the column must be less than or equal to the given value.
760
     * - `>=`: the column must be greater than or equal to the given value.
761
     * - `<>`: the column must not be the same as the given value.
762
     * - `=`: the column must be equal to the given value.
763
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
764
     *
765
     * @param string $name the column name.
766
     * @param string $value the column value optionally prepended with the comparison operator.
767
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
768
     * Defaults to `=`, performing an exact match.
769
     * @return $this The query object itself
770
     * @since 2.0.8
771
     */
772 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
773
    {
774 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
775 3
            $operator = $matches[1];
776 3
            $value = substr($value, strlen($operator));
777
        } else {
778 3
            $operator = $defaultOperator;
779
        }
780
781 3
        return $this->andFilterWhere([$operator, $name, $value]);
782
    }
783
784
    /**
785
     * Appends a JOIN part to the query.
786
     * The first parameter specifies what type of join it is.
787
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
788
     * @param string|array $table the table to be joined.
789
     *
790
     * Use a string to represent the name of the table to be joined.
791
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
792
     * The method will automatically quote the table name unless it contains some parenthesis
793
     * (which means the table is given as a sub-query or DB expression).
794
     *
795
     * Use an array to represent joining with a sub-query. The array must contain only one element.
796
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
797
     * represents the alias for the sub-query.
798
     *
799
     * @param string|array $on the join condition that should appear in the ON part.
800
     * Please refer to [[where()]] on how to specify this parameter.
801
     *
802
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
803
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
804
     * match the `post.author_id` column value against the string `'user.id'`.
805
     * It is recommended to use the string syntax here which is more suited for a join:
806
     *
807
     * ```php
808
     * 'post.author_id = user.id'
809
     * ```
810
     *
811
     * @param array $params the parameters (name => value) to be bound to the query.
812
     * @return $this the query object itself
813
     */
814 48
    public function join($type, $table, $on = '', $params = [])
815
    {
816 48
        $this->join[] = [$type, $table, $on];
817 48
        return $this->addParams($params);
818
    }
819
820
    /**
821
     * Appends an INNER JOIN part to the query.
822
     * @param string|array $table the table to be joined.
823
     *
824
     * Use a string to represent the name of the table to be joined.
825
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
826
     * The method will automatically quote the table name unless it contains some parenthesis
827
     * (which means the table is given as a sub-query or DB expression).
828
     *
829
     * Use an array to represent joining with a sub-query. The array must contain only one element.
830
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
831
     * represents the alias for the sub-query.
832
     *
833
     * @param string|array $on the join condition that should appear in the ON part.
834
     * Please refer to [[join()]] on how to specify this parameter.
835
     * @param array $params the parameters (name => value) to be bound to the query.
836
     * @return $this the query object itself
837
     */
838 3
    public function innerJoin($table, $on = '', $params = [])
839
    {
840 3
        $this->join[] = ['INNER JOIN', $table, $on];
841 3
        return $this->addParams($params);
842
    }
843
844
    /**
845
     * Appends a LEFT OUTER JOIN part to the query.
846
     * @param string|array $table the table to be joined.
847
     *
848
     * Use a string to represent the name of the table to be joined.
849
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
850
     * The method will automatically quote the table name unless it contains some parenthesis
851
     * (which means the table is given as a sub-query or DB expression).
852
     *
853
     * Use an array to represent joining with a sub-query. The array must contain only one element.
854
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
855
     * represents the alias for the sub-query.
856
     *
857
     * @param string|array $on the join condition that should appear in the ON part.
858
     * Please refer to [[join()]] on how to specify this parameter.
859
     * @param array $params the parameters (name => value) to be bound to the query
860
     * @return $this the query object itself
861
     */
862 3
    public function leftJoin($table, $on = '', $params = [])
863
    {
864 3
        $this->join[] = ['LEFT JOIN', $table, $on];
865 3
        return $this->addParams($params);
866
    }
867
868
    /**
869
     * Appends a RIGHT OUTER JOIN part to the query.
870
     * @param string|array $table the table to be joined.
871
     *
872
     * Use a string to represent the name of the table to be joined.
873
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
874
     * The method will automatically quote the table name unless it contains some parenthesis
875
     * (which means the table is given as a sub-query or DB expression).
876
     *
877
     * Use an array to represent joining with a sub-query. The array must contain only one element.
878
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
879
     * represents the alias for the sub-query.
880
     *
881
     * @param string|array $on the join condition that should appear in the ON part.
882
     * Please refer to [[join()]] on how to specify this parameter.
883
     * @param array $params the parameters (name => value) to be bound to the query
884
     * @return $this the query object itself
885
     */
886
    public function rightJoin($table, $on = '', $params = [])
887
    {
888
        $this->join[] = ['RIGHT JOIN', $table, $on];
889
        return $this->addParams($params);
890
    }
891
892
    /**
893
     * Sets the GROUP BY part of the query.
894
     * @param string|array|Expression $columns the columns to be grouped by.
895
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
896
     * The method will automatically quote the column names unless a column contains some parenthesis
897
     * (which means the column contains a DB expression).
898
     *
899
     * Note that if your group-by is an expression containing commas, you should always use an array
900
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
901
     * the group-by columns.
902
     *
903
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
904
     * @return $this the query object itself
905
     * @see addGroupBy()
906
     */
907 24
    public function groupBy($columns)
908
    {
909 24
        if ($columns instanceof Expression) {
910 3
            $columns = [$columns];
911 24
        } elseif (!is_array($columns)) {
912 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
913
        }
914 24
        $this->groupBy = $columns;
915 24
        return $this;
916
    }
917
918
    /**
919
     * Adds additional group-by columns to the existing ones.
920
     * @param string|array $columns additional columns to be grouped by.
921
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
922
     * The method will automatically quote the column names unless a column contains some parenthesis
923
     * (which means the column contains a DB expression).
924
     *
925
     * Note that if your group-by is an expression containing commas, you should always use an array
926
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
927
     * the group-by columns.
928
     *
929
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
930
     * @return $this the query object itself
931
     * @see groupBy()
932
     */
933 3
    public function addGroupBy($columns)
934
    {
935 3
        if ($columns instanceof Expression) {
936
            $columns = [$columns];
937 3
        } elseif (!is_array($columns)) {
938 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
939
        }
940 3
        if ($this->groupBy === null) {
941
            $this->groupBy = $columns;
942
        } else {
943 3
            $this->groupBy = array_merge($this->groupBy, $columns);
944
        }
945
946 3
        return $this;
947
    }
948
949
    /**
950
     * Sets the HAVING part of the query.
951
     * @param string|array|Expression $condition the conditions to be put after HAVING.
952
     * Please refer to [[where()]] on how to specify this parameter.
953
     * @param array $params the parameters (name => value) to be bound to the query.
954
     * @return $this the query object itself
955
     * @see andHaving()
956
     * @see orHaving()
957
     */
958 10
    public function having($condition, $params = [])
959
    {
960 10
        $this->having = $condition;
961 10
        $this->addParams($params);
962 10
        return $this;
963
    }
964
965
    /**
966
     * Adds an additional HAVING condition to the existing one.
967
     * The new condition and the existing one will be joined using the `AND` operator.
968
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
969
     * on how to specify this parameter.
970
     * @param array $params the parameters (name => value) to be bound to the query.
971
     * @return $this the query object itself
972
     * @see having()
973
     * @see orHaving()
974
     */
975 3
    public function andHaving($condition, $params = [])
976
    {
977 3
        if ($this->having === null) {
978
            $this->having = $condition;
979
        } else {
980 3
            $this->having = ['and', $this->having, $condition];
981
        }
982 3
        $this->addParams($params);
983 3
        return $this;
984
    }
985
986
    /**
987
     * Adds an additional HAVING condition to the existing one.
988
     * The new condition and the existing one will be joined using the `OR` operator.
989
     * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
990
     * on how to specify this parameter.
991
     * @param array $params the parameters (name => value) to be bound to the query.
992
     * @return $this the query object itself
993
     * @see having()
994
     * @see andHaving()
995
     */
996 3
    public function orHaving($condition, $params = [])
997
    {
998 3
        if ($this->having === null) {
999
            $this->having = $condition;
1000
        } else {
1001 3
            $this->having = ['or', $this->having, $condition];
1002
        }
1003 3
        $this->addParams($params);
1004 3
        return $this;
1005
    }
1006
1007
    /**
1008
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1009
     *
1010
     * This method is similar to [[having()]]. The main difference is that this method will
1011
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1012
     * for building query conditions based on filter values entered by users.
1013
     *
1014
     * The following code shows the difference between this method and [[having()]]:
1015
     *
1016
     * ```php
1017
     * // HAVING `age`=:age
1018
     * $query->filterHaving(['name' => null, 'age' => 20]);
1019
     * // HAVING `age`=:age
1020
     * $query->having(['age' => 20]);
1021
     * // HAVING `name` IS NULL AND `age`=:age
1022
     * $query->having(['name' => null, 'age' => 20]);
1023
     * ```
1024
     *
1025
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1026
     *
1027
     * @param array $condition the conditions that should be put in the HAVING part.
1028
     * See [[having()]] on how to specify this parameter.
1029
     * @return $this the query object itself
1030
     * @see having()
1031
     * @see andFilterHaving()
1032
     * @see orFilterHaving()
1033
     * @since 2.0.11
1034
     */
1035 6
    public function filterHaving(array $condition)
1036
    {
1037 6
        $condition = $this->filterCondition($condition);
1038 6
        if ($condition !== []) {
1039 6
            $this->having($condition);
1040
        }
1041
1042 6
        return $this;
1043
    }
1044
1045
    /**
1046
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1047
     * The new condition and the existing one will be joined using the `AND` operator.
1048
     *
1049
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1050
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1051
     * for building query conditions based on filter values entered by users.
1052
     *
1053
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1054
     * on how to specify this parameter.
1055
     * @return $this the query object itself
1056
     * @see filterHaving()
1057
     * @see orFilterHaving()
1058
     * @since 2.0.11
1059
     */
1060 6
    public function andFilterHaving(array $condition)
1061
    {
1062 6
        $condition = $this->filterCondition($condition);
1063 6
        if ($condition !== []) {
1064
            $this->andHaving($condition);
1065
        }
1066
1067 6
        return $this;
1068
    }
1069
1070
    /**
1071
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1072
     * The new condition and the existing one will be joined using the `OR` operator.
1073
     *
1074
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1075
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1076
     * for building query conditions based on filter values entered by users.
1077
     *
1078
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1079
     * on how to specify this parameter.
1080
     * @return $this the query object itself
1081
     * @see filterHaving()
1082
     * @see andFilterHaving()
1083
     * @since 2.0.11
1084
     */
1085 6
    public function orFilterHaving(array $condition)
1086
    {
1087 6
        $condition = $this->filterCondition($condition);
1088 6
        if ($condition !== []) {
1089
            $this->orHaving($condition);
1090
        }
1091
1092 6
        return $this;
1093
    }
1094
1095
    /**
1096
     * Appends a SQL statement using UNION operator.
1097
     * @param string|Query $sql the SQL statement to be appended using UNION
1098
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1099
     * @return $this the query object itself
1100
     */
1101 10
    public function union($sql, $all = false)
1102
    {
1103 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1104 10
        return $this;
1105
    }
1106
1107
    /**
1108
     * Sets the parameters to be bound to the query.
1109
     * @param array $params list of query parameter values indexed by parameter placeholders.
1110
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1111
     * @return $this the query object itself
1112
     * @see addParams()
1113
     */
1114 6
    public function params($params)
1115
    {
1116 6
        $this->params = $params;
1117 6
        return $this;
1118
    }
1119
1120
    /**
1121
     * Adds additional parameters to be bound to the query.
1122
     * @param array $params list of query parameter values indexed by parameter placeholders.
1123
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1124
     * @return $this the query object itself
1125
     * @see params()
1126
     */
1127 882
    public function addParams($params)
1128
    {
1129 882
        if (!empty($params)) {
1130 71
            if (empty($this->params)) {
1131 71
                $this->params = $params;
1132
            } else {
1133 6
                foreach ($params as $name => $value) {
1134 6
                    if (is_int($name)) {
1135
                        $this->params[] = $value;
1136
                    } else {
1137 6
                        $this->params[$name] = $value;
1138
                    }
1139
                }
1140
            }
1141
        }
1142
1143 882
        return $this;
1144
    }
1145
1146
    /**
1147
     * Creates a new Query object and copies its property values from an existing one.
1148
     * The properties being copies are the ones to be used by query builders.
1149
     * @param Query $from the source query object
1150
     * @return Query the new Query object
1151
     */
1152 346
    public static function create($from)
1153
    {
1154 346
        return new self([
1155 346
            'where' => $from->where,
1156 346
            'limit' => $from->limit,
1157 346
            'offset' => $from->offset,
1158 346
            'orderBy' => $from->orderBy,
1159 346
            'indexBy' => $from->indexBy,
1160 346
            'select' => $from->select,
1161 346
            'selectOption' => $from->selectOption,
1162 346
            'distinct' => $from->distinct,
1163 346
            'from' => $from->from,
1164 346
            'groupBy' => $from->groupBy,
1165 346
            'join' => $from->join,
1166 346
            'having' => $from->having,
1167 346
            'union' => $from->union,
1168 346
            'params' => $from->params,
1169
        ]);
1170
    }
1171
}
1172