Complex classes like ActiveQuery often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ActiveQuery, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
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 | 285 | public function __construct($modelClass, $config = []) |
|
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 | 285 | public function init() |
|
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 | 158 | public function all($db = null) |
|
135 | |||
136 | /** |
||
137 | * @inheritdoc |
||
138 | */ |
||
139 | 274 | public function prepare($builder) |
|
200 | |||
201 | /** |
||
202 | * @inheritdoc |
||
203 | */ |
||
204 | 245 | public function populate($rows) |
|
205 | { |
||
206 | 245 | if (empty($rows)) { |
|
207 | 37 | return []; |
|
208 | } |
||
209 | |||
210 | 245 | $models = $this->createModels($rows); |
|
211 | 245 | if (!empty($this->join) && $this->indexBy === null) { |
|
212 | 24 | $models = $this->removeDuplicatedModels($models); |
|
213 | 24 | } |
|
214 | 245 | if (!empty($this->with)) { |
|
215 | 63 | $this->findWith($this->with, $models); |
|
216 | 63 | } |
|
217 | |||
218 | 245 | if ($this->inverseOf !== null) { |
|
219 | 6 | $this->addInverseRelations($models); |
|
220 | 6 | } |
|
221 | |||
222 | 245 | if (!$this->asArray) { |
|
223 | 239 | foreach ($models as $model) { |
|
224 | 239 | $model->afterFind(); |
|
225 | 239 | } |
|
226 | 239 | } |
|
227 | |||
228 | 245 | if ($this->collectionClass !== null) { |
|
229 | 3 | return new $this->collectionClass($models); |
|
230 | } |
||
231 | |||
232 | 242 | return $models; |
|
233 | } |
||
234 | |||
235 | /** |
||
236 | * Removes duplicated models by checking their primary key values. |
||
237 | * This method is mainly called when a join query is performed, which may cause duplicated rows being returned. |
||
238 | * @param array $models the models to be checked |
||
239 | * @throws InvalidConfigException if model primary key is empty |
||
240 | * @return array the distinctive models |
||
241 | */ |
||
242 | 24 | private function removeDuplicatedModels($models) |
|
288 | |||
289 | /** |
||
290 | * Executes query and returns a single row of result. |
||
291 | * @param Connection $db the DB connection used to create the DB command. |
||
292 | * If null, the DB connection returned by [[modelClass]] will be used. |
||
293 | * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]], |
||
294 | * the query result may be either an array or an ActiveRecord object. Null will be returned |
||
295 | * if the query results in nothing. |
||
296 | */ |
||
297 | 202 | public function one($db = null) |
|
307 | |||
308 | /** |
||
309 | * Creates a DB command that can be used to execute this query. |
||
310 | * @param Connection $db the DB connection used to create the DB command. |
||
311 | * If null, the DB connection returned by [[modelClass]] will be used. |
||
312 | * @return Command the created DB command instance. |
||
313 | */ |
||
314 | 277 | public function createCommand($db = null) |
|
331 | |||
332 | /** |
||
333 | * @inheritdoc |
||
334 | */ |
||
335 | 52 | protected function queryScalar($selectExpression, $db) |
|
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 boolean|array $eagerLoading whether to eager load the relations specified in `$with`. |
||
397 | * When this is a boolean, it applies to all relations specified in `$with`. Use an array |
||
398 | * to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`. |
||
399 | * @param string|array $joinType the join type of the relations specified in `$with`. |
||
400 | * When this is a string, it applies to all relations specified in `$with`. Use an array |
||
401 | * in the format of `relationName => joinType` to specify different join types for different relations. |
||
402 | * @return $this the query object itself |
||
403 | */ |
||
404 | 36 | public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN') |
|
435 | |||
436 | 75 | private function buildJoinWith() |
|
477 | |||
478 | /** |
||
479 | * Inner joins with the specified relations. |
||
480 | * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN". |
||
481 | * Please refer to [[joinWith()]] for detailed usage of this method. |
||
482 | * @param string|array $with the relations to be joined with. |
||
483 | * @param boolean|array $eagerLoading whether to eager loading the relations. |
||
484 | * @return $this the query object itself |
||
485 | * @see joinWith() |
||
486 | */ |
||
487 | 9 | public function innerJoinWith($with, $eagerLoading = true) |
|
491 | |||
492 | /** |
||
493 | * Modifies the current query by adding join fragments based on the given relations. |
||
494 | * @param ActiveRecord $model the primary model |
||
495 | * @param array $with the relations to be joined |
||
496 | * @param string|array $joinType the join type |
||
497 | */ |
||
498 | 36 | private function joinWithRelations($model, $with, $joinType) |
|
540 | |||
541 | /** |
||
542 | * Returns the join type based on the given join type parameter and the relation name. |
||
543 | * @param string|array $joinType the given join type(s) |
||
544 | * @param string $name relation name |
||
545 | * @return string the real join type |
||
546 | */ |
||
547 | 36 | private function getJoinType($joinType, $name) |
|
555 | |||
556 | /** |
||
557 | * Returns the table name and the table alias for [[modelClass]]. |
||
558 | * @param ActiveQuery $query |
||
559 | * @return array the table name and the table alias. |
||
560 | */ |
||
561 | 39 | private function getQueryTableName($query) |
|
562 | { |
||
563 | 39 | if (empty($query->from)) { |
|
564 | /* @var $modelClass ActiveRecord */ |
||
565 | 39 | $modelClass = $query->modelClass; |
|
566 | 39 | $tableName = $modelClass::tableName(); |
|
567 | 39 | } else { |
|
568 | 36 | $tableName = ''; |
|
569 | 36 | foreach ($query->from as $alias => $tableName) { |
|
570 | 36 | if (is_string($alias)) { |
|
571 | 12 | return [$tableName, $alias]; |
|
572 | } else { |
||
573 | 33 | break; |
|
574 | } |
||
575 | 33 | } |
|
576 | } |
||
577 | |||
578 | 39 | if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) { |
|
579 | 3 | $alias = $matches[2]; |
|
580 | 3 | } else { |
|
581 | 39 | $alias = $tableName; |
|
582 | } |
||
583 | |||
584 | 39 | return [$tableName, $alias]; |
|
585 | } |
||
586 | |||
587 | /** |
||
588 | * Joins a parent query with a child query. |
||
589 | * The current query object will be modified accordingly. |
||
590 | * @param ActiveQuery $parent |
||
591 | * @param ActiveQuery $child |
||
592 | * @param string $joinType |
||
593 | */ |
||
594 | 36 | private function joinWithRelation($parent, $child, $joinType) |
|
595 | { |
||
596 | 36 | $via = $child->via; |
|
597 | 36 | $child->via = null; |
|
598 | 36 | if ($via instanceof ActiveQuery) { |
|
599 | // via table |
||
600 | 9 | $this->joinWithRelation($parent, $via, $joinType); |
|
601 | 9 | $this->joinWithRelation($via, $child, $joinType); |
|
602 | 9 | return; |
|
603 | 36 | } elseif (is_array($via)) { |
|
604 | // via relation |
||
605 | 12 | $this->joinWithRelation($parent, $via[1], $joinType); |
|
606 | 12 | $this->joinWithRelation($via[1], $child, $joinType); |
|
607 | 12 | return; |
|
608 | } |
||
609 | |||
610 | 36 | list ($parentTable, $parentAlias) = $this->getQueryTableName($parent); |
|
611 | 36 | list ($childTable, $childAlias) = $this->getQueryTableName($child); |
|
612 | |||
613 | 36 | if (!empty($child->link)) { |
|
614 | |||
615 | 36 | if (strpos($parentAlias, '{{') === false) { |
|
616 | 30 | $parentAlias = '{{' . $parentAlias . '}}'; |
|
617 | 30 | } |
|
618 | 36 | if (strpos($childAlias, '{{') === false) { |
|
619 | 36 | $childAlias = '{{' . $childAlias . '}}'; |
|
620 | 36 | } |
|
621 | |||
622 | 36 | $on = []; |
|
623 | 36 | foreach ($child->link as $childColumn => $parentColumn) { |
|
624 | 36 | $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]"; |
|
625 | 36 | } |
|
626 | 36 | $on = implode(' AND ', $on); |
|
627 | 36 | if (!empty($child->on)) { |
|
628 | 9 | $on = ['and', $on, $child->on]; |
|
629 | 9 | } |
|
630 | 36 | } else { |
|
631 | $on = $child->on; |
||
632 | } |
||
633 | 36 | $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on); |
|
634 | |||
635 | 36 | if (!empty($child->where)) { |
|
636 | 6 | $this->andWhere($child->where); |
|
637 | 6 | } |
|
638 | 36 | if (!empty($child->having)) { |
|
639 | $this->andHaving($child->having); |
||
640 | } |
||
641 | 36 | if (!empty($child->orderBy)) { |
|
642 | 12 | $this->addOrderBy($child->orderBy); |
|
643 | 12 | } |
|
644 | 36 | if (!empty($child->groupBy)) { |
|
645 | $this->addGroupBy($child->groupBy); |
||
646 | } |
||
647 | 36 | if (!empty($child->params)) { |
|
648 | $this->addParams($child->params); |
||
649 | } |
||
650 | 36 | if (!empty($child->join)) { |
|
651 | 6 | foreach ($child->join as $join) { |
|
652 | 6 | $this->join[] = $join; |
|
653 | 6 | } |
|
654 | 6 | } |
|
655 | 36 | if (!empty($child->union)) { |
|
656 | foreach ($child->union as $union) { |
||
657 | $this->union[] = $union; |
||
658 | } |
||
659 | } |
||
660 | 36 | } |
|
661 | |||
662 | /** |
||
663 | * Sets the ON condition for a relational query. |
||
664 | * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called. |
||
665 | * Otherwise, the condition will be used in the WHERE part of a query. |
||
666 | * |
||
667 | * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class: |
||
668 | * |
||
669 | * ```php |
||
670 | * public function getActiveUsers() |
||
671 | * { |
||
672 | * return $this->hasMany(User::className(), ['id' => 'user_id']) |
||
673 | * ->onCondition(['active' => true]); |
||
674 | * } |
||
675 | * ``` |
||
676 | * |
||
677 | * Note that this condition is applied in case of a join as well as when fetching the related records. |
||
678 | * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary |
||
679 | * record will cause an error in a non-join-query. |
||
680 | * |
||
681 | * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter. |
||
682 | * @param array $params the parameters (name => value) to be bound to the query. |
||
683 | * @return $this the query object itself |
||
684 | */ |
||
685 | 12 | public function onCondition($condition, $params = []) |
|
691 | |||
692 | /** |
||
693 | * Adds an additional ON condition to the existing one. |
||
694 | * The new condition and the existing one will be joined using the 'AND' operator. |
||
695 | * @param string|array $condition the new ON condition. Please refer to [[where()]] |
||
696 | * on how to specify this parameter. |
||
697 | * @param array $params the parameters (name => value) to be bound to the query. |
||
698 | * @return $this the query object itself |
||
699 | * @see onCondition() |
||
700 | * @see orOnCondition() |
||
701 | */ |
||
702 | public function andOnCondition($condition, $params = []) |
||
712 | |||
713 | /** |
||
714 | * Adds an additional ON condition to the existing one. |
||
715 | * The new condition and the existing one will be joined using the 'OR' operator. |
||
716 | * @param string|array $condition the new ON condition. Please refer to [[where()]] |
||
717 | * on how to specify this parameter. |
||
718 | * @param array $params the parameters (name => value) to be bound to the query. |
||
719 | * @return $this the query object itself |
||
720 | * @see onCondition() |
||
721 | * @see andOnCondition() |
||
722 | */ |
||
723 | public function orOnCondition($condition, $params = []) |
||
733 | |||
734 | /** |
||
735 | * Specifies the junction table for a relational query. |
||
736 | * |
||
737 | * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class: |
||
738 | * |
||
739 | * ```php |
||
740 | * public function getItems() |
||
741 | * { |
||
742 | * return $this->hasMany(Item::className(), ['id' => 'item_id']) |
||
743 | * ->viaTable('order_item', ['order_id' => 'id']); |
||
744 | * } |
||
745 | * ``` |
||
746 | * |
||
747 | * @param string $tableName the name of the junction table. |
||
748 | * @param array $link the link between the junction table and the table associated with [[primaryModel]]. |
||
749 | * The keys of the array represent the columns in the junction table, and the values represent the columns |
||
750 | * in the [[primaryModel]] table. |
||
751 | * @param callable $callable a PHP callback for customizing the relation associated with the junction table. |
||
752 | * Its signature should be `function($query)`, where `$query` is the query to be customized. |
||
753 | * @return $this the query object itself |
||
754 | * @see via() |
||
755 | */ |
||
756 | 18 | public function viaTable($tableName, $link, callable $callable = null) |
|
771 | |||
772 | /** |
||
773 | * Define an alias for the table defined in [[modelClass]]. |
||
774 | * |
||
775 | * This method will adjust [[from]] so that an already defined alias will be overwritten. |
||
776 | * If none was defined, [[from]] will be populated with the given alias. |
||
777 | * |
||
778 | * @param string $alias the table alias. |
||
779 | * @return $this the query object itself |
||
780 | * @since 2.0.7 |
||
781 | */ |
||
782 | 12 | public function alias($alias) |
|
801 | } |
||
802 |
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..