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 string - настройка связи моделей. ключ_у_связанной_модели |
||
| 25 | */ |
||
| 26 | public $foreignKey; |
||
| 27 | /** |
||
| 28 | * @var string - настройка связи моделей. ключ_у_текущей_модели |
||
| 29 | */ |
||
| 30 | public $localKey; |
||
| 31 | /** |
||
| 32 | * @var BaseBitrixModel - модель, для которой производится загрузка релейшена |
||
| 33 | */ |
||
| 34 | public $primaryModel; |
||
| 35 | /** |
||
| 36 | * @var array - список связей, которые должны быть подгружены при выполнении запроса |
||
| 37 | */ |
||
| 38 | public $with; |
||
| 39 | /** |
||
| 40 | * @var string - название отношения, обратное текущему отношению |
||
| 41 | */ |
||
| 42 | public $inverseOf; |
||
| 43 | |||
| 44 | /** |
||
| 45 | * Установить название отношения, обратное текущему отношению |
||
| 46 | * |
||
| 47 | * @param string $relationName |
||
| 48 | * @return $this |
||
| 49 | */ |
||
| 50 | public function inverseOf($relationName) |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Найти связанные записи для определенной модели [[$this->primaryModel]] |
||
| 58 | * Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation |
||
| 59 | * @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели |
||
| 60 | * @throws \Exception |
||
| 61 | */ |
||
| 62 | public function findFor() |
||
| 66 | |||
| 67 | /** |
||
| 68 | * Определяет связи, которые должны быть загружены при выполнении запроса |
||
| 69 | * |
||
| 70 | * Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса |
||
| 71 | * |
||
| 72 | * @param array|string $with - связи, которые необходимо жадно подгрузить |
||
| 73 | * // Загрузить Customer и сразу для каждой модели подгрузить orders и country |
||
| 74 | * Customer::query()->with(['orders', 'country'])->getList(); |
||
| 75 | * |
||
| 76 | * // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address |
||
| 77 | * Customer::find()->with('orders.address')->getList(); |
||
| 78 | * |
||
| 79 | * // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные) |
||
| 80 | * Customer::find()->with([ |
||
| 81 | * 'orders' => function (BaseQuery $query) { |
||
| 82 | * $query->filter(['ACTIVE' => 'Y']); |
||
| 83 | * }, |
||
| 84 | * 'country', |
||
| 85 | * ])->all(); |
||
| 86 | * |
||
| 87 | * @return $this |
||
| 88 | */ |
||
| 89 | public function with($with) |
||
| 107 | |||
| 108 | /** |
||
| 109 | * Добавить фильтр для загрзуки связи относительно моделей |
||
| 110 | * @param Collection|BaseBitrixModel[] $models |
||
| 111 | */ |
||
| 112 | protected function filterByModels($models) |
||
| 137 | |||
| 138 | /** |
||
| 139 | * Подгрузить связанные модели для уже загруденных моделей |
||
| 140 | * @param array $with - массив релейшенов, которые необходимо подгрузить |
||
| 141 | * @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи |
||
| 142 | */ |
||
| 143 | public function findWith($with, &$models) |
||
| 157 | |||
| 158 | /** |
||
| 159 | * @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы |
||
| 160 | * @param array $with |
||
| 161 | * @return BaseQuery[] |
||
| 162 | */ |
||
| 163 | private function normalizeRelations($model, $with) |
||
| 196 | /** |
||
| 197 | * Находит связанные записи и заполняет их в первичных моделях. |
||
| 198 | * @param string $name - имя релейшена |
||
| 199 | * @param array $primaryModels - первичные модели |
||
| 200 | * @return Collection|BaseBitrixModel[] - найденные модели |
||
| 201 | */ |
||
| 202 | public function populateRelation($name, &$primaryModels) |
||
| 232 | |||
| 233 | /** |
||
| 234 | * Сгруппировать найденные модели |
||
| 235 | * @param array $models |
||
| 236 | * @param array|string $linkKeys |
||
| 237 | * @param bool $checkMultiple |
||
| 238 | * @return array |
||
| 239 | */ |
||
| 240 | private function buildBuckets($models, $linkKeys, $checkMultiple = true) |
||
| 257 | |||
| 258 | /** |
||
| 259 | * Получить значение атрибутов в виде строки |
||
| 260 | * @param BaseBitrixModel $model |
||
| 261 | * @param array $attributes |
||
| 262 | * @return string |
||
| 263 | */ |
||
| 264 | private function getModelKey($model, $attributes) |
||
| 276 | |||
| 277 | /** |
||
| 278 | * @param mixed $value raw key value. |
||
| 279 | * @return string normalized key value. |
||
| 280 | */ |
||
| 281 | private function normalizeModelKey($value) |
||
| 290 | |||
| 291 | /** |
||
| 292 | * Добавляет основную модель запроса в релейшен |
||
| 293 | * @param Collection|BaseBitrixModel[] $result |
||
| 294 | */ |
||
| 295 | private function addInverseRelations(&$result) |
||
| 308 | /** |
||
| 309 | * @param Collection|BaseBitrixModel[] $primaryModels primary models |
||
| 310 | * @param Collection|BaseBitrixModel[] $models models |
||
| 311 | * @param string $primaryName the primary relation name |
||
| 312 | * @param string $name the relation name |
||
| 313 | */ |
||
| 314 | private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name) |
||
| 345 | } |
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
Idableprovides a methodequalsIdthat 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.