| Total Complexity | 136 |
| Total Lines | 646 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like ModelsBase 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.
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 ModelsBase, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 46 | abstract class ModelsBase extends Model |
||
| 47 | { |
||
| 48 | |||
| 49 | public function initialize(): void |
||
| 50 | { |
||
| 51 | self::setup(['orm.events' => true]); |
||
| 52 | $this->keepSnapshots(true); |
||
| 53 | |||
| 54 | // Пройдемся по модулям и подключим их отношения к текущей модели, если они описаны |
||
| 55 | $cacheKey = explode('\\', static::class)[3]; |
||
| 56 | $modulesDir = $this->di->getShared('config')->core->modulesDir; |
||
| 57 | $parameters = [ |
||
| 58 | 'conditions' => 'disabled=0', |
||
| 59 | 'cache' => [ |
||
| 60 | 'key' => $cacheKey, |
||
| 61 | 'lifetime' => 5, //seconds |
||
| 62 | ], |
||
| 63 | ]; |
||
| 64 | $modules = PbxExtensionModules::find($parameters)->toArray(); |
||
| 65 | foreach ($modules as $module) { |
||
| 66 | $moduleModelsDir = "{$modulesDir}/{$module['uniqid']}/Models"; |
||
| 67 | $results = glob($moduleModelsDir . '/*.php', GLOB_NOSORT); |
||
| 68 | foreach ($results as $file) { |
||
| 69 | $className = pathinfo($file)['filename']; |
||
| 70 | $moduleModelClass = "\\Modules\\{$module['uniqid']}\\Models\\{$className}"; |
||
| 71 | if (class_exists($moduleModelClass) && method_exists($moduleModelClass, 'getDynamicRelations')) { |
||
| 72 | $moduleModelClass::getDynamicRelations($this); |
||
| 73 | } |
||
| 74 | } |
||
| 75 | } |
||
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * Обработчик ошибок валидации, обычно сюда попадаем если неправильно |
||
| 80 | * сохраняются или удаляютмя модели или неправильно настроены зависимости между ними. |
||
| 81 | * Эта функция формирует список ссылок на объект который мы пытаемся удалить |
||
| 82 | * |
||
| 83 | * При описании отношений необходимо в foreignKey секцию добавлять атрибут |
||
| 84 | * message в котором указывать алиас посе слова Models, |
||
| 85 | * например Models\IvrMenuTimeout, иначе метод getRelated не сможет найти зависимые |
||
| 86 | * записи в моделях |
||
| 87 | */ |
||
| 88 | public function onValidationFails(): void |
||
| 89 | { |
||
| 90 | $errorMessages = $this->getMessages(); |
||
| 91 | if (php_sapi_name() === 'cli') { |
||
| 92 | Util::sysLogMsg(__CLASS__, implode(' ', $errorMessages)); |
||
| 93 | |||
| 94 | return; |
||
| 95 | } |
||
| 96 | foreach ($errorMessages as $errorMessage) { |
||
| 97 | if ($errorMessage->getType() === 'ConstraintViolation') { |
||
| 98 | $arrMessageParts = explode('Common\\Models\\', $errorMessage->getMessage()); |
||
| 99 | if (count($arrMessageParts) === 2) { |
||
| 100 | $relatedModel = $arrMessageParts[1]; |
||
| 101 | } else { |
||
| 102 | $relatedModel = $errorMessage->getMessage(); |
||
| 103 | } |
||
| 104 | $relatedRecords = $this->getRelated($relatedModel); |
||
| 105 | $newErrorMessage = $this->t('ConstraintViolation'); |
||
| 106 | $newErrorMessage .= "<ul class='list'>"; |
||
| 107 | if ($relatedRecords === false) { |
||
| 108 | throw new Model\Exception('Error on models relationship ' . $errorMessage); |
||
| 109 | } |
||
| 110 | if ($relatedRecords instanceof Resultset) { |
||
| 111 | foreach ($relatedRecords as $item) { |
||
| 112 | $newErrorMessage .= '<li>' . $item->getRepresent(true) . '</li>'; |
||
|
|
|||
| 113 | } |
||
| 114 | } else { |
||
| 115 | $newErrorMessage .= '<li>Unknown object</li>'; |
||
| 116 | } |
||
| 117 | $newErrorMessage .= '</ul>'; |
||
| 118 | $errorMessage->setMessage($newErrorMessage); |
||
| 119 | break; |
||
| 120 | } |
||
| 121 | } |
||
| 122 | } |
||
| 123 | |||
| 124 | /** |
||
| 125 | * Функция для доступа к массиву переводов из моделей, используется для |
||
| 126 | * сообщений на понятном пользователю языке |
||
| 127 | * |
||
| 128 | * @param $message |
||
| 129 | * @param array $parameters |
||
| 130 | * |
||
| 131 | * @return mixed |
||
| 132 | */ |
||
| 133 | public function t($message, $parameters = []) |
||
| 136 | } |
||
| 137 | |||
| 138 | /** |
||
| 139 | * Fill default values from annotations |
||
| 140 | */ |
||
| 141 | public function beforeValidationOnCreate(): void |
||
| 148 | } |
||
| 149 | } |
||
| 150 | } |
||
| 151 | |||
| 152 | /** |
||
| 153 | * Функция позволяет вывести список зависимостей с сылками, |
||
| 154 | * которые мешают удалению текущей сущности |
||
| 155 | * |
||
| 156 | * @return bool |
||
| 157 | */ |
||
| 158 | public function beforeDelete(): bool |
||
| 161 | } |
||
| 162 | |||
| 163 | /** |
||
| 164 | * Check whether this object has unsatisfied relations or not |
||
| 165 | * |
||
| 166 | * @param $theFirstDeleteRecord |
||
| 167 | * @param $currentDeleteRecord |
||
| 168 | * |
||
| 169 | * @return bool |
||
| 170 | */ |
||
| 171 | private function checkRelationsSatisfaction($theFirstDeleteRecord, $currentDeleteRecord): bool |
||
| 172 | { |
||
| 173 | $result = true; |
||
| 174 | $relations |
||
| 175 | = $currentDeleteRecord->_modelsManager->getRelations(get_class($currentDeleteRecord)); |
||
| 176 | foreach ($relations as $relation) { |
||
| 177 | $foreignKey = $relation->getOption('foreignKey'); |
||
| 178 | if ( ! array_key_exists('action', $foreignKey)) { |
||
| 179 | continue; |
||
| 180 | } |
||
| 181 | // Check if there are some record which restrict delete current record |
||
| 182 | $relatedModel = $relation->getReferencedModel(); |
||
| 183 | $mappedFields = $relation->getFields(); |
||
| 184 | $mappedFields = is_array($mappedFields) |
||
| 185 | ? $mappedFields : [$mappedFields]; |
||
| 186 | $referencedFields = $relation->getReferencedFields(); |
||
| 187 | $referencedFields = is_array($referencedFields) |
||
| 188 | ? $referencedFields : [$referencedFields]; |
||
| 189 | $parameters['conditions'] = ''; |
||
| 190 | $parameters['bind'] = []; |
||
| 191 | foreach ($referencedFields as $index => $referencedField) { |
||
| 192 | $parameters['conditions'] .= $index > 0 |
||
| 193 | ? ' OR ' : ''; |
||
| 194 | $parameters['conditions'] .= $referencedField |
||
| 195 | . '= :field' |
||
| 196 | . $index . ':'; |
||
| 197 | $bindField |
||
| 198 | = $mappedFields[$index]; |
||
| 199 | $parameters['bind']['field' . $index] = $currentDeleteRecord->$bindField; |
||
| 200 | } |
||
| 201 | $relatedRecords = $relatedModel::find($parameters); |
||
| 202 | switch ($foreignKey['action']) { |
||
| 203 | case Relation::ACTION_RESTRICT: // Restrict deletion and add message about unsatisfied undeleted links |
||
| 204 | foreach ($relatedRecords as $relatedRecord) { |
||
| 205 | if (serialize($relatedRecord) === serialize($theFirstDeleteRecord)) { |
||
| 206 | continue; // It is checked object |
||
| 207 | } |
||
| 208 | $message = new Message( |
||
| 209 | $theFirstDeleteRecord->t( |
||
| 210 | 'mo_BeforeDeleteFirst', |
||
| 211 | [ |
||
| 212 | 'represent' => $relatedRecord->getRepresent(true), |
||
| 213 | ] |
||
| 214 | ) |
||
| 215 | ); |
||
| 216 | $theFirstDeleteRecord->appendMessage($message); |
||
| 217 | $result = false; |
||
| 218 | } |
||
| 219 | break; |
||
| 220 | case Relation::ACTION_CASCADE: // Удалим все зависимые записи |
||
| 221 | foreach ($relatedRecords as $record) { |
||
| 222 | $result = $result && $record->checkRelationsSatisfaction($theFirstDeleteRecord, $record); |
||
| 223 | if ($result) { |
||
| 224 | $result = $record->delete(); |
||
| 225 | } |
||
| 226 | } |
||
| 227 | break; |
||
| 228 | case Relation::NO_ACTION: // Clear all refs |
||
| 229 | break; |
||
| 230 | default: |
||
| 231 | break; |
||
| 232 | } |
||
| 233 | } |
||
| 234 | |||
| 235 | return $result; |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * После сохранения данных любой модели |
||
| 240 | */ |
||
| 241 | public function afterSave(): void |
||
| 245 | } |
||
| 246 | |||
| 247 | /** |
||
| 248 | * Готовит массив действий для перезапуска модулей ядра системы |
||
| 249 | * и Asterisk |
||
| 250 | * |
||
| 251 | * @param $action string быть afterSave или afterDelete |
||
| 252 | */ |
||
| 253 | private function processSettingsChanges(string $action): void |
||
| 283 | } |
||
| 284 | } |
||
| 285 | |||
| 286 | /** |
||
| 287 | * Очистка кешей при сохранении данных в базу |
||
| 288 | * |
||
| 289 | * @param $calledClass string модель, с чей кеш будем чистить в полном формате |
||
| 290 | */ |
||
| 291 | public function clearCache(string $calledClass): void |
||
| 292 | { |
||
| 293 | if ($this->di->has('managedCache')) { |
||
| 294 | $managedCache = $this->di->getShared('managedCache'); |
||
| 295 | $category = explode('\\', $calledClass)[3]; |
||
| 296 | $keys = $managedCache->getAdapter()->getKeys($category); |
||
| 297 | if (count($keys) > 0) { |
||
| 298 | $managedCache->deleteMultiple($keys); |
||
| 299 | } |
||
| 300 | } |
||
| 301 | if ($this->di->has('modelsCache')) { |
||
| 302 | $modelsCache = $this->di->getShared('modelsCache'); |
||
| 303 | $category = explode('\\', $calledClass)[3]; |
||
| 304 | $keys = $modelsCache->getAdapter()->getKeys($category); |
||
| 305 | if (count($keys) > 0) { |
||
| 306 | $modelsCache->deleteMultiple($keys); |
||
| 307 | } |
||
| 308 | } |
||
| 309 | } |
||
| 310 | |||
| 311 | /** |
||
| 312 | * После удаления данных любой модели |
||
| 313 | */ |
||
| 314 | public function afterDelete(): void |
||
| 318 | } |
||
| 319 | |||
| 320 | /** |
||
| 321 | * Возвращает предстваление элемента базы данных |
||
| 322 | * для сообщения об ошибках с ссылкой на элемент или для выбора в списках |
||
| 323 | * строкой |
||
| 324 | * |
||
| 325 | * @param bool $needLink - предстваление с ссылкой |
||
| 326 | * |
||
| 327 | * @return string |
||
| 328 | */ |
||
| 329 | public function getRepresent($needLink = false): string |
||
| 528 | } |
||
| 529 | |||
| 530 | /** |
||
| 531 | * Укорачивает длинные имена |
||
| 532 | * |
||
| 533 | * @param $s |
||
| 534 | * |
||
| 535 | * @return string |
||
| 536 | */ |
||
| 537 | private function trimName($s): string |
||
| 547 | } |
||
| 548 | |||
| 549 | /** |
||
| 550 | * Return link on database record in web interface |
||
| 551 | * |
||
| 552 | * @return string |
||
| 553 | */ |
||
| 554 | public function getWebInterfaceLink(): string |
||
| 672 | } |
||
| 673 | |||
| 674 | /** |
||
| 675 | * Возвращает массив полей, по которым следует добавить индекс в DB. |
||
| 676 | * |
||
| 677 | * @return array |
||
| 678 | */ |
||
| 679 | public function getIndexColumn(): array |
||
| 680 | { |
||
| 681 | return []; |
||
| 682 | } |
||
| 683 | |||
| 684 | /** |
||
| 685 | * Returns Identity field name for current model |
||
| 686 | * @return string |
||
| 687 | */ |
||
| 688 | public function getIdentityFieldName():string |
||
| 692 | } |
||
| 693 | } |
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.