Passed
Push — master ( 364bec...91edba )
by Wilmer
02:56
created

ActiveQuery::prepare()   C

Complexity

Conditions 15
Paths 192

Size

Total Lines 77
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 17.0986

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 77
ccs 30
cts 38
cp 0.7895
rs 5.15
c 0
b 0
f 0
cc 15
nc 192
nop 1
crap 17.0986

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
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord;
6
7
use ReflectionException;
8
use Throwable;
9
use Yiisoft\Db\Command\Command;
10
use Yiisoft\Db\Exception\Exception;
11
use Yiisoft\Db\Exception\InvalidArgumentException;
12
use Yiisoft\Db\Exception\NotSupportedException;
13
use Yiisoft\Db\Expression\ExpressionInterface;
14
use Yiisoft\Db\Query\Query;
15
use Yiisoft\Db\Query\QueryBuilder;
16
use Yiisoft\Db\Exception\InvalidConfigException;
17
18
use function array_merge;
19
use function array_values;
20
use function count;
21
use function get_class;
22
use function implode;
23
use function in_array;
24
use function is_array;
25
use function is_int;
26
use function is_string;
27
use function preg_match;
28
use function reset;
29
use function serialize;
30
use function strpos;
31
use function substr;
32
33
/**
34
 * ActiveQuery represents a DB query associated with an Active Record class.
35
 *
36
 * An ActiveQuery can be a normal query or be used in a relational context.
37
 *
38
 * ActiveQuery instances are usually created by {@see ActiveRecord::find()} and {@see ActiveRecord::findBySql()}.
39
 * Relational queries are created by {@see ActiveRecord::hasOne()} and {@see ActiveRecord::hasMany()}.
40
 *
41
 * Normal Query
42
 * ------------
43
 *
44
 * ActiveQuery mainly provides the following methods to retrieve the query results:
45
 *
46
 * - {@see one()}: returns a single record populated with the first row of data.
47
 * - {@see all()}: returns all records based on the query results.
48
 * - {@see count()}: returns the number of records.
49
 * - {@see sum()}: returns the sum over the specified column.
50
 * - {@see average()}: returns the average over the specified column.
51
 * - {@see min()}: returns the min over the specified column.
52
 * - {@see max()}: returns the max over the specified column.
53
 * - {@see scalar()}: returns the value of the first column in the first row of the query result.
54
 * - {@see column()}: returns the value of the first column in the query result.
55
 * - {@see exists()}: returns a value indicating whether the query result has data or not.
56
 *
57
 * Because ActiveQuery extends from {@see Query}, one can use query methods, such as {@see where()}, {@see orderBy()} to
58
 * customize the query options.
59
 *
60
 * ActiveQuery also provides the following additional query options:
61
 *
62
 * - {@see with()}: list of relations that this query should be performed with.
63
 * - {@see joinWith()}: reuse a relation query definition to add a join to a query.
64
 * - {@see indexBy()}: the name of the column by which the query result should be indexed.
65
 * - {@see asArray()}: whether to return each record as an array.
66
 *
67
 * These options can be configured using methods of the same name. For example:
68
 *
69
 * ```php
70
 * $customers = Customer::find()->with('orders')->asArray()->all();
71
 * ```
72
 *
73
 * Relational query
74
 * ----------------
75
 *
76
 * In relational context ActiveQuery represents a relation between two Active Record classes.
77
 *
78
 * Relational ActiveQuery instances are usually created by calling {@see ActiveRecord::hasOne()} and
79
 * {@see ActiveRecord::hasMany()}. An Active Record class declares a relation by defining a getter method which calls
80
 * one of the above methods and returns the created ActiveQuery object.
81
 *
82
 * A relation is specified by {@see link} which represents the association between columns of different tables; and the
83
 * multiplicity of the relation is indicated by {@see multiple}.
84
 *
85
 * If a relation involves a junction table, it may be specified by {@see via()} or {@see viaTable()} method.
86
 * These methods may only be called in a relational context. Same is true for {@see inverseOf()}, which marks a relation
87
 * as inverse of another relation and {@see onCondition()} which adds a condition that is to be added to relational
88
 * query join condition.
89
 */
90
class ActiveQuery extends Query implements ActiveQueryInterface
91
{
92
    use ActiveQueryTrait;
93
    use ActiveRelationTrait;
94
95
    protected string $modelClass;
96
    private ?string $sql = null;
97
    private $on;
98
    private array $joinWith = [];
99
100 560
    public function __construct(string $modelClass)
101
    {
102 560
        $this->modelClass = $modelClass;
103
104 560
        parent::__construct($modelClass::getConnection());
105 560
    }
106
107
    /**
108
     * Executes query and returns all results as an array.
109
     *
110
     * If null, the DB connection returned by {@see modelClass} will be used.
111
     *
112
     * @throws InvalidConfigException
113
     * @throws Exception
114
     * @throws InvalidArgumentException
115
     * @throws NotSupportedException
116
     *
117
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
118
     */
119 228
    public function all(): array
120
    {
121 228
        return parent::all();
122
    }
123
124
    /**
125
     * Prepares for building SQL.
126
     *
127
     * This method is called by {@see QueryBuilder} when it starts to build SQL from a query object.
128
     *
129
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
130
     *
131
     * @param QueryBuilder $builder
132
     *
133
     * @throws Exception
134
     * @throws InvalidArgumentException
135
     * @throws InvalidConfigException
136
     * @throws NotSupportedException
137
     * @throws ReflectionException
138
     *
139
     * @return Query a prepared query instance which will be used by {@see QueryBuilder} to build the SQL.
140
     */
141 428
    public function prepare(QueryBuilder $builder): Query
142
    {
143
        /**
144
         * NOTE: because the same ActiveQuery may be used to build different SQL statements (e.g. by ActiveDataProvider,
145
         * one for count query, the other for row data query, it is important to make sure the same ActiveQuery can be
146
         * used to build SQL statements multiple times.
147
         */
148 428
        if (!empty($this->joinWith)) {
149 52
            $this->buildJoinWith();
150
            /** clean it up to avoid issue {@see https://github.com/yiisoft/yii2/issues/2687} */
151 52
            $this->joinWith = [];
152
        }
153
154 428
        if (empty($this->getFrom())) {
155 400
            $this->from = [$this->getPrimaryTableName()];
156
        }
157
158 428
        if (empty($this->getSelect()) && !empty($this->getJoin())) {
159 48
            [, $alias] = $this->getTableNameAndAlias();
160
161 48
            $this->select(["$alias.*"]);
162
        }
163
164 428
        if ($this->primaryModel === null) {
165
            /** eager loading */
166 420
            $query = Query::create($this->modelClass::getConnection(), $this);
167
        } else {
168
            /** lazy loading of a relation */
169 128
            $where = $this->getWhere();
170
171 128
            if ($this->via instanceof self) {
172
                /** via junction table */
173 20
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
174
175 20
                $this->filterByModels($viaModels);
176 116
            } elseif (is_array($this->via)) {
177
                /**
178
                 * via relation
179
                 *
180
                 * @var $viaQuery ActiveQuery
181
                 */
182 36
                [$viaName, $viaQuery, $viaCallableUsed] = $this->via;
183
184 36
                if ($viaQuery->getMultiple()) {
185 36
                    if ($viaCallableUsed) {
186 24
                        $viaModels = $viaQuery->all();
187 12
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
0 ignored issues
show
Bug introduced by
The method isRelationPopulated() does not exist on Yiisoft\ActiveRecord\ActiveRecordInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\ActiveRecord\ActiveRecordInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

187
                    } elseif ($this->primaryModel->/** @scrutinizer ignore-call */ isRelationPopulated($viaName)) {
Loading history...
188
                        $viaModels = $this->primaryModel->$viaName;
189
                    } else {
190 12
                        $viaModels = $viaQuery->all();
191 36
                        $this->primaryModel->populateRelation($viaName, $viaModels);
192
                    }
193
                } else {
194
                    if ($viaCallableUsed) {
195
                        $model = $viaQuery->one();
196
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
197
                        $model = $this->primaryModel->$viaName;
198
                    } else {
199
                        $model = $viaQuery->one();
200
                        $this->primaryModel->populateRelation($viaName, $model);
201
                    }
202
                    $viaModels = $model === null ? [] : [$model];
203
                }
204 36
                $this->filterByModels($viaModels);
205
            } else {
206 116
                $this->filterByModels([$this->primaryModel]);
207
            }
208
209 128
            $query = Query::create($this->modelClass::getConnection(), $this);
210 128
            $this->where($where);
211
        }
212
213 428
        if (!empty($this->on)) {
214 24
            $query->andWhere($this->on);
215
        }
216
217 428
        return $query;
218
    }
219
220
    /**
221
     * Converts the raw query results into the format as specified by this query.
222
     *
223
     * This method is internally used to convert the data fetched from database into the format as required by this
224
     * query.
225
     *
226
     * @param array $rows the raw query result from database.
227
     *
228
     * @throws Exception
229
     * @throws InvalidArgumentException
230
     * @throws InvalidConfigException
231
     * @throws NotSupportedException
232
     * @throws ReflectionException
233
     *
234
     * @return array the converted query result.
235
     */
236 348
    public function populate(array $rows): array
237
    {
238 348
        if (empty($rows)) {
239 69
            return [];
240
        }
241
242 336
        $models = $this->createModels($rows);
243
244 336
        if (!empty($this->join) && $this->getIndexBy() === null) {
245 36
            $models = $this->removeDuplicatedModels($models);
246
        }
247
248 336
        if (!empty($this->with)) {
249 99
            $this->findWith($this->with, $models);
250
        }
251
252 336
        if ($this->inverseOf !== null) {
253 16
            $this->addInverseRelations($models);
254
        }
255
256 336
        return parent::populate($models);
257
    }
258
259
    /**
260
     * Removes duplicated models by checking their primary key values.
261
     *
262
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
263
     *
264
     * @param array $models the models to be checked
265
     *
266
     * @throws Exception
267
     * @throws InvalidConfigException
268
     *
269
     * @return array the distinctive models
270
     */
271 36
    private function removeDuplicatedModels(array $models): array
272
    {
273 36
        $hash = [];
274
275
        /** @var $class ActiveRecord */
276 36
        $class = $this->modelClass;
277
278 36
        $pks = $class::primaryKey();
279
280 36
        if (count($pks) > 1) {
281
            /** composite primary key */
282 8
            foreach ($models as $i => $model) {
283 8
                $key = [];
284 8
                foreach ($pks as $pk) {
285 8
                    if (!isset($model[$pk])) {
286
                        /** do not continue if the primary key is not part of the result set */
287 4
                        break 2;
288
                    }
289 7
                    $key[] = $model[$pk];
290
                }
291
292 4
                $key = serialize($key);
293
294 4
                if (isset($hash[$key])) {
295
                    unset($models[$i]);
296
                } else {
297 4
                    $hash[$key] = true;
298
                }
299
            }
300 32
        } elseif (empty($pks)) {
301
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
302
        } else {
303
            /** single column primary key */
304 32
            $pk = reset($pks);
305
306 32
            foreach ($models as $i => $model) {
307 32
                if (!isset($model[$pk])) {
308
                    /** do not continue if the primary key is not part of the result set */
309 4
                    break;
310
                }
311
312 28
                $key = $model[$pk];
313
314 28
                if (isset($hash[$key])) {
315 16
                    unset($models[$i]);
316 28
                } elseif ($key !== null) {
317 28
                    $hash[$key] = true;
318
                }
319
            }
320
        }
321
322 36
        return array_values($models);
323
    }
324
325
    /**
326
     * Executes query and returns a single row of result.
327
     *
328
     * @throws Exception
329
     * @throws InvalidArgumentException
330
     * @throws InvalidConfigException
331
     * @throws NotSupportedException
332
     * @throws ReflectionException
333
     *
334
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of {@see asArray}, the
335
     * query result may be either an array or an ActiveRecord object. `null` will be returned if the query results in
336
     * nothing.
337
     */
338 264
    public function one()
339
    {
340 264
        $row = parent::one();
341
342 264
        if ($row !== false) {
0 ignored issues
show
introduced by
The condition $row !== false is always true.
Loading history...
343 260
            $models = $this->populate([$row]);
344
345 260
            return reset($models) ?: null;
346
        }
347
348 32
        return null;
349
    }
350
351
    /**
352
     * Creates a DB command that can be used to execute this query.
353
     *
354
     * @return Command the created DB command instance.
355
     */
356 380
    public function createCommand(): Command
357
    {
358 380
        if ($this->sql === null) {
359 376
            [$sql, $params] = $this->modelClass::getConnection()->getQueryBuilder()->build($this);
360
        } else {
361 4
            $sql = $this->sql;
362 4
            $params = $this->params;
363
        }
364
365 380
        $command = $this->modelClass::getConnection()->createCommand($sql, $params);
366
367 380
        $this->setCommandCache($command);
368
369 380
        return $command;
370
    }
371
372
    /**
373
     * Queries a scalar value by setting {@see select} first.
374
     *
375
     * Restores the value of select to make this query reusable.
376
     *
377
     * @param string|ExpressionInterface $selectExpression
378
     *
379
     * @throws Exception
380
     * @throws InvalidArgumentException
381
     * @throws InvalidConfigException
382
     * @throws NotSupportedException
383
     * @throws Throwable
384
     *
385
     * @return bool|string
386
     */
387 61
    protected function queryScalar($selectExpression)
388
    {
389 61
        if ($this->sql === null) {
390 57
            return parent::queryScalar($selectExpression);
391
        }
392
393 4
        $command = (new Query($this->modelClass::getConnection()))->select([$selectExpression])
394 4
            ->from(['c' => "({$this->sql})"])
395 4
            ->params($this->params)
396 4
            ->createCommand();
397
398 4
        $this->setCommandCache($command);
399
400 4
        return $command->queryScalar();
401
    }
402
403
    /**
404
     * Joins with the specified relations.
405
     *
406
     * This method allows you to reuse existing relation definitions to perform JOIN queries. Based on the definition of
407
     * the specified relation(s), the method will append one or multiple JOIN statements to the current query.
408
     *
409
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
410
     * which is equivalent to calling {@see with()} using the specified relations.
411
     *
412
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
413
     *
414
     * This method differs from {@see with()} in that it will build up and execute a JOIN SQL statement
415
     * for the primary table. And when `$eagerLoading` is true, it will call {@see with()} in addition with the
416
     * specified relations.
417
     *
418
     * @param string|array $with the relations to be joined. This can either be a string, representing a relation name
419
     * or an array with the following semantics:
420
     *
421
     * - Each array element represents a single relation.
422
     * - You may specify the relation name as the array key and provide an anonymous functions that can be used to
423
     * modify the relation queries on-the-fly as the array value.
424
     * - If a relation query does not need modification, you may use the relation name as the array value.
425
     *
426
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
427
     *
428
     * Sub-relations can also be specified, see {@see with()} for the syntax.
429
     *
430
     * In the following you find some examples:
431
     *
432
     * ```php
433
     * // find all orders that contain books, and eager loading "books"
434
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
435
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
436
     * Order::find()->joinWith([
437
     *     'books' => function (\Yiisoft\ActiveRecord\ActiveQuery $query) {
438
     *         $query->orderBy('item.name');
439
     *     }
440
     * ])->all();
441
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
442
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
443
     * ```
444
     *
445
     * @param bool|array $eagerLoading whether to eager load the relations specified in `$with`. When this is a boolean,
446
     * it applies to all relations specified in `$with`. Use an array to explicitly list which relations in `$with` need
447
     * to be eagerly loaded.  Note, that this does not mean, that the relations are populated from the query result. An
448
     * extra query will still be performed to bring in the related data. Defaults to `true`.
449
     * @param string|array $joinType the join type of the relations specified in `$with`.  When this is a string, it
450
     * applies to all relations specified in `$with`. Use an array in the format of `relationName => joinType` to
451
     * specify different join types for different relations.
452
     *
453
     * @return $this the query object itself.
454
     */
455 64
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN'): self
456
    {
457 64
        $relations = [];
458
459 64
        foreach ((array) $with as $name => $callback) {
460 64
            if (is_int($name)) {
461 64
                $name = $callback;
462 64
                $callback = null;
463
            }
464
465 64
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
466
                /** relation is defined with an alias, adjust callback to apply alias */
467 12
                [, $relation, $alias] = $matches;
468
469 12
                $name = $relation;
470
471 12
                $callback = static function ($query) use ($callback, $alias) {
472
                    /** @var $query ActiveQuery */
473 12
                    $query->alias($alias);
474
475 12
                    if ($callback !== null) {
476 12
                        $callback($query);
477
                    }
478 12
                };
479
            }
480
481 64
            if ($callback === null) {
482 64
                $relations[] = $name;
483
            } else {
484 20
                $relations[$name] = $callback;
485
            }
486
        }
487
488 64
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
489
490 64
        return $this;
491
    }
492
493 52
    private function buildJoinWith(): void
494
    {
495 52
        $join = $this->join;
496
497 52
        $this->join = [];
498
499
        /** @var $modelClass ActiveRecordInterface */
500 52
        $modelClass = $this->modelClass;
501
502 52
        $model = $modelClass::instance();
0 ignored issues
show
Bug introduced by
The method instance() does not exist on Yiisoft\ActiveRecord\ActiveRecordInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\ActiveRecord\ActiveRecordInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

502
        /** @scrutinizer ignore-call */ 
503
        $model = $modelClass::instance();
Loading history...
503
504 52
        foreach ($this->joinWith as [$with, $eagerLoading, $joinType]) {
505 52
            $this->joinWithRelations($model, $with, $joinType);
506
507 52
            if (is_array($eagerLoading)) {
508
                foreach ($with as $name => $callback) {
509
                    if (is_int($name)) {
510
                        if (!in_array($callback, $eagerLoading, true)) {
511
                            unset($with[$name]);
512
                        }
513
                    } elseif (!in_array($name, $eagerLoading, true)) {
514
                        unset($with[$name]);
515
                    }
516
                }
517 52
            } elseif (!$eagerLoading) {
518 16
                $with = [];
519
            }
520
521 52
            $this->with($with);
522
        }
523
524
        /**
525
         * remove duplicated joins added by joinWithRelations that may be added e.g. when joining a relation and a via
526
         * relation at the same time.
527
         */
528 52
        $uniqueJoins = [];
529
530 52
        foreach ($this->join as $j) {
531 52
            $uniqueJoins[serialize($j)] = $j;
532
        }
533
534 52
        $this->join = array_values($uniqueJoins);
535
536 52
        if (!empty($join)) {
537
            /**
538
             * append explicit join to joinWith()
539
             *
540
             * {@see https://github.com/yiisoft/yii2/issues/2880}
541
             */
542
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
543
        }
544 52
    }
545
546
    /**
547
     * Inner joins with the specified relations.
548
     *
549
     * This is a shortcut method to {@see joinWith()} with the join type set as "INNER JOIN". Please refer to
550
     * {@see joinWith()} for detailed usage of this method.
551
     *
552
     * @param string|array $with the relations to be joined with.
553
     * @param bool|array $eagerLoading whether to eager load the relations. Note, that this does not mean, that the
554
     * relations are populated from the query result. An extra query will still be performed to bring in the related
555
     * data.
556
     *
557
     * @return $this the query object itself.
558
     *
559
     * {@see joinWith()}
560
     */
561 16
    public function innerJoinWith($with, $eagerLoading = true): self
562
    {
563 16
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
564
    }
565
566
    /**
567
     * Modifies the current query by adding join fragments based on the given relations.
568
     *
569
     * @param ActiveRecord $model the primary model.
570
     * @param array $with the relations to be joined.
571
     * @param string|array $joinType the join type.
572
     *
573
     * @throws InvalidArgumentException
574
     * @throws ReflectionException
575
     */
576 52
    private function joinWithRelations(ActiveRecord $model, array $with, $joinType): void
577
    {
578 52
        $relations = [];
579
580 52
        foreach ($with as $name => $callback) {
581 52
            if (is_int($name)) {
582 52
                $name = $callback;
583 52
                $callback = null;
584
            }
585
586 52
            $primaryModel = $model;
587 52
            $parent = $this;
588 52
            $prefix = '';
589
590 52
            while (($pos = strpos($name, '.')) !== false) {
591 8
                $childName = substr($name, $pos + 1);
592 8
                $name = substr($name, 0, $pos);
593 8
                $fullName = $prefix === '' ? $name : "$prefix.$name";
594
595 8
                if (!isset($relations[$fullName])) {
596
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
597
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
598
                } else {
599 8
                    $relation = $relations[$fullName];
600
                }
601
602
                /** @var $relationModelClass ActiveRecordInterface */
603 8
                $relationModelClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
604
605 8
                $primaryModel = new $relationModelClass();
606
607 8
                $parent = $relation;
608 8
                $prefix = $fullName;
609 8
                $name = $childName;
610
            }
611
612 52
            $fullName = $prefix === '' ? $name : "$prefix.$name";
613
614 52
            if (!isset($relations[$fullName])) {
615 52
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
616
617 52
                if ($callback !== null) {
618 20
                    $callback($relation);
619
                }
620
621 52
                if (!empty($relation->joinWith)) {
0 ignored issues
show
Bug introduced by
Accessing joinWith on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
622 8
                    $relation->buildJoinWith();
0 ignored issues
show
Bug introduced by
The method buildJoinWith() does not exist on Yiisoft\ActiveRecord\ActiveQueryInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\ActiveRecord\ActiveQueryInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

622
                    $relation->/** @scrutinizer ignore-call */ 
623
                               buildJoinWith();
Loading history...
623
                }
624
625 52
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
626
            }
627
        }
628 52
    }
629
630
    /**
631
     * Returns the join type based on the given join type parameter and the relation name.
632
     *
633
     * @param string|array $joinType the given join type(s).
634
     * @param string $name relation name.
635
     *
636
     * @return string the real join type.
637
     */
638 52
    private function getJoinType($joinType, string $name): string
639
    {
640 52
        if (is_array($joinType) && isset($joinType[$name])) {
641
            return $joinType[$name];
642
        }
643
644 52
        return is_string($joinType) ? $joinType : 'INNER JOIN';
645
    }
646
647
    /**
648
     * Returns the table name and the table alias for {@see modelClass}.
649
     *
650
     * @return array the table name and the table alias.
651
     */
652 116
    private function getTableNameAndAlias(): array
653
    {
654 116
        if (empty($this->from)) {
655 108
            $tableName = $this->getPrimaryTableName();
656
        } else {
657 60
            $tableName = '';
658
659 60
            foreach ($this->from as $alias => $tableName) {
660 60
                if (is_string($alias)) {
661 20
                    return [$tableName, $alias];
662
                }
663 52
                break;
664
            }
665
        }
666
667 112
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
668 4
            $alias = $matches[2];
669
        } else {
670 112
            $alias = $tableName;
671
        }
672
673 112
        return [$tableName, $alias];
674
    }
675
676
    /**
677
     * Joins a parent query with a child query.
678
     *
679
     * The current query object will be modified accordingly.
680
     *
681
     * @param ActiveQuery $parent
682
     * @param ActiveQuery $child
683
     * @param string $joinType
684
     */
685 52
    private function joinWithRelation(ActiveQuery $parent, ActiveQuery $child, string $joinType): void
686
    {
687 52
        $via = $child->via;
688 52
        $child->via = null;
689
690 52
        if ($via instanceof self) {
691
            /** via table */
692 12
            $this->joinWithRelation($parent, $via, $joinType);
693 12
            $this->joinWithRelation($via, $child, $joinType);
694
695 12
            return;
696
        }
697
698 52
        if (is_array($via)) {
699
            /** via relation */
700 16
            $this->joinWithRelation($parent, $via[1], $joinType);
701 16
            $this->joinWithRelation($via[1], $child, $joinType);
702
703 16
            return;
704
        }
705
706 52
        [$parentTable, $parentAlias] = $parent->getTableNameAndAlias();
707 52
        [$childTable, $childAlias] = $child->getTableNameAndAlias();
708
709 52
        if (!empty($child->link)) {
710 52
            if (strpos($parentAlias, '{{') === false) {
711 52
                $parentAlias = '{{' . $parentAlias . '}}';
712
            }
713
714 52
            if (strpos($childAlias, '{{') === false) {
715 52
                $childAlias = '{{' . $childAlias . '}}';
716
            }
717
718 52
            $on = [];
719
720 52
            foreach ($child->link as $childColumn => $parentColumn) {
721 52
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
722
            }
723
724 52
            $on = implode(' AND ', $on);
725
726 52
            if (!empty($child->on)) {
727 52
                $on = ['and', $on, $child->on];
728
            }
729
        } else {
730
            $on = $child->on;
731
        }
732
733 52
        $this->join($joinType, empty($child->getFrom()) ? $childTable : $child->getFrom(), $on);
734
735 52
        if (!empty($child->getWhere())) {
736 8
            $this->andWhere($child->getWhere());
737
        }
738
739 52
        if (!empty($child->getHaving())) {
740
            $this->andHaving($child->getHaving());
741
        }
742
743 52
        if (!empty($child->getOrderBy())) {
744 16
            $this->addOrderBy($child->getOrderBy());
745
        }
746
747 52
        if (!empty($child->getGroupBy())) {
748
            $this->addGroupBy($child->getGroupBy());
749
        }
750
751 52
        if (!empty($child->getParams())) {
752
            $this->addParams($child->getParams());
753
        }
754
755 52
        if (!empty($child->getJoin())) {
756 8
            foreach ($child->getJoin() as $join) {
757 8
                $this->join[] = $join;
758
            }
759
        }
760
761 52
        if (!empty($child->getUnion())) {
762
            foreach ($child->getUnion() as $union) {
763
                $this->union[] = $union;
764
            }
765
        }
766 52
    }
767
768
    /**
769
     * Sets the ON condition for a relational query.
770
     *
771
     * The condition will be used in the ON part when {@see ActiveQuery::joinWith()} is called.
772
     *
773
     * Otherwise, the condition will be used in the WHERE part of a query.
774
     *
775
     * Use this method to specify additional conditions when declaring a relation in the {@see ActiveRecord} class:
776
     *
777
     * ```php
778
     * public function getActiveUsers()
779
     * {
780
     *     return $this->hasMany(User::class, ['id' => 'user_id'])
781
     *         ->onCondition(['active' => true]);
782
     * }
783
     * ```
784
     *
785
     * Note that this condition is applied in case of a join as well as when fetching the related records. This only
786
     * fields of the related table can be used in the condition. Trying to access fields of the primary record will
787
     * cause an error in a non-join-query.
788
     *
789
     * @param string|array $condition the ON condition. Please refer to {@see Query::where()} on how to specify this
790
     * parameter.
791
     * @param array $params the parameters (name => value) to be bound to the query.
792
     *
793
     * @return $this the query object itself
794
     */
795 28
    public function onCondition($condition, array $params = []): self
796
    {
797 28
        $this->on = $condition;
798
799 28
        $this->addParams($params);
800
801 28
        return $this;
802
    }
803
804
    /**
805
     * Adds an additional ON condition to the existing one.
806
     *
807
     * The new condition and the existing one will be joined using the 'AND' operator.
808
     *
809
     * @param string|array $condition the new ON condition. Please refer to {@see where()} on how to specify this
810
     * parameter.
811
     * @param array $params the parameters (name => value) to be bound to the query.
812
     *
813
     * @return $this the query object itself.
814
     *
815
     * {@see onCondition()}
816
     * {@see orOnCondition()}
817
     */
818 8
    public function andOnCondition($condition, array $params = []): self
819
    {
820 8
        if ($this->on === null) {
821 4
            $this->on = $condition;
822
        } else {
823 4
            $this->on = ['and', $this->on, $condition];
824
        }
825
826 8
        $this->addParams($params);
827
828 8
        return $this;
829
    }
830
831
    /**
832
     * Adds an additional ON condition to the existing one.
833
     *
834
     * The new condition and the existing one will be joined using the 'OR' operator.
835
     *
836
     * @param string|array $condition the new ON condition. Please refer to {@see where()} on how to specify this
837
     * parameter.
838
     * @param array $params the parameters (name => value) to be bound to the query.
839
     *
840
     * @return $this the query object itself.
841
     *
842
     * {@see onCondition()}
843
     * {@see andOnCondition()}
844
     */
845 8
    public function orOnCondition($condition, array $params = []): self
846
    {
847 8
        if ($this->on === null) {
848 4
            $this->on = $condition;
849
        } else {
850 4
            $this->on = ['or', $this->on, $condition];
851
        }
852
853 8
        $this->addParams($params);
854
855 8
        return $this;
856
    }
857
858
    /**
859
     * Specifies the junction table for a relational query.
860
     *
861
     * Use this method to specify a junction table when declaring a relation in the {@see ActiveRecord} class:
862
     *
863
     * ```php
864
     * public function getItems()
865
     * {
866
     *     return $this->hasMany(Item::class, ['id' => 'item_id'])
867
     *         ->viaTable('order_item', ['order_id' => 'id']);
868
     * }
869
     * ```
870
     *
871
     * @param string $tableName the name of the junction table.
872
     * @param array $link the link between the junction table and the table associated with {@see primaryModel}.
873
     * The keys of the array represent the columns in the junction table, and the values represent the columns in the
874
     * {@see primaryModel} table.
875
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
876
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
877
     *
878
     * @return $this the query object itself.
879
     *
880
     * {@see via()}
881
     */
882 32
    public function viaTable(string $tableName, array $link, callable $callable = null): self
883
    {
884 32
        $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass;
885
886 32
        $relation = (new self($modelClass))->from([$tableName])->link($link)->multiple(true)->asArray(true);
887
888 32
        $this->via = $relation;
889
890 32
        if ($callable !== null) {
891 8
            $callable($relation);
892
        }
893
894 32
        return $this;
895
    }
896
897
    /**
898
     * Define an alias for the table defined in {@see modelClass}.
899
     *
900
     * This method will adjust {@see from} so that an already defined alias will be overwritten. If none was defined,
901
     * {@see from} will be populated with the given alias.
902
     *
903
     * @param string $alias the table alias.
904
     *
905
     * @return $this the query object itself.
906
     */
907 68
    public function alias(string $alias): self
908
    {
909 68
        if (empty($this->from) || count($this->from) < 2) {
910 68
            [$tableName] = $this->getTableNameAndAlias();
911 68
            $this->from = [$alias => $tableName];
912
        } else {
913 4
            $tableName = $this->getPrimaryTableName();
914
915 4
            foreach ($this->from as $key => $table) {
916 4
                if ($table === $tableName) {
917 4
                    unset($this->from[$key]);
918 4
                    $this->from[$alias] = $tableName;
919
                }
920
            }
921
        }
922
923 68
        return $this;
924
    }
925
926
    /**
927
     * Returns table names used in {@see from} indexed by aliases.
928
     *
929
     * Both aliases and names are enclosed into {{ and }}.
930
     *
931
     * @throws InvalidArgumentException
932
     * @throws InvalidConfigException
933
     *
934
     * @return array table names indexed by aliases.
935
     */
936 164
    public function getTablesUsedInFrom(): array
937
    {
938 164
        if (empty($this->from)) {
939 96
            return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
940
        }
941
942 68
        return parent::getTablesUsedInFrom();
943
    }
944
945 480
    protected function getPrimaryTableName(): string
946
    {
947 480
        return $this->modelClass::tableName();
948
    }
949
950
    /**
951
     * @return string|array the join condition to be used when this query is used in a relational context.
952
     *
953
     * The condition will be used in the ON part when {@see ActiveQuery::joinWith()} is called. Otherwise, the condition
954
     * will be used in the WHERE part of a query.
955
     *
956
     * Please refer to {@see Query::where()} on how to specify this parameter.
957
     *
958
     * {@see onCondition()}
959
     */
960 44
    public function getOn()
961
    {
962 44
        return $this->on;
963
    }
964
965
    /**
966
     * @return array $value a list of relations that this query should be joined with.
967
     */
968 173
    public function getJoinWith(): array
969
    {
970 173
        return $this->joinWith;
971
    }
972
973
    /**
974
     * @return string|null the SQL statement to be executed for retrieving AR records.
975
     *
976
     * This is set by {@see ActiveRecord::findBySql()}.
977
     */
978
    public function getSql(): ?string
979
    {
980
        return $this->sql;
981
    }
982
983 44
    public function getModelClass(): ?string
984
    {
985 44
        return $this->modelClass;
986
    }
987
988 12
    public function on($value): self
989
    {
990 12
        $this->on = $value;
991
992 12
        return $this;
993
    }
994
995 8
    public function sql(?string $value): self
996
    {
997 8
        $this->sql = $value;
998
999 8
        return $this;
1000
    }
1001
}
1002