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 | /** |
||
| 41 | * Найти связанные записи для определенной модели [[$this->primaryModel]] |
||
| 42 | * Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation |
||
| 43 | * @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели |
||
| 44 | * @throws \Exception |
||
| 45 | */ |
||
| 46 | public function findFor() |
||
| 47 | { |
||
| 48 | return $this->multiple ? $this->getList() : $this->first(); |
||
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Определяет связи, которые должны быть загружены при выполнении запроса |
||
| 53 | * |
||
| 54 | * Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса |
||
| 55 | * |
||
| 56 | * @param array|string $with - связи, которые необходимо жадно подгрузить |
||
| 57 | * // Загрузить Customer и сразу для каждой модели подгрузить orders и country |
||
| 58 | * Customer::query()->with(['orders', 'country'])->getList(); |
||
| 59 | * |
||
| 60 | * // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address |
||
| 61 | * Customer::find()->with('orders.address')->getList(); |
||
| 62 | * |
||
| 63 | * // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные) |
||
| 64 | * Customer::find()->with([ |
||
| 65 | * 'orders' => function (BaseQuery $query) { |
||
| 66 | * $query->filter(['ACTIVE' => 'Y']); |
||
| 67 | * }, |
||
| 68 | * 'country', |
||
| 69 | * ])->all(); |
||
| 70 | * |
||
| 71 | * @return $this |
||
| 72 | */ |
||
| 73 | public function with($with) |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Добавить фильтр для загрзуки связи относительно моделей |
||
| 94 | * @param Collection|BaseBitrixModel[] $models |
||
| 95 | */ |
||
| 96 | protected function filterByModels($models) |
||
| 121 | |||
| 122 | /** |
||
| 123 | * Подгрузить связанные модели для уже загруденных моделей |
||
| 124 | * @param array $with - массив релейшенов, которые необходимо подгрузить |
||
| 125 | * @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи |
||
| 126 | */ |
||
| 127 | public function findWith($with, &$models) |
||
| 141 | |||
| 142 | /** |
||
| 143 | * @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы |
||
| 144 | * @param array $with |
||
| 145 | * @return BaseQuery[] |
||
| 146 | */ |
||
| 147 | private function normalizeRelations($model, $with) |
||
| 180 | /** |
||
| 181 | * Находит связанные записи и заполняет их в первичных моделях. |
||
| 182 | * @param string $name - имя релейшена |
||
| 183 | * @param array $primaryModels - первичные модели |
||
| 184 | * @return Collection|BaseBitrixModel[] - найденные модели |
||
| 185 | */ |
||
| 186 | public function populateRelation($name, &$primaryModels) |
||
| 212 | |||
| 213 | /** |
||
| 214 | * Сгруппировать найденные модели |
||
| 215 | * @param array $models |
||
| 216 | * @param array|string $linkKeys |
||
| 217 | * @param bool $checkMultiple |
||
| 218 | * @return array |
||
| 219 | */ |
||
| 220 | private function buildBuckets($models, $linkKeys, $checkMultiple = true) |
||
| 221 | { |
||
| 222 | $buckets = []; |
||
| 223 | |||
| 224 | foreach ($models as $model) { |
||
| 225 | $key = $this->getModelKey($model, $linkKeys); |
||
| 226 | $buckets[$key][] = $model; |
||
| 227 | } |
||
| 228 | |||
| 229 | if ($checkMultiple && !$this->multiple) { |
||
| 230 | foreach ($buckets as $i => $bucket) { |
||
| 231 | $buckets[$i] = reset($bucket); |
||
| 232 | } |
||
| 233 | } |
||
| 234 | |||
| 235 | return $buckets; |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * Получить значение атрибутов в виде строки |
||
| 240 | * @param BaseBitrixModel $model |
||
| 241 | * @param array|string $attributes |
||
| 242 | * @return string |
||
| 243 | */ |
||
| 244 | private function getModelKey($model, $attributes) |
||
| 256 | |||
| 257 | /** |
||
| 258 | * @param mixed $value raw key value. |
||
| 259 | * @return string normalized key value. |
||
| 260 | */ |
||
| 261 | private function normalizeModelKey($value) |
||
| 270 | } |
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.