Passed
Push — master ( ef9bba...04d154 )
by Def
02:37
created

ActiveQuery::createQueryHelper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
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\CommandInterface;
10
use Yiisoft\Db\Connection\ConnectionInterface;
11
use Yiisoft\Db\Exception\Exception;
12
use Yiisoft\Db\Exception\InvalidArgumentException;
13
use Yiisoft\Db\Exception\InvalidConfigException;
14
use Yiisoft\Db\Exception\NotSupportedException;
15
use Yiisoft\Db\Expression\ExpressionInterface;
16
use Yiisoft\Db\Helper\ArrayHelper;
17
use Yiisoft\Db\Query\Query;
18
use Yiisoft\Db\Query\QueryInterface;
19
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
20
use Yiisoft\Definitions\Exception\CircularReferenceException;
21
use Yiisoft\Definitions\Exception\NotInstantiableException;
22
use Yiisoft\Factory\NotFoundException;
23
24
use function array_merge;
25
use function array_values;
26
use function count;
27
use function implode;
28
use function in_array;
29
use function is_array;
30
use function is_int;
31
use function is_string;
32
use function preg_match;
33
use function reset;
34
use function serialize;
35
use function strpos;
36
use function substr;
37
38
/**
39
 * ActiveQuery represents a DB query associated with an Active Record class.
40
 *
41
 * An ActiveQuery can be a normal query or be used in a relational context.
42
 *
43
 * ActiveQuery instances are usually created by {@see ActiveQuery::findOne()}, {@see ActiveQuery::findBySql()},
44
 * {@see ActiveQuery::findAll()}
45
 *
46
 * Relational queries are created by {@see ActiveRecord::hasOne()} and {@see ActiveRecord::hasMany()}.
47
 *
48
 * Normal Query
49
 * ------------
50
 *
51
 * ActiveQuery mainly provides the following methods to retrieve the query results:
52
 *
53
 * - {@see one()}: returns a single record populated with the first row of data.
54
 * - {@see all()}: returns all records based on the query results.
55
 * - {@see count()}: returns the number of records.
56
 * - {@see sum()}: returns the sum over the specified column.
57
 * - {@see average()}: returns the average over the specified column.
58
 * - {@see min()}: returns the min over the specified column.
59
 * - {@see max()}: returns the max over the specified column.
60
 * - {@see scalar()}: returns the value of the first column in the first row of the query result.
61
 * - {@see column()}: returns the value of the first column in the query result.
62
 * - {@see exists()}: returns a value indicating whether the query result has data or not.
63
 *
64
 * Because ActiveQuery extends from {@see Query}, one can use query methods, such as {@see where()}, {@see orderBy()} to
65
 * customize the query options.
66
 *
67
 * ActiveQuery also provides the following additional query options:
68
 *
69
 * - {@see with()}: list of relations that this query should be performed with.
70
 * - {@see joinWith()}: reuse a relation query definition to add a join to a query.
71
 * - {@see indexBy()}: the name of the column by which the query result should be indexed.
72
 * - {@see asArray()}: whether to return each record as an array.
73
 *
74
 * These options can be configured using methods of the same name. For example:
75
 *
76
 * ```php
77
 * $customerQuery = new ActiveQuery(Customer::class, $db);
78
 * $query = $customerQuery->with('orders')->asArray()->all();
79
 * ```
80
 *
81
 * Relational query
82
 * ----------------
83
 *
84
 * In relational context ActiveQuery represents a relation between two Active Record classes.
85
 *
86
 * Relational ActiveQuery instances are usually created by calling {@see ActiveRecord::hasOne()} and
87
 * {@see ActiveRecord::hasMany()}. An Active Record class declares a relation by defining a getter method which calls
88
 * one of the above methods and returns the created ActiveQuery object.
89
 *
90
 * A relation is specified by {@see link} which represents the association between columns of different tables; and the
91
 * multiplicity of the relation is indicated by {@see multiple}.
92
 *
93
 * If a relation involves a junction table, it may be specified by {@see via()} or {@see viaTable()} method.
94
 *
95
 * These methods may only be called in a relational context. Same is true for {@see inverseOf()}, which marks a relation
96
 * as inverse of another relation and {@see onCondition()} which adds a condition that is to be added to relational
97
 * query join condition.
98
 */
99
class ActiveQuery extends Query implements ActiveQueryInterface
100
{
101
    use ActiveQueryTrait;
102
    use ActiveRelationTrait;
103
104
    private string|null $sql = null;
105
    private array|string|null $on = null;
106
    private array $joinWith = [];
107
    private ActiveRecordInterface|null $arInstance = null;
108
109 720
    public function __construct(
110
        protected string $arClass,
111 720
        protected ConnectionInterface $db,
112 720
        private ActiveRecordFactory|null $arFactory = null,
113 720
        private string $tableName = ''
114
    ) {
115 720
        parent::__construct($db);
116 720
    }
117
118
    /**
119
     * Executes query and returns all results as an array.
120
     *
121
     * If null, the DB connection returned by {@see arClass} will be used.
122
     *
123
     * @throws Exception
124
     * @throws InvalidConfigException
125
     * @throws Throwable
126
     *
127 244
     * @return array the query results. If the query results in nothing, an empty array will be returned.
128
     *
129 244
     * @psalm-return ActiveRecord[]|array
130
     */
131
    public function all(): array
132
    {
133
        return parent::all();
134
    }
135
136
    public function prepare(QueryBuilderInterface $builder): QueryInterface
137
    {
138
        /**
139
         * NOTE: because the same ActiveQuery may be used to build different SQL statements, one for count query, the
140
         * other for row data query, it is important to make sure the same ActiveQuery can be used to build SQL
141
         * statements multiple times.
142
         */
143
        if (!empty($this->joinWith)) {
144
            $this->buildJoinWith();
145
            /** clean it up to avoid issue {@see https://github.com/yiisoft/yii2/issues/2687} */
146 497
            $this->joinWith = [];
147
        }
148
149
        if (empty($this->getFrom())) {
150
            $this->from = [$this->getPrimaryTableName()];
151
        }
152
153 497
        if (empty($this->getSelect()) && !empty($this->getJoin())) {
154 80
            [, $alias] = $this->getTableNameAndAlias();
155
156 80
            $this->select(["$alias.*"]);
157
        }
158
159 497
        if ($this->primaryModel === null) {
160 489
            /** eager loading */
161
            $query = (new Query($this->db))
162
                ->where($this->getWhere())
163 497
                ->limit($this->getLimit())
164 76
                ->offset($this->getOffset())
165
                ->orderBy($this->getOrderBy())
166 76
                ->indexBy($this->getIndexBy())
167
                ->select($this->select)
168
                ->selectOption($this->selectOption)
169 497
                ->distinct($this->distinct)
170
                ->from($this->from)
171 489
                ->groupBy($this->groupBy)
172
                ->setJoin($this->join)
173
                ->having($this->having)
174 113
                ->setUnion($this->union)
175
                ->params($this->params)
176 113
                ->withQueries($this->withQueries);
177
        } else {
178 20
            /** lazy loading of a relation */
179
            $where = $this->getWhere();
180 20
181 101
            if ($this->via instanceof self) {
182
                /** via junction table */
183
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
184
185
                $this->filterByModels($viaModels);
186
            } elseif (is_array($this->via)) {
187 28
                [$viaName, $viaQuery, $viaCallableUsed] = $this->via;
188
189 28
                if ($viaQuery->getMultiple()) {
190 28
                    if ($viaCallableUsed) {
191 20
                        $viaModels = $viaQuery->all();
192 8
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
193
                        $viaModels = $this->primaryModel->$viaName;
194
                    } else {
195 8
                        $viaModels = $viaQuery->all();
196 28
                        $this->primaryModel->populateRelation($viaName, $viaModels);
197
                    }
198
                } else {
199
                    if ($viaCallableUsed) {
200
                        $model = $viaQuery->one();
201
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
202
                        $model = $this->primaryModel->$viaName;
203
                    } else {
204
                        $model = $viaQuery->one();
205
                        $this->primaryModel->populateRelation($viaName, $model);
206
                    }
207
                    $viaModels = $model === null ? [] : [$model];
208
                }
209 28
                $this->filterByModels($viaModels);
210
            } else {
211 101
                $this->filterByModels([$this->primaryModel]);
212
            }
213
214 113
            $query = (new Query($this->db))
215 113
                ->where($this->getWhere())
216
                ->limit($this->getLimit())
217
                ->offset($this->getOffset())
218 497
                ->orderBy($this->getOrderBy())
219 24
                ->indexBy($this->getIndexBy())
220
                ->select($this->select)
221
                ->selectOption($this->selectOption)
222 497
                ->distinct($this->distinct)
223
                ->from($this->from)
224
                ->groupBy($this->groupBy)
225
                ->setJoin($this->join)
226
                ->having($this->having)
227
                ->setUnion($this->union)
228
                ->params($this->params)
229
                ->withQueries($this->withQueries);
230
            $this->where($where);
231
        }
232
233
        if (!empty($this->on)) {
234
            $query->andWhere($this->on);
235
        }
236
237 419
        return $query;
238
    }
239 419
240 74
    /**
241
     * Converts the raw query results into the format as specified by this query.
242
     *
243 406
     * This method is internally used to convert the data fetched from database into the format as required by this
244
     * query.
245 406
     *
246 64
     * @param array $rows the raw query result from database.
247
     *
248
     * @throws Exception
249 406
     * @throws InvalidArgumentException
250 131
     * @throws InvalidConfigException
251
     * @throws NotSupportedException
252
     * @throws ReflectionException
253 406
     * @throws Throwable
254 16
     *
255
     * @return array the converted query result.
256
     */
257 406
    public function populate(array $rows): array
258
    {
259
        if (empty($rows)) {
260
            return [];
261
        }
262
263
        $models = $this->createModels($rows);
264
265
        if (!empty($this->join) && $this->getIndexBy() === null) {
266
            $models = $this->removeDuplicatedModels($models);
267
        }
268
269
        if (!empty($this->with)) {
270
            $this->findWith($this->with, $models);
271 64
        }
272
273 64
        if ($this->inverseOf !== null) {
274
            $this->addInverseRelations($models);
275 64
        }
276
277 64
        return parent::populate($models);
278
    }
279 8
280 8
    /**
281 8
     * Removes duplicated models by checking their primary key values.
282 8
     *
283
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
284 4
     *
285
     * @param array $models the models to be checked.
286 7
     *
287
     * @throws CircularReferenceException
288
     * @throws Exception
289 4
     * @throws InvalidConfigException
290
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
291 4
     * @throws NotFoundException
292
     * @throws NotInstantiableException
293
     *
294 4
     * @return array the distinctive models.
295
     */
296
    private function removeDuplicatedModels(array $models): array
297 60
    {
298
        $hash = [];
299
300
        $pks = $this->getARInstance()->primaryKey();
301 60
302
        if (count($pks) > 1) {
303 60
            /** composite primary key */
304 60
            foreach ($models as $i => $model) {
305
                $key = [];
306 4
                foreach ($pks as $pk) {
307
                    if (!isset($model[$pk])) {
308
                        /** do not continue if the primary key is not part of the result set */
309 56
                        break 2;
310
                    }
311 56
                    $key[] = $model[$pk];
312 28
                }
313 56
314 56
                $key = serialize($key);
315
316
                if (isset($hash[$key])) {
317
                    unset($models[$i]);
318
                } else {
319 64
                    $hash[$key] = true;
320
                }
321
            }
322
        } elseif (empty($pks)) {
323
            throw new InvalidConfigException("Primary key of '$this->arClass' can not be empty.");
324
        } else {
325
            /** single column primary key */
326
            $pk = reset($pks);
327
328
            foreach ($models as $i => $model) {
329
                if (!isset($model[$pk])) {
330
                    /** do not continue if the primary key is not part of the result set */
331
                    break;
332 305
                }
333
334 305
                $key = $model[$pk];
335
336 305
                if (isset($hash[$key])) {
337 301
                    unset($models[$i]);
338
                } else {
339 301
                    $hash[$key] = true;
340
                }
341
            }
342 32
        }
343
344
        return array_values($models);
345
    }
346
347
    /**
348
     * @psalm-suppress NullableReturnStatement
349
     */
350
    public function one(): array|null|object
351
    {
352 449
        $row = parent::one();
353
354 449
        if ($row !== null) {
355 445
            $activeRecord = $this->populate([$row]);
356
            $row = reset($activeRecord) ?: null;
357 4
        }
358 4
359
        return $row;
360
    }
361 449
362
    /**
363 449
     * Creates a DB command that can be used to execute this query.
364
     *
365 449
     * @throws Exception
366
     *
367
     * @return CommandInterface the created DB command instance.
368
     */
369
    public function createCommand(): CommandInterface
370
    {
371
        if ($this->sql === null) {
372
            [$sql, $params] = $this->db->getQueryBuilder()->build($this);
373
        } else {
374
            $sql = $this->sql;
375
            $params = $this->params;
376
        }
377
378
        return $this->db->createCommand($sql, $params);
379 61
    }
380
381 61
    /**
382 57
     * Queries a scalar value by setting {@see select} first.
383
     *
384
     * Restores the value of select to make this query reusable.
385 4
     *
386 4
     * @param ExpressionInterface|string $selectExpression
387 4
     *
388 4
     * @throws Exception
389
     * @throws InvalidConfigException
390 4
     * @throws Throwable
391
     */
392 4
    protected function queryScalar(string|ExpressionInterface $selectExpression): bool|string|null|int|float
393
    {
394
        if ($this->sql === null) {
395
            return parent::queryScalar($selectExpression);
396
        }
397
398
        $command = (new Query($this->db))->select([$selectExpression])
399
            ->from(['c' => "($this->sql)"])
400
            ->params($this->params)
401
            ->createCommand();
402
403
        return $command->queryScalar();
404
    }
405
406
    /**
407
     * Joins with the specified relations.
408
     *
409
     * This method allows you to reuse existing relation definitions to perform JOIN queries. Based on the definition of
410
     * the specified relation(s), the method will append one or multiple JOIN statements to the current query.
411
     *
412
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
413
     * which is equivalent to calling {@see with()} using the specified relations.
414
     *
415
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
416
     *
417
     * This method differs from {@see with()} in that it will build up and execute a JOIN SQL statement  for the primary
418
     * table. And when `$eagerLoading` is true, it will call {@see with()} in addition with the specified relations.
419
     *
420
     * @param array|string $with the relations to be joined. This can either be a string, representing a relation name
421
     * or an array with the following semantics:
422
     *
423
     * - Each array element represents a single relation.
424
     * - You may specify the relation name as the array key and provide an anonymous functions that can be used to
425
     *   modify the relation queries on-the-fly as the array value.
426
     * - If a relation query does not need modification, you may use the relation name as the array value.
427
     *
428
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
429
     *
430
     * Sub-relations can also be specified, see {@see with()} for the syntax.
431
     *
432
     * In the following you find some examples:
433
     *
434
     * ```php
435
     * // find all orders that contain books, and eager loading "books".
436
     * $orderQuery = new ActiveQuery(Order::class, $db);
437
     * $orderQuery->joinWith('books', true, 'INNER JOIN')->all();
438
     *
439
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
440
     * $orderQuery = new ActiveQuery(Order::class, $db);
441
     * $orderQuery->joinWith([
442
     *     'books' => function (ActiveQuery $query) {
443
     *         $query->orderBy('item.name');
444
     *     }
445
     * ])->all();
446
     *
447
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table.
448
     * $order = new ActiveQuery(Order::class, $db);
449
     * $orderQuery->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
450
     * ```
451 99
     * @param array|bool $eagerLoading whether to eager load the relations specified in `$with`. When this is a boolean,
452
     * it applies to all relations specified in `$with`. Use an array to explicitly list which relations in `$with` need
453 99
     * to be eagerly loaded.  Note, that this does not mean, that the relations are populated from the query result. An
454
     * extra query will still be performed to bring in the related data. Defaults to `true`.
455 99
     * @param array|string $joinType the join type of the relations specified in `$with`.  When this is a string, it
456 99
     * applies to all relations specified in `$with`. Use an array in the format of `relationName => joinType` to
457 95
     * specify different join types for different relations.
458 95
     *
459
     * @return $this the query object itself.
460
     */
461 99
    public function joinWith(
462
        array|string $with,
463 20
        array|bool $eagerLoading = true,
464
        array|string $joinType = 'LEFT JOIN'
465 20
    ): self {
466
        $relations = [];
467 20
468
        foreach ((array) $with as $name => $callback) {
469 20
            if (is_int($name)) {
470
                $name = $callback;
471 20
                $callback = null;
472 16
            }
473
474 20
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
475
                /** relation is defined with an alias, adjust callback to apply alias */
476
                [, $relation, $alias] = $matches;
477 99
478 95
                $name = $relation;
479
480 48
                $callback = static function (self $query) use ($callback, $alias) {
481
                    $query->alias($alias);
482
483
                    if ($callback !== null) {
484 99
                        $callback($query);
485
                    }
486 99
                };
487
            }
488
489 84
            if ($callback === null) {
490
                $relations[] = $name;
491 84
            } else {
492
                $relations[$name] = $callback;
493 84
            }
494
        }
495 84
496
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
497 84
498 84
        return $this;
499
    }
500 84
501
    /**
502
     * @throws CircularReferenceException
503
     * @throws InvalidConfigException
504
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
505
     * @throws NotFoundException
506
     * @throws NotInstantiableException
507
     */
508
    public function buildJoinWith(): void
509
    {
510 84
        $join = $this->join;
511 16
512
        $this->join = [];
513
514 84
        $arClass = $this->getARInstance();
515
516
        foreach ($this->joinWith as [$with, $eagerLoading, $joinType]) {
517
            $this->joinWithRelations($arClass, $with, $joinType);
518
519
            if (is_array($eagerLoading)) {
520
                foreach ($with as $name => $callback) {
521 84
                    if (is_int($name)) {
522
                        if (!in_array($callback, $eagerLoading, true)) {
523 84
                            unset($with[$name]);
524 84
                        }
525
                    } elseif (!in_array($name, $eagerLoading, true)) {
526 84
                        unset($with[$name]);
527
                    }
528
                }
529 84
            } elseif (!$eagerLoading) {
530
                $with = [];
531 84
            }
532 84
533 84
            $this->with($with);
534 84
        }
535
536
        /**
537
         * Remove duplicated joins added by joinWithRelations that may be added e.g. when joining a relation and a via
538 84
         * relation at the same time.
539
         */
540 84
        $uniqueJoins = [];
541
542
        foreach ($this->join as $j) {
543
            $uniqueJoins[serialize($j)] = $j;
544 84
        }
545
        $this->join = array_values($uniqueJoins);
546
547
        /** {@see https://github.com/yiisoft/yii2/issues/16092 } */
548
        $uniqueJoinsByTableName = [];
549
550
        foreach ($this->join as $config) {
551
            $tableName = serialize($config[1]);
552
            if (!array_key_exists($tableName, $uniqueJoinsByTableName)) {
553
                $uniqueJoinsByTableName[$tableName] = $config;
554
            }
555
        }
556
557
        $this->join = array_values($uniqueJoinsByTableName);
558
559
        if (!empty($join)) {
560
            /** Append explicit join to joinWith() {@see https://github.com/yiisoft/yii2/issues/2880} */
561 53
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
562
        }
563 53
    }
564
565
    /**
566
     * Inner joins with the specified relations.
567
     *
568
     * This is a shortcut method to {@see joinWith()} with the join type set as "INNER JOIN". Please refer to
569
     * {@see joinWith()} for detailed usage of this method.
570
     *
571
     * @param array|string $with the relations to be joined with.
572
     * @param array|bool $eagerLoading whether to eager load the relations. Note, that this does not mean, that the
573 84
     * relations are populated from the query result. An extra query will still be performed to bring in the related
574
     * data.
575 84
     *
576
     * @return $this the query object itself.
577 84
     *
578 84
     * {@see joinWith()}
579 80
     */
580 80
    public function innerJoinWith(array|string $with, array|bool $eagerLoading = true): self
581
    {
582
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
583 84
    }
584 84
585 84
    /**
586
     * Modifies the current query by adding join fragments based on the given relations.
587 84
     *
588 20
     * @param ActiveRecordInterface $arClass the primary model.
589 20
     * @param array $with the relations to be joined.
590 20
     * @param array|string $joinType the join type.
591
     *
592 20
     * @throws CircularReferenceException
593 12
     * @throws InvalidConfigException
594 12
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
595
     * @throws NotFoundException
596 8
     * @throws NotInstantiableException
597
     */
598
    private function joinWithRelations(ActiveRecordInterface $arClass, array $with, array|string $joinType): void
599 20
    {
600
        $relations = [];
601 20
602 20
        foreach ($with as $name => $callback) {
603 20
            if (is_int($name)) {
604
                $name = $callback;
605
                $callback = null;
606 84
            }
607
608 84
            $primaryModel = $arClass;
609 84
            $parent = $this;
610
            $prefix = '';
611 84
612 48
            while (($pos = strpos($name, '.')) !== false) {
613
                $childName = substr($name, $pos + 1);
614
                $name = substr($name, 0, $pos);
615 84
                $fullName = $prefix === '' ? $name : "$prefix.$name";
616 12
617
                if (!isset($relations[$fullName])) {
618
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
619 84
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
0 ignored issues
show
Bug introduced by
It seems like $relation can also be of type null; however, parameter $child of Yiisoft\ActiveRecord\Act...ery::joinWithRelation() does only seem to accept Yiisoft\ActiveRecord\ActiveQueryInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

619
                    $this->joinWithRelation($parent, /** @scrutinizer ignore-type */ $relation, $this->getJoinType($joinType, $fullName));
Loading history...
620
                } else {
621
                    $relation = $relations[$fullName];
622 84
                }
623
624
                $primaryModel = $relation->getARInstance();
0 ignored issues
show
Bug introduced by
The method getARInstance() 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

624
                /** @scrutinizer ignore-call */ 
625
                $primaryModel = $relation->getARInstance();
Loading history...
625
626
                $parent = $relation;
627
                $prefix = $fullName;
628
                $name = $childName;
629
            }
630
631
            $fullName = $prefix === '' ? $name : "$prefix.$name";
632 84
633
            if (!isset($relations[$fullName])) {
634 84
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
635
636
                if ($callback !== null) {
637
                    $callback($relation);
638 84
                }
639
640
                if (!empty($relation->getJoinWith())) {
641
                    $relation->buildJoinWith();
642
                }
643
644
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
0 ignored issues
show
Bug introduced by
It seems like $parent can also be of type null; however, parameter $parent of Yiisoft\ActiveRecord\Act...ery::joinWithRelation() does only seem to accept Yiisoft\ActiveRecord\ActiveQueryInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

644
                $this->joinWithRelation(/** @scrutinizer ignore-type */ $parent, $relation, $this->getJoinType($joinType, $fullName));
Loading history...
645
            }
646 113
        }
647
    }
648 113
649 104
    /**
650
     * Returns the join type based on the given join type parameter and the relation name.
651 89
     *
652
     * @param array|string $joinType the given join type(s).
653 89
     * @param string $name relation name.
654 89
     *
655 28
     * @return string the real join type.
656
     */
657 81
    private function getJoinType(array|string $joinType, string $name): string
658
    {
659
        if (is_array($joinType) && isset($joinType[$name])) {
660
            return $joinType[$name];
661 109
        }
662 8
663
        return is_string($joinType) ? $joinType : 'INNER JOIN';
664 109
    }
665
666
    /**
667 109
     * Returns the table name and the table alias for {@see arClass}.
668
     *
669
     * @throws CircularReferenceException
670
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
671
     * @throws NotFoundException
672
     * @throws NotInstantiableException
673
     */
674
    private function getTableNameAndAlias(): array
675
    {
676
        if (empty($this->from)) {
677
            $tableName = $this->getPrimaryTableName();
678
        } else {
679 84
            $tableName = '';
680
681 84
            foreach ($this->from as $alias => $tableName) {
682 84
                if (is_string($alias)) {
683
                    return [$tableName, $alias];
684 84
                }
685
                break;
686 12
            }
687 12
        }
688
689 12
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
690
            $alias = $matches[2];
691
        } else {
692 84
            $alias = $tableName;
693
        }
694 28
695 28
        return [$tableName, $alias];
696
    }
697 28
698
    /**
699
     * Joins a parent query with a child query.
700 84
     *
701 84
     * The current query object will be modified accordingly.
702
     *
703 84
     * @param ActiveQuery $parent
704 84
     * @param ActiveQuery $child
705 84
     * @param string $joinType
706
     *
707
     * @throws CircularReferenceException
708 84
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
709 84
     * @throws NotFoundException
710
     * @throws NotInstantiableException
711
     */
712 84
    private function joinWithRelation(ActiveQueryInterface $parent, ActiveQueryInterface $child, string $joinType): void
713
    {
714 84
        $via = $child->via;
0 ignored issues
show
Bug introduced by
Accessing via on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
715 84
        $child->via = null;
716
717
        if ($via instanceof self) {
718 84
            /** via table */
719
            $this->joinWithRelation($parent, $via, $joinType);
720 84
            $this->joinWithRelation($via, $child, $joinType);
721 84
722
            return;
723
        }
724
725
        if (is_array($via)) {
726
            /** via relation */
727 84
            $this->joinWithRelation($parent, $via[1], $joinType);
728
            $this->joinWithRelation($via[1], $child, $joinType);
729 84
730 28
            return;
731
        }
732
733 84
        [$parentTable, $parentAlias] = $parent->getTableNameAndAlias();
0 ignored issues
show
Bug introduced by
The method getTableNameAndAlias() 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

733
        /** @scrutinizer ignore-call */ 
734
        [$parentTable, $parentAlias] = $parent->getTableNameAndAlias();
Loading history...
734
        [$childTable, $childAlias] = $child->getTableNameAndAlias();
735
736
        if (!empty($child->link)) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
737 84
            if (!str_contains($parentAlias, '{{')) {
738 32
                $parentAlias = '{{' . $parentAlias . '}}';
739
            }
740
741 84
            if (!str_contains($childAlias, '{{')) {
742
                $childAlias = '{{' . $childAlias . '}}';
743
            }
744
745 84
            $on = [];
746
747
            foreach ($child->link as $childColumn => $parentColumn) {
748
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
749 84
            }
750 12
751 12
            $on = implode(' AND ', $on);
752
753
            if (!empty($child->on)) {
0 ignored issues
show
Bug introduced by
Accessing on on the interface Yiisoft\ActiveRecord\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
754
                $on = ['and', $on, $child->on];
755 84
            }
756
        } else {
757
            $on = $child->on;
758
        }
759
760 84
        $this->join($joinType, empty($child->getFrom()) ? $childTable : $child->getFrom(), $on);
761
762
        if (!empty($child->getWhere())) {
763
            $this->andWhere($child->getWhere());
764
        }
765
766
        if (!empty($child->getHaving())) {
767
            $this->andHaving($child->getHaving());
768
        }
769
770
        if (!empty($child->getOrderBy())) {
771
            $this->addOrderBy($child->getOrderBy());
772
        }
773
774
        if (!empty($child->getGroupBy())) {
775
            $this->addGroupBy($child->getGroupBy());
776
        }
777
778
        if (!empty($child->getParams())) {
779
            $this->addParams($child->getParams());
780
        }
781
782
        if (!empty($child->getJoin())) {
783
            foreach ($child->getJoin() as $join) {
784
                $this->join[] = $join;
785
            }
786
        }
787
788 29
        if (!empty($child->getUnion())) {
789
            foreach ($child->getUnion() as $union) {
790 29
                $this->union[] = $union;
791
            }
792 29
        }
793
    }
794 29
795
    /**
796
     * Sets the ON condition for a relational query.
797
     *
798
     * The condition will be used in the ON part when {@see ActiveQuery::joinWith()} is called.
799
     *
800
     * Otherwise, the condition will be used in the WHERE part of a query.
801
     *
802
     * Use this method to specify additional conditions when declaring a relation in the {@see ActiveRecord} class:
803
     *
804
     * ```php
805
     * public function getActiveUsers(): ActiveQuery
806
     * {
807
     *     return $this->hasMany(User::class, ['id' => 'user_id'])->onCondition(['active' => true]);
808
     * }
809
     * ```
810
     *
811 10
     * Note that this condition is applied in case of a join as well as when fetching the related records. This only
812
     * fields of the related table can be used in the condition. Trying to access fields of the primary record will
813 10
     * cause an error in a non-join-query.
814 5
     *
815
     * @param array|string $condition the ON condition. Please refer to {@see Query::where()} on how to specify this
816 5
     * parameter.
817
     * @param array $params the parameters (name => value) to be bound to the query.
818
     *
819 10
     * @return $this the query object itself
820
     */
821 10
    public function onCondition(array|string $condition, array $params = []): self
822
    {
823
        $this->on = $condition;
824
825
        $this->addParams($params);
826
827
        return $this;
828
    }
829
830
    /**
831
     * Adds ON condition to the existing one.
832
     *
833
     * The new condition and the existing one will be joined using the 'AND' operator.
834
     *
835
     * @param array|string $condition the new ON condition. Please refer to {@see where()} on how to specify this
836
     * parameter.
837
     * @param array $params the parameters (name => value) to be bound to the query.
838 10
     *
839
     * @return $this the query object itself.
840 10
     *
841 5
     * {@see onCondition()}
842
     * {@see orOnCondition()}
843 5
     */
844
    public function andOnCondition(array|string $condition, array $params = []): self
845
    {
846 10
        if ($this->on === null) {
847
            $this->on = $condition;
848 10
        } else {
849
            $this->on = ['and', $this->on, $condition];
850
        }
851
852
        $this->addParams($params);
853
854
        return $this;
855
    }
856
857
    /**
858
     * Adds ON condition to the existing one.
859
     *
860
     * The new condition and the existing one will be joined using the 'OR' operator.
861
     *
862
     * @param array|string $condition the new ON condition. Please refer to {@see where()} on how to specify this
863
     * parameter.
864
     * @param array $params the parameters (name => value) to be bound to the query.
865
     *
866
     * @return $this the query object itself.
867
     *
868
     * {@see onCondition()}
869
     * {@see andOnCondition()}
870
     */
871
    public function orOnCondition(array|string $condition, array $params = []): self
872
    {
873
        if ($this->on === null) {
874 32
            $this->on = $condition;
875
        } else {
876 32
            $this->on = ['or', $this->on, $condition];
877
        }
878 32
879
        $this->addParams($params);
880 32
881
        return $this;
882 32
    }
883
884 32
    /**
885 8
     * Specifies the junction table for a relational query.
886
     *
887
     * Use this method to specify a junction table when declaring a relation in the {@see ActiveRecord} class:
888 32
     *
889
     * ```php
890
     * public function getItems()
891
     * {
892
     *     return $this->hasMany(Item::class, ['id' => 'item_id'])->viaTable('order_item', ['order_id' => 'id']);
893
     * }
894
     * ```
895
     *
896
     * @param string $tableName the name of the junction table.
897
     * @param array $link the link between the junction table and the table associated with {@see primaryModel}.
898
     * The keys of the array represent the columns in the junction table, and the values represent the columns in the
899
     * {@see primaryModel} table.
900
     * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
901 41
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
902
     *
903 41
     * @return $this the query object itself.
904 41
     *
905 41
     * {@see via()}
906
     */
907 4
    public function viaTable(string $tableName, array $link, callable $callable = null): self
908
    {
909 4
        $arClass = $this->primaryModel ? $this->primaryModel::class : $this->arClass;
910 4
911 4
        $arClassInstance = new self($arClass, $this->db);
912 4
913
        $relation = $arClassInstance->from([$tableName])->link($link)->multiple(true)->asArray(true);
914
915
        $this->via = $relation;
916
917 41
        if ($callable !== null) {
918
            $callable($relation);
919
        }
920
921
        return $this;
922
    }
923
924
    /**
925
     * Define an alias for the table defined in {@see arClass}.
926
     *
927
     * This method will adjust {@see from} so that an already defined alias will be overwritten. If none was defined,
928
     * {@see from} will be populated with the given alias.
929 168
     *
930
     * @param string $alias the table alias.
931 168
     *
932 136
     * @throws CircularReferenceException
933
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
934
     * @throws NotFoundException
935 44
     * @throws NotInstantiableException
936
     */
937
    public function alias(string $alias): self
938 553
    {
939
        if (empty($this->from) || count($this->from) < 2) {
940 553
            [$tableName] = $this->getTableNameAndAlias();
941
            $this->from = [$alias => $tableName];
942
        } else {
943
            $tableName = $this->getPrimaryTableName();
944
945
            foreach ($this->from as $key => $table) {
946
                if ($table === $tableName) {
947
                    unset($this->from[$key]);
948
                    $this->from[$alias] = $tableName;
949
                }
950
            }
951
        }
952
953 52
        return $this;
954
    }
955 52
956
    /**
957
     * Returns table names used in {@see from} indexed by aliases.
958
     *
959
     * Both aliases and names are enclosed into {{ and }}.
960
     *
961 204
     * @throws CircularReferenceException
962
     * @throws InvalidArgumentException
963 204
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
964
     * @throws NotFoundException
965
     * @throws NotInstantiableException
966
     */
967
    public function getTablesUsedInFrom(): array
968
    {
969
        if (empty($this->from)) {
970
            return $this->db->getQuoter()->cleanUpTableNames([$this->getPrimaryTableName()]);
971 4
        }
972
973 4
        return parent::getTablesUsedInFrom();
974
    }
975
976 5
    /**
977
     * @throws CircularReferenceException
978 5
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
979
     * @throws NotFoundException
980
     * @throws NotInstantiableException
981
     */
982
    protected function getPrimaryTableName(): string
983
    {
984
        return $this->getARInstance()->getTableName();
985
    }
986
987
    /**
988 228
     * @return array|string|null the join condition to be used when this query is used in a relational context.
989
     *
990 228
     * The condition will be used in the ON part when {@see ActiveQuery::joinWith()} is called. Otherwise, the condition
991
     * will be used in the WHERE part of a query.
992
     *
993
     * Please refer to {@see Query::where()} on how to specify this parameter.
994
     *
995
     * {@see onCondition()}
996
     */
997
    public function getOn(): array|string|null
998
    {
999
        return $this->on;
1000 5
    }
1001
1002 5
    /**
1003
     * @return array $value a list of relations that this query should be joined with.
1004
     */
1005
    public function getJoinWith(): array
1006
    {
1007
        return $this->joinWith;
1008
    }
1009
1010
    /**
1011
     * @return string|null the SQL statement to be executed for retrieving AR records.
1012
     *
1013
     * This is set by {@see ActiveRecord::findBySql()}.
1014
     */
1015
    public function getSql(): string|null
1016 285
    {
1017
        return $this->sql;
1018 285
    }
1019
1020 285
    public function getARClass(): string|null
1021 185
    {
1022
        return $this->arClass;
1023
    }
1024 285
1025
    /**
1026 189
     * @throws Exception
1027
     * @throws InvalidArgumentException
1028 189
     * @throws InvalidConfigException
1029 189
     * @throws Throwable
1030
     */
1031 189
    public function findOne(mixed $condition): array|ActiveRecordInterface|null
1032
    {
1033
        return $this->findByCondition($condition)->one();
1034
    }
1035
1036
    /**
1037
     * @param mixed $condition primary key value or a set of column values.
1038
     *
1039 189
     * @throws Exception
1040
     * @throws InvalidArgumentException
1041 189
     * @throws InvalidConfigException
1042
     * @throws Throwable
1043 108
     *
1044 108
     * @return array of ActiveRecord instance, or an empty array if nothing matches.
1045 108
     */
1046
    public function findAll(mixed $condition): array
1047
    {
1048 253
        return $this->findByCondition($condition)->all();
1049
    }
1050
1051
    /**
1052
     * Finds ActiveRecord instance(s) by the given condition.
1053
     *
1054
     * This method is internally called by {@see findOne()} and {@see findAll()}.
1055
     *
1056
     * @param mixed $condition please refer to {@see findOne()} for the explanation of this parameter.
1057
     *
1058
     * @throws CircularReferenceException
1059
     * @throws Exception
1060
     * @throws InvalidArgumentException
1061
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException if there is no primary key defined.
1062
     * @throws NotFoundException
1063
     * @throws NotInstantiableException
1064
     */
1065
    protected function findByCondition(mixed $condition): QueryInterface
1066
    {
1067
        $arInstance = $this->getARInstance();
1068
1069
        if (!is_array($condition)) {
1070 8
            $condition = [$condition];
1071
        }
1072 8
1073
        if (!ArrayHelper::isAssociative($condition) && !$condition instanceof ExpressionInterface) {
1074
            /** query by primary key */
1075 15
            $primaryKey = $arInstance->primaryKey();
1076
1077 15
            if (isset($primaryKey[0])) {
1078 15
                $pk = $primaryKey[0];
1079
1080
                if (!empty($this->getJoin()) || !empty($this->getJoinWith())) {
1081 12
                    $pk = $arInstance->getTableName() . '.' . $pk;
1082
                }
1083 12
1084 12
                /**
1085
                 * if condition is scalar, search for a single primary key, if it is array, search for multiple primary
1086
                 * key values
1087 625
                 */
1088
                $condition = [$pk => array_values($condition)];
1089 625
            } else {
1090 1
                throw new InvalidConfigException('"' . $arInstance::class . '" must have a primary key.');
1091
            }
1092
        } else {
1093 625
            $aliases = $arInstance->filterValidAliases($this);
1094
            $condition = $arInstance->filterCondition($condition, $aliases);
1095 625
        }
1096
1097
        return $this->where($condition);
1098 1
    }
1099
1100 1
    /**
1101
     * Creates an {@see ActiveQuery} instance with a given SQL statement.
1102 1
     *
1103
     * Note that because the SQL statement is already specified, calling additional query modification methods (such as
1104
     * `where()`, `order()`) on the created {@see ActiveQuery} instance will have no effect. However, calling `with()`,
1105
     * `asArray()` or `indexBy()` is still fine.
1106
     *
1107
     * Below is an example:
1108
     *
1109
     * ```php
1110
     * $customerQuery = new ActiveQuery(Customer::class, $db);
1111
     * $customers = $customerQuery->findBySql('SELECT * FROM customer')->all();
1112
     * ```
1113
     *
1114
     * @param string $sql the SQL statement to be executed.
1115
     * @param array $params parameters to be bound to the SQL statement during execution.
1116
     *
1117
     * @return QueryInterface the newly created {@see ActiveQuery} instance
1118
     */
1119
    public function findBySql(string $sql, array $params = []): QueryInterface
1120
    {
1121
        return $this->sql($sql)->params($params);
1122
    }
1123
1124
    public function on(array|string|null $value): self
1125
    {
1126
        $this->on = $value;
1127
        return $this;
1128
    }
1129
1130
    public function sql(string|null $value): self
1131
    {
1132
        $this->sql = $value;
1133
        return $this;
1134
    }
1135
1136
    /**
1137
     * @throws CircularReferenceException
1138
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
1139
     * @throws NotFoundException
1140
     * @throws NotInstantiableException
1141
     */
1142
    public function getARInstance(): ActiveRecordInterface
1143
    {
1144
        if ($this->arFactory !== null) {
1145
            return $this->getARInstanceFactory();
1146
        }
1147
1148
        $class = $this->arClass;
1149
1150
        return new $class($this->db, null, $this->tableName);
1151
    }
1152
1153
    /**
1154
     * @throws CircularReferenceException
1155
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
1156
     * @throws NotInstantiableException
1157
     * @throws NotFoundException
1158
     */
1159
    public function getARInstanceFactory(): ActiveRecordInterface
1160
    {
1161
        return $this->arFactory->createAR($this->arClass, $this->tableName, $this->db);
0 ignored issues
show
Bug introduced by
The method createAR() does not exist on null. ( Ignorable by Annotation )

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

1161
        return $this->arFactory->/** @scrutinizer ignore-call */ createAR($this->arClass, $this->tableName, $this->db);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1162
    }
1163
}
1164