Complex classes like BaseRelationQuery 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 BaseRelationQuery, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
17 | trait BaseRelationQuery |
||
18 | { |
||
19 | /** |
||
20 | * @var bool - когда запрос представляет связь с один-ко-многим. Если true, вернуться все найденные модели, иначе только первая |
||
21 | */ |
||
22 | public $multiple; |
||
23 | /** |
||
24 | * @var array - настройка связи моделей. [ключ_у_связанной_модели => ключ_у_текущей_модели] |
||
25 | */ |
||
26 | public $link; |
||
27 | /** |
||
28 | * @var BaseBitrixModel - модель, для которой производится загрузка релейшена |
||
29 | */ |
||
30 | public $primaryModel; |
||
31 | /** |
||
32 | * @var array - список связей, которые должны быть подгружены при выполнении запроса |
||
33 | */ |
||
34 | public $with; |
||
35 | /** |
||
36 | * @var string - название отношения, обратное текущему отношению |
||
37 | */ |
||
38 | public $inverseOf; |
||
39 | |||
40 | /** |
||
41 | * Установить название отношения, обратное текущему отношению |
||
42 | * |
||
43 | * @param string $relationName |
||
44 | * @return $this |
||
45 | */ |
||
46 | public function inverseOf($relationName) |
||
51 | |||
52 | /** |
||
53 | * Найти связанные записи для определенной модели [[$this->primaryModel]] |
||
54 | * Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation |
||
55 | * @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели |
||
56 | * @throws \Exception |
||
57 | */ |
||
58 | public function findFor() |
||
62 | |||
63 | /** |
||
64 | * Определяет связи, которые должны быть загружены при выполнении запроса |
||
65 | * |
||
66 | * Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса |
||
67 | * |
||
68 | * @param array|string $with - связи, которые необходимо жадно подгрузить |
||
69 | * // Загрузить Customer и сразу для каждой модели подгрузить orders и country |
||
70 | * Customer::query()->with(['orders', 'country'])->getList(); |
||
71 | * |
||
72 | * // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address |
||
73 | * Customer::find()->with('orders.address')->getList(); |
||
74 | * |
||
75 | * // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные) |
||
76 | * Customer::find()->with([ |
||
77 | * 'orders' => function (BaseQuery $query) { |
||
78 | * $query->filter(['ACTIVE' => 'Y']); |
||
79 | * }, |
||
80 | * 'country', |
||
81 | * ])->all(); |
||
82 | * |
||
83 | * @return $this |
||
84 | */ |
||
85 | public function with($with) |
||
103 | |||
104 | /** |
||
105 | * Добавить фильтр для загрзуки связи относительно моделей |
||
106 | * @param Collection|BaseBitrixModel[] $models |
||
107 | */ |
||
108 | protected function filterByModels($models) |
||
140 | |||
141 | /** |
||
142 | * Подгрузить связанные модели для уже загруденных моделей |
||
143 | * @param array $with - массив релейшенов, которые необходимо подгрузить |
||
144 | * @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи |
||
145 | */ |
||
146 | public function findWith($with, &$models) |
||
160 | |||
161 | /** |
||
162 | * @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы |
||
163 | * @param array $with |
||
164 | * @return BaseQuery[] |
||
165 | */ |
||
166 | private function normalizeRelations($model, $with) |
||
199 | /** |
||
200 | * Находит связанные записи и заполняет их в первичных моделях. |
||
201 | * @param string $name - имя релейшена |
||
202 | * @param array $primaryModels - первичные модели |
||
203 | * @return Collection|BaseBitrixModel[] - найденные модели |
||
204 | */ |
||
205 | public function populateRelation($name, &$primaryModels) |
||
239 | |||
240 | /** |
||
241 | * Сгруппировать найденные модели |
||
242 | * @param array $models |
||
243 | * @param array $link |
||
244 | * @param bool $checkMultiple |
||
245 | * @return array |
||
246 | */ |
||
247 | private function buildBuckets($models, $link, $checkMultiple = true) |
||
265 | |||
266 | /** |
||
267 | * Получить значение атрибутов в виде строки |
||
268 | * @param BaseBitrixModel $model |
||
269 | * @param array $attributes |
||
270 | * @return string |
||
271 | */ |
||
272 | private function getModelKey($model, $attributes) |
||
284 | |||
285 | /** |
||
286 | * @param mixed $value raw key value. |
||
287 | * @return string normalized key value. |
||
288 | */ |
||
289 | private function normalizeModelKey($value) |
||
298 | |||
299 | /** |
||
300 | * Добавляет основную модель запроса в релейшен |
||
301 | * @param Collection|BaseBitrixModel[] $result |
||
302 | */ |
||
303 | private function addInverseRelations(&$result) |
||
316 | /** |
||
317 | * @param Collection|BaseBitrixModel[] $primaryModels primary models |
||
318 | * @param Collection|BaseBitrixModel[] $models models |
||
319 | * @param string $primaryName the primary relation name |
||
320 | * @param string $name the relation name |
||
321 | */ |
||
322 | private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name) |
||
353 | } |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.