Completed
Push — master ( 856760...5bd6ed )
by Dmitry
12:27
created

ActiveQuery::removeDuplicatedModels()   C

Complexity

Conditions 11
Paths 5

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11.1659

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 46
ccs 24
cts 27
cp 0.8889
rs 5.2653
cc 11
eloc 29
nc 5
nop 1
crap 11.1659

How to fix   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\base\InvalidConfigException;
11
12
/**
13
 * ActiveQuery represents a DB query associated with an Active Record class.
14
 *
15
 * An ActiveQuery can be a normal query or be used in a relational context.
16
 *
17
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
18
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
19
 *
20
 * Normal Query
21
 * ------------
22
 *
23
 * ActiveQuery mainly provides the following methods to retrieve the query results:
24
 *
25
 * - [[one()]]: returns a single record populated with the first row of data.
26
 * - [[all()]]: returns all records based on the query results.
27
 * - [[count()]]: returns the number of records.
28
 * - [[sum()]]: returns the sum over the specified column.
29
 * - [[average()]]: returns the average over the specified column.
30
 * - [[min()]]: returns the min over the specified column.
31
 * - [[max()]]: returns the max over the specified column.
32
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
33
 * - [[column()]]: returns the value of the first column in the query result.
34
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
35
 *
36
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
37
 * [[orderBy()]] to customize the query options.
38
 *
39
 * ActiveQuery also provides the following additional query options:
40
 *
41
 * - [[with()]]: list of relations that this query should be performed with.
42
 * - [[joinWith()]]: reuse a relation query definition to add a join to a query.
43
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
44
 * - [[asArray()]]: whether to return each record as an array.
45
 *
46
 * These options can be configured using methods of the same name. For example:
47
 *
48
 * ```php
49
 * $customers = Customer::find()->with('orders')->asArray()->all();
50
 * ```
51
 *
52
 * Relational query
53
 * ----------------
54
 *
55
 * In relational context ActiveQuery represents a relation between two Active Record classes.
56
 *
57
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
58
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
59
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
60
 *
61
 * A relation is specified by [[link]] which represents the association between columns
62
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
63
 *
64
 * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method.
65
 * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
66
 * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
67
 * is to be added to relational query join condition.
68
 *
69
 * @author Qiang Xue <[email protected]>
70
 * @author Carsten Brandt <[email protected]>
71
 * @since 2.0
72
 */
73
class ActiveQuery extends Query implements ActiveQueryInterface
74
{
75
    use ActiveQueryTrait;
76
    use ActiveRelationTrait;
77
78
    /**
79
     * @event Event an event that is triggered when the query is initialized via [[init()]].
80
     */
81
    const EVENT_INIT = 'init';
82
83
    /**
84
     * @var string the SQL statement to be executed for retrieving AR records.
85
     * This is set by [[ActiveRecord::findBySql()]].
86
     */
87
    public $sql;
88
    /**
89
     * @var string|array the join condition to be used when this query is used in a relational context.
90
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
91
     * Otherwise, the condition will be used in the WHERE part of a query.
92
     * Please refer to [[Query::where()]] on how to specify this parameter.
93
     * @see onCondition()
94
     */
95
    public $on;
96
    /**
97
     * @var array a list of relations that this query should be joined with
98
     */
99
    public $joinWith;
100
101
102
    /**
103
     * Constructor.
104
     * @param string $modelClass the model class associated with this query
105
     * @param array $config configurations to be applied to the newly created query object
106
     */
107 452
    public function __construct($modelClass, $config = [])
108
    {
109 452
        $this->modelClass = $modelClass;
110 452
        parent::__construct($config);
111 452
    }
112
113
    /**
114
     * Initializes the object.
115
     * This method is called at the end of the constructor. The default implementation will trigger
116
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
117
     * to ensure triggering of the event.
118
     */
119 452
    public function init()
120
    {
121 452
        parent::init();
122 452
        $this->trigger(self::EVENT_INIT);
123 452
    }
124
125
    /**
126
     * Executes query and returns all results as an array.
127
     * @param Connection $db the DB connection used to create the DB command.
128
     * If null, the DB connection returned by [[modelClass]] will be used.
129
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
130
     */
131 186
    public function all($db = null)
132
    {
133 186
        return parent::all($db);
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139 360
    public function prepare($builder)
140
    {
141
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
142
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
143
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
144
        // multiple times.
145 360
        if (!empty($this->joinWith)) {
146 48
            $this->buildJoinWith();
147 48
            $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $joinWith.

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...
148
        }
149
150 360
        if (empty($this->from)) {
151 357
            $this->from = [$this->getPrimaryTableName()];
152
        }
153
154 360
        if (empty($this->select) && !empty($this->join)) {
155 39
            list(, $alias) = $this->getTableNameAndAlias();
156 39
            $this->select = ["$alias.*"];
157
        }
158
159 360
        if ($this->primaryModel === null) {
160
            // eager loading
161 359
            $query = Query::create($this);
162
        } else {
163
            // lazy loading of a relation
164 85
            $where = $this->where;
165
166 85
            if ($this->via instanceof self) {
167
                // via junction table
168 15
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
169 15
                $this->filterByModels($viaModels);
170 76
            } elseif (is_array($this->via)) {
171
                // via relation
172
                /* @var $viaQuery ActiveQuery */
173 27
                list($viaName, $viaQuery) = $this->via;
174 27
                if ($viaQuery->multiple) {
175 27
                    $viaModels = $viaQuery->all();
176 27
                    $this->primaryModel->populateRelation($viaName, $viaModels);
177
                } else {
178
                    $model = $viaQuery->one();
179
                    $this->primaryModel->populateRelation($viaName, $model);
180
                    $viaModels = $model === null ? [] : [$model];
181
                }
182 27
                $this->filterByModels($viaModels);
183
            } else {
184 76
                $this->filterByModels([$this->primaryModel]);
185
            }
186
187 85
            $query = Query::create($this);
188 85
            $this->where = $where;
189
        }
190
191 360
        if (!empty($this->on)) {
192 18
            $query->andWhere($this->on);
193
        }
194
195 360
        return $query;
196
    }
197
198
    /**
199
     * {@inheritdoc}
200
     */
201 304
    public function populate($rows)
202
    {
203 304
        if (empty($rows)) {
204 52
            return [];
205
        }
206
207 295
        $models = $this->createModels($rows);
208 295
        if (!empty($this->join) && $this->indexBy === null) {
209 33
            $models = $this->removeDuplicatedModels($models);
210
        }
211 295
        if (!empty($this->with)) {
212 78
            $this->findWith($this->with, $models);
213
        }
214
215 295
        if ($this->inverseOf !== null) {
216 9
            $this->addInverseRelations($models);
217
        }
218
219 295
        if (!$this->asArray) {
220 285
            foreach ($models as $model) {
221 285
                $model->afterFind();
222
            }
223
        }
224
225 295
        return $models;
226
    }
227
228
    /**
229
     * Removes duplicated models by checking their primary key values.
230
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
231
     * @param array $models the models to be checked
232
     * @throws InvalidConfigException if model primary key is empty
233
     * @return array the distinctive models
234
     */
235 33
    private function removeDuplicatedModels($models)
236
    {
237 33
        $hash = [];
238
        /* @var $class ActiveRecord */
239 33
        $class = $this->modelClass;
240 33
        $pks = $class::primaryKey();
241
242 33
        if (count($pks) > 1) {
243
            // composite primary key
244 6
            foreach ($models as $i => $model) {
245 6
                $key = [];
246 6
                foreach ($pks as $pk) {
247 6
                    if (!isset($model[$pk])) {
248
                        // do not continue if the primary key is not part of the result set
249 3
                        break 2;
250
                    }
251 6
                    $key[] = $model[$pk];
252
                }
253 3
                $key = serialize($key);
254 3
                if (isset($hash[$key])) {
255
                    unset($models[$i]);
256
                } else {
257 6
                    $hash[$key] = true;
258
                }
259
            }
260
        } elseif (empty($pks)) {
261
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
262
        } else {
263
            // single column primary key
264 30
            $pk = reset($pks);
265 30
            foreach ($models as $i => $model) {
266 30
                if (!isset($model[$pk])) {
267
                    // do not continue if the primary key is not part of the result set
268 3
                    break;
269
                }
270 27
                $key = $model[$pk];
271 27
                if (isset($hash[$key])) {
272 12
                    unset($models[$i]);
273 27
                } elseif ($key !== null) {
274 27
                    $hash[$key] = true;
275
                }
276
            }
277
        }
278
279 33
        return array_values($models);
280
    }
281
282
    /**
283
     * Executes query and returns a single row of result.
284
     * @param Connection|null $db the DB connection used to create the DB command.
285
     * If `null`, the DB connection returned by [[modelClass]] will be used.
286
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
287
     * the query result may be either an array or an ActiveRecord object. `null` will be returned
288
     * if the query results in nothing.
289
     */
290 251
    public function one($db = null)
291
    {
292 251
        $row = parent::one($db);
293 251
        if ($row !== false) {
294 248
            $models = $this->populate([$row]);
295 248
            return reset($models) ?: null;
296
        }
297
298 24
        return null;
299
    }
300
301
    /**
302
     * Creates a DB command that can be used to execute this query.
303
     * @param Connection|null $db the DB connection used to create the DB command.
304
     * If `null`, the DB connection returned by [[modelClass]] will be used.
305
     * @return Command the created DB command instance.
306
     */
307 360
    public function createCommand($db = null)
308
    {
309
        /* @var $modelClass ActiveRecord */
310 360
        $modelClass = $this->modelClass;
311 360
        if ($db === null) {
312 349
            $db = $modelClass::getDb();
313
        }
314
315 360
        if ($this->sql === null) {
316 357
            list($sql, $params) = $db->getQueryBuilder()->build($this);
317
        } else {
318 3
            $sql = $this->sql;
319 3
            $params = $this->params;
320
        }
321
322 360
        $command = $db->createCommand($sql, $params);
323 360
        $this->setCommandCache($command);
324
325 360
        return $command;
326
    }
327
328
    /**
329
     * {@inheritdoc}
330
     */
331 64
    protected function queryScalar($selectExpression, $db)
332
    {
333
        /* @var $modelClass ActiveRecord */
334 64
        $modelClass = $this->modelClass;
335 64
        if ($db === null) {
336 63
            $db = $modelClass::getDb();
337
        }
338
339 64
        if ($this->sql === null) {
340 61
            return parent::queryScalar($selectExpression, $db);
341
        }
342
343 3
        $command = (new Query())->select([$selectExpression])
344 3
            ->from(['c' => "({$this->sql})"])
345 3
            ->params($this->params)
346 3
            ->createCommand($db);
347 3
        $this->setCommandCache($command);
348
349 3
        return $command->queryScalar();
350
    }
351
352
    /**
353
     * Joins with the specified relations.
354
     *
355
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
356
     * Based on the definition of the specified relation(s), the method will append one or multiple
357
     * JOIN statements to the current query.
358
     *
359
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
360
     * which is equivalent to calling [[with()]] using the specified relations.
361
     *
362
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
363
     *
364
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
365
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
366
     *
367
     * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
368
     * an array with the following semantics:
369
     *
370
     * - Each array element represents a single relation.
371
     * - You may specify the relation name as the array key and provide an anonymous functions that
372
     *   can be used to modify the relation queries on-the-fly as the array value.
373
     * - If a relation query does not need modification, you may use the relation name as the array value.
374
     *
375
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
376
     *
377
     * Sub-relations can also be specified, see [[with()]] for the syntax.
378
     *
379
     * In the following you find some examples:
380
     *
381
     * ```php
382
     * // find all orders that contain books, and eager loading "books"
383
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
384
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
385
     * Order::find()->joinWith([
386
     *     'books' => function (\yii\db\ActiveQuery $query) {
387
     *         $query->orderBy('item.name');
388
     *     }
389
     * ])->all();
390
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
391
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
392
     * ```
393
     *
394
     * The alias syntax is available since version 2.0.7.
395
     *
396
     * @param bool|array $eagerLoading whether to eager load the relations
397
     * specified in `$with`.  When this is a boolean, it applies to all
398
     * relations specified in `$with`. Use an array to explicitly list which
399
     * relations in `$with` need to be eagerly loaded.  Note, that this does
400
     * not mean, that the relations are populated from the query result. An
401
     * extra query will still be performed to bring in the related data.
402
     * Defaults to `true`.
403
     * @param string|array $joinType the join type of the relations specified in `$with`.
404
     * When this is a string, it applies to all relations specified in `$with`. Use an array
405
     * in the format of `relationName => joinType` to specify different join types for different relations.
406
     * @return $this the query object itself
407
     */
408 54
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
409
    {
410 54
        $relations = [];
411 54
        foreach ((array) $with as $name => $callback) {
412 54
            if (is_int($name)) {
413 54
                $name = $callback;
414 54
                $callback = null;
415
            }
416
417 54
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
418
                // relation is defined with an alias, adjust callback to apply alias
419 12
                list(, $relation, $alias) = $matches;
420 12
                $name = $relation;
421 12
                $callback = function ($query) use ($callback, $alias) {
422
                    /* @var $query ActiveQuery */
423 12
                    $query->alias($alias);
424 12
                    if ($callback !== null) {
425 9
                        call_user_func($callback, $query);
426
                    }
427 12
                };
428
            }
429
430 54
            if ($callback === null) {
431 51
                $relations[] = $name;
432
            } else {
433 54
                $relations[$name] = $callback;
434
            }
435
        }
436 54
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
437 54
        return $this;
438
    }
439
440 48
    private function buildJoinWith()
441
    {
442 48
        $join = $this->join;
443 48
        $this->join = [];
444
445
        /* @var $modelClass ActiveRecordInterface */
446 48
        $modelClass = $this->modelClass;
447 48
        $model = $modelClass::instance();
448 48
        foreach ($this->joinWith as $config) {
449 48
            list($with, $eagerLoading, $joinType) = $config;
450 48
            $this->joinWithRelations($model, $with, $joinType);
0 ignored issues
show
Compatibility introduced by
$model of type object<yii\db\ActiveRecordInterface> is not a sub-type of object<yii\db\ActiveRecord>. It seems like you assume a concrete implementation of the interface yii\db\ActiveRecordInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
451
452 48
            if (is_array($eagerLoading)) {
453
                foreach ($with as $name => $callback) {
454
                    if (is_int($name)) {
455
                        if (!in_array($callback, $eagerLoading, true)) {
456
                            unset($with[$name]);
457
                        }
458
                    } elseif (!in_array($name, $eagerLoading, true)) {
459
                        unset($with[$name]);
460
                    }
461
                }
462 48
            } elseif (!$eagerLoading) {
463 15
                $with = [];
464
            }
465
466 48
            $this->with($with);
467
        }
468
469
        // remove duplicated joins added by joinWithRelations that may be added
470
        // e.g. when joining a relation and a via relation at the same time
471 48
        $uniqueJoins = [];
472 48
        foreach ($this->join as $j) {
473 48
            $uniqueJoins[serialize($j)] = $j;
474
        }
475 48
        $this->join = array_values($uniqueJoins);
476
477 48
        if (!empty($join)) {
478
            // append explicit join to joinWith()
479
            // https://github.com/yiisoft/yii2/issues/2880
480
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
481
        }
482 48
    }
483
484
    /**
485
     * Inner joins with the specified relations.
486
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
487
     * Please refer to [[joinWith()]] for detailed usage of this method.
488
     * @param string|array $with the relations to be joined with.
489
     * @param bool|array $eagerLoading whether to eager load the relations.
490
     * Note, that this does not mean, that the relations are populated from the
491
     * query result. An extra query will still be performed to bring in the
492
     * related data.
493
     * @return $this the query object itself
494
     * @see joinWith()
495
     */
496 18
    public function innerJoinWith($with, $eagerLoading = true)
497
    {
498 18
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
499
    }
500
501
    /**
502
     * Modifies the current query by adding join fragments based on the given relations.
503
     * @param ActiveRecord $model the primary model
504
     * @param array $with the relations to be joined
505
     * @param string|array $joinType the join type
506
     */
507 48
    private function joinWithRelations($model, $with, $joinType)
508
    {
509 48
        $relations = [];
510
511 48
        foreach ($with as $name => $callback) {
512 48
            if (is_int($name)) {
513 45
                $name = $callback;
514 45
                $callback = null;
515
            }
516
517 48
            $primaryModel = $model;
518 48
            $parent = $this;
519 48
            $prefix = '';
520 48
            while (($pos = strpos($name, '.')) !== false) {
521 6
                $childName = substr($name, $pos + 1);
522 6
                $name = substr($name, 0, $pos);
523 6
                $fullName = $prefix === '' ? $name : "$prefix.$name";
524 6
                if (!isset($relations[$fullName])) {
525
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
526
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
0 ignored issues
show
Compatibility introduced by
$relation of type object<yii\db\ActiveQueryInterface> is not a sub-type of object<yii\db\ActiveQuery>. It seems like you assume a concrete implementation of the interface yii\db\ActiveQueryInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
527
                } else {
528 6
                    $relation = $relations[$fullName];
529
                }
530
                /* @var $relationModelClass ActiveRecordInterface */
531 6
                $relationModelClass = $relation->modelClass;
532 6
                $primaryModel = $relationModelClass::instance();
533 6
                $parent = $relation;
534 6
                $prefix = $fullName;
535 6
                $name = $childName;
536
            }
537
538 48
            $fullName = $prefix === '' ? $name : "$prefix.$name";
539 48
            if (!isset($relations[$fullName])) {
540 48
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
541 48
                if ($callback !== null) {
542 18
                    call_user_func($callback, $relation);
543
                }
544 48
                if (!empty($relation->joinWith)) {
0 ignored issues
show
Bug introduced by
Accessing joinWith on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
545 6
                    $relation->buildJoinWith();
546
                }
547 48
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
0 ignored issues
show
Compatibility introduced by
$relation of type object<yii\db\ActiveQueryInterface> is not a sub-type of object<yii\db\ActiveQuery>. It seems like you assume a concrete implementation of the interface yii\db\ActiveQueryInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
548
            }
549
        }
550 48
    }
551
552
    /**
553
     * Returns the join type based on the given join type parameter and the relation name.
554
     * @param string|array $joinType the given join type(s)
555
     * @param string $name relation name
556
     * @return string the real join type
557
     */
558 48
    private function getJoinType($joinType, $name)
559
    {
560 48
        if (is_array($joinType) && isset($joinType[$name])) {
561
            return $joinType[$name];
562
        }
563
564 48
        return is_string($joinType) ? $joinType : 'INNER JOIN';
565
    }
566
567
    /**
568
     * Returns the table name and the table alias for [[modelClass]].
569
     * @return array the table name and the table alias.
570
     * @internal
571
     */
572 66
    private function getTableNameAndAlias()
573
    {
574 66
        if (empty($this->from)) {
575 60
            $tableName = $this->getPrimaryTableName();
576
        } else {
577 51
            $tableName = '';
578 51
            foreach ($this->from as $alias => $tableName) {
579 51
                if (is_string($alias)) {
580 18
                    return [$tableName, $alias];
581
                }
582 42
                break;
583
            }
584
        }
585
586 63
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
587 3
            $alias = $matches[2];
588
        } else {
589 63
            $alias = $tableName;
590
        }
591
592 63
        return [$tableName, $alias];
593
    }
594
595
    /**
596
     * Joins a parent query with a child query.
597
     * The current query object will be modified accordingly.
598
     * @param ActiveQuery $parent
599
     * @param ActiveQuery $child
600
     * @param string $joinType
601
     */
602 48
    private function joinWithRelation($parent, $child, $joinType)
603
    {
604 48
        $via = $child->via;
605 48
        $child->via = null;
606 48
        if ($via instanceof self) {
607
            // via table
608 9
            $this->joinWithRelation($parent, $via, $joinType);
609 9
            $this->joinWithRelation($via, $child, $joinType);
610 9
            return;
611 48
        } elseif (is_array($via)) {
612
            // via relation
613 15
            $this->joinWithRelation($parent, $via[1], $joinType);
614 15
            $this->joinWithRelation($via[1], $child, $joinType);
615 15
            return;
616
        }
617
618 48
        list($parentTable, $parentAlias) = $parent->getTableNameAndAlias();
0 ignored issues
show
Unused Code introduced by
The assignment to $parentTable is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
619 48
        list($childTable, $childAlias) = $child->getTableNameAndAlias();
620
621 48
        if (!empty($child->link)) {
622 48
            if (strpos($parentAlias, '{{') === false) {
623 42
                $parentAlias = '{{' . $parentAlias . '}}';
624
            }
625 48
            if (strpos($childAlias, '{{') === false) {
626 48
                $childAlias = '{{' . $childAlias . '}}';
627
            }
628
629 48
            $on = [];
630 48
            foreach ($child->link as $childColumn => $parentColumn) {
631 48
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
632
            }
633 48
            $on = implode(' AND ', $on);
634 48
            if (!empty($child->on)) {
635 48
                $on = ['and', $on, $child->on];
636
            }
637
        } else {
638
            $on = $child->on;
639
        }
640 48
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
641
642 48
        if (!empty($child->where)) {
643 6
            $this->andWhere($child->where);
644
        }
645 48
        if (!empty($child->having)) {
646
            $this->andHaving($child->having);
647
        }
648 48
        if (!empty($child->orderBy)) {
649 15
            $this->addOrderBy($child->orderBy);
650
        }
651 48
        if (!empty($child->groupBy)) {
652
            $this->addGroupBy($child->groupBy);
653
        }
654 48
        if (!empty($child->params)) {
655
            $this->addParams($child->params);
656
        }
657 48
        if (!empty($child->join)) {
658 6
            foreach ($child->join as $join) {
659 6
                $this->join[] = $join;
660
            }
661
        }
662 48
        if (!empty($child->union)) {
663
            foreach ($child->union as $union) {
664
                $this->union[] = $union;
665
            }
666
        }
667 48
    }
668
669
    /**
670
     * Sets the ON condition for a relational query.
671
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
672
     * Otherwise, the condition will be used in the WHERE part of a query.
673
     *
674
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
675
     *
676
     * ```php
677
     * public function getActiveUsers()
678
     * {
679
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])
680
     *                 ->onCondition(['active' => true]);
681
     * }
682
     * ```
683
     *
684
     * Note that this condition is applied in case of a join as well as when fetching the related records.
685
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
686
     * record will cause an error in a non-join-query.
687
     *
688
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
689
     * @param array $params the parameters (name => value) to be bound to the query.
690
     * @return $this the query object itself
691
     */
692 21
    public function onCondition($condition, $params = [])
693
    {
694 21
        $this->on = $condition;
695 21
        $this->addParams($params);
696 21
        return $this;
697
    }
698
699
    /**
700
     * Adds an additional ON condition to the existing one.
701
     * The new condition and the existing one will be joined using the 'AND' operator.
702
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
703
     * on how to specify this parameter.
704
     * @param array $params the parameters (name => value) to be bound to the query.
705
     * @return $this the query object itself
706
     * @see onCondition()
707
     * @see orOnCondition()
708
     */
709 6
    public function andOnCondition($condition, $params = [])
710
    {
711 6
        if ($this->on === null) {
712 3
            $this->on = $condition;
713
        } else {
714 3
            $this->on = ['and', $this->on, $condition];
715
        }
716 6
        $this->addParams($params);
717 6
        return $this;
718
    }
719
720
    /**
721
     * Adds an additional ON condition to the existing one.
722
     * The new condition and the existing one will be joined using the 'OR' operator.
723
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
724
     * on how to specify this parameter.
725
     * @param array $params the parameters (name => value) to be bound to the query.
726
     * @return $this the query object itself
727
     * @see onCondition()
728
     * @see andOnCondition()
729
     */
730 6
    public function orOnCondition($condition, $params = [])
731
    {
732 6
        if ($this->on === null) {
733 3
            $this->on = $condition;
734
        } else {
735 3
            $this->on = ['or', $this->on, $condition];
736
        }
737 6
        $this->addParams($params);
738 6
        return $this;
739
    }
740
741
    /**
742
     * Specifies the junction table for a relational query.
743
     *
744
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
745
     *
746
     * ```php
747
     * public function getItems()
748
     * {
749
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
750
     *                 ->viaTable('order_item', ['order_id' => 'id']);
751
     * }
752
     * ```
753
     *
754
     * @param string $tableName the name of the junction table.
755
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
756
     * The keys of the array represent the columns in the junction table, and the values represent the columns
757
     * in the [[primaryModel]] table.
758
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
759
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
760
     * @return $this the query object itself
761
     * @see via()
762
     */
763 24
    public function viaTable($tableName, $link, callable $callable = null)
764
    {
765 24
        $modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : get_class();
766
767 24
        $relation = new self($modelClass, [
768 24
            'from' => [$tableName],
769 24
            'link' => $link,
770
            'multiple' => true,
771
            'asArray' => true,
772
        ]);
773 24
        $this->via = $relation;
774 24
        if ($callable !== null) {
775 6
            call_user_func($callable, $relation);
776
        }
777
778 24
        return $this;
779
    }
780
781
    /**
782
     * Define an alias for the table defined in [[modelClass]].
783
     *
784
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
785
     * If none was defined, [[from]] will be populated with the given alias.
786
     *
787
     * @param string $alias the table alias.
788
     * @return $this the query object itself
789
     * @since 2.0.7
790
     */
791 24
    public function alias($alias)
792
    {
793 24
        if (empty($this->from) || count($this->from) < 2) {
794 24
            list($tableName) = $this->getTableNameAndAlias();
795 24
            $this->from = [$alias => $tableName];
796
        } else {
797 3
            $tableName = $this->getPrimaryTableName();
798
799 3
            foreach ($this->from as $key => $table) {
800 3
                if ($table === $tableName) {
801 3
                    unset($this->from[$key]);
802 3
                    $this->from[$alias] = $tableName;
803
                }
804
            }
805
        }
806
807 24
        return $this;
808
    }
809
810
    /**
811
     * {@inheritdoc}
812
     * @since 2.0.12
813
     */
814 132
    public function getTablesUsedInFrom()
815
    {
816 132
        if (empty($this->from)) {
817 99
            return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
818
        }
819
820 33
        return parent::getTablesUsedInFrom();
821
    }
822
823
    /**
824
     * @return string primary table name
825
     * @since 2.0.12
826
     */
827 375
    protected function getPrimaryTableName()
828
    {
829
        /* @var $modelClass ActiveRecord */
830 375
        $modelClass = $this->modelClass;
831 375
        return $modelClass::tableName();
832
    }
833
}
834