| Total Complexity | 146 |
| Total Lines | 677 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| 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 |
||
| 47 | abstract class ModelsBase extends Model |
||
| 48 | { |
||
| 49 | |||
| 50 | public function initialize(): void |
||
| 51 | { |
||
| 52 | self::setup(['orm.events' => true]); |
||
| 53 | $this->keepSnapshots(true); |
||
| 54 | |||
| 55 | // Пройдемся по модулям и подключим их отношения к текущей модели, если они описаны |
||
| 56 | $cacheKey = explode('\\', static::class)[3]; |
||
| 57 | $modulesDir = $this->di->getShared('config')->core->modulesDir; |
||
| 58 | $parameters = [ |
||
| 59 | 'conditions' => 'disabled=0', |
||
| 60 | 'cache' => [ |
||
| 61 | 'key' => $cacheKey, |
||
| 62 | 'lifetime' => 5, //seconds |
||
| 63 | ], |
||
| 64 | ]; |
||
| 65 | $modules = PbxExtensionModules::find($parameters)->toArray(); |
||
| 66 | foreach ($modules as $module) { |
||
| 67 | $moduleModelsDir = "{$modulesDir}/{$module['uniqid']}/Models"; |
||
| 68 | $results = glob($moduleModelsDir . '/*.php', GLOB_NOSORT); |
||
| 69 | foreach ($results as $file) { |
||
| 70 | $className = pathinfo($file)['filename']; |
||
| 71 | $moduleModelClass = "\\Modules\\{$module['uniqid']}\\Models\\{$className}"; |
||
| 72 | if (class_exists($moduleModelClass) && method_exists($moduleModelClass, 'getDynamicRelations')) { |
||
| 73 | $moduleModelClass::getDynamicRelations($this); |
||
| 74 | } |
||
| 75 | } |
||
| 76 | } |
||
| 77 | } |
||
| 78 | |||
| 79 | /** |
||
| 80 | * Обработчик ошибок валидации, обычно сюда попадаем если неправильно |
||
| 81 | * сохраняются или удаляютмя модели или неправильно настроены зависимости между ними. |
||
| 82 | * Эта функция формирует список ссылок на объект который мы пытаемся удалить |
||
| 83 | * |
||
| 84 | * При описании отношений необходимо в foreignKey секцию добавлять атрибут |
||
| 85 | * message в котором указывать алиас посе слова Models, |
||
| 86 | * например Models\IvrMenuTimeout, иначе метод getRelated не сможет найти зависимые |
||
| 87 | * записи в моделях |
||
| 88 | */ |
||
| 89 | public function onValidationFails(): void |
||
| 90 | { |
||
| 91 | $errorMessages = $this->getMessages(); |
||
| 92 | if (php_sapi_name() === 'cli') { |
||
| 93 | Util::sysLogMsg(__CLASS__, implode(' ', $errorMessages)); |
||
| 94 | |||
| 95 | return; |
||
| 96 | } |
||
| 97 | foreach ($errorMessages as $errorMessage) { |
||
| 98 | if ($errorMessage->getType() === 'ConstraintViolation') { |
||
| 99 | $arrMessageParts = explode('Common\\Models\\', $errorMessage->getMessage()); |
||
| 100 | if (count($arrMessageParts) === 2) { |
||
| 101 | $relatedModel = $arrMessageParts[1]; |
||
| 102 | } else { |
||
| 103 | $relatedModel = $errorMessage->getMessage(); |
||
| 104 | } |
||
| 105 | $relatedRecords = $this->getRelated($relatedModel); |
||
| 106 | $newErrorMessage = $this->t('ConstraintViolation'); |
||
| 107 | $newErrorMessage .= "<ul class='list'>"; |
||
| 108 | if ($relatedRecords === false) { |
||
| 109 | throw new Model\Exception('Error on models relationship ' . $errorMessage); |
||
| 110 | } |
||
| 111 | if ($relatedRecords instanceof Resultset) { |
||
| 112 | foreach ($relatedRecords as $item) { |
||
| 113 | $newErrorMessage .= '<li>' . $item->getRepresent(true) . '</li>'; |
||
|
|
|||
| 114 | } |
||
| 115 | } else { |
||
| 116 | $newErrorMessage .= '<li>Unknown object</li>'; |
||
| 117 | } |
||
| 118 | $newErrorMessage .= '</ul>'; |
||
| 119 | $errorMessage->setMessage($newErrorMessage); |
||
| 120 | break; |
||
| 121 | } |
||
| 122 | } |
||
| 123 | } |
||
| 124 | |||
| 125 | /** |
||
| 126 | * Функция для доступа к массиву переводов из моделей, используется для |
||
| 127 | * сообщений на понятном пользователю языке |
||
| 128 | * |
||
| 129 | * @param $message |
||
| 130 | * @param array $parameters |
||
| 131 | * |
||
| 132 | * @return mixed |
||
| 133 | */ |
||
| 134 | public function t($message, $parameters = []) |
||
| 135 | { |
||
| 136 | return $this->getDI()->getShared('translation')->t($message, $parameters); |
||
| 137 | } |
||
| 138 | |||
| 139 | /** |
||
| 140 | * Fill default values from annotations |
||
| 141 | */ |
||
| 142 | public function beforeValidationOnCreate(): void |
||
| 143 | { |
||
| 144 | $metaData = $metaData = $this->di->get('modelsMetadata'); |
||
| 145 | $defaultValues = $metaData->getDefaultValues($this); |
||
| 146 | foreach ($defaultValues as $field => $value) { |
||
| 147 | if ( ! isset($this->{$field}) || $this->{$field} === null) { |
||
| 148 | $this->{$field} = new RawValue($value); |
||
| 149 | } |
||
| 150 | } |
||
| 151 | } |
||
| 152 | |||
| 153 | /** |
||
| 154 | * Функция позволяет вывести список зависимостей с сылками, |
||
| 155 | * которые мешают удалению текущей сущности |
||
| 156 | * |
||
| 157 | * @return bool |
||
| 158 | */ |
||
| 159 | public function beforeDelete(): bool |
||
| 160 | { |
||
| 161 | return $this->checkRelationsSatisfaction($this, $this); |
||
| 162 | } |
||
| 163 | |||
| 164 | /** |
||
| 165 | * Check whether this object has unsatisfied relations or not |
||
| 166 | * |
||
| 167 | * @param $theFirstDeleteRecord |
||
| 168 | * @param $currentDeleteRecord |
||
| 169 | * |
||
| 170 | * @return bool |
||
| 171 | */ |
||
| 172 | private function checkRelationsSatisfaction($theFirstDeleteRecord, $currentDeleteRecord): bool |
||
| 173 | { |
||
| 174 | $result = true; |
||
| 175 | $relations |
||
| 176 | = $currentDeleteRecord->_modelsManager->getRelations(get_class($currentDeleteRecord)); |
||
| 177 | foreach ($relations as $relation) { |
||
| 178 | $foreignKey = $relation->getOption('foreignKey'); |
||
| 179 | if ( ! array_key_exists('action', $foreignKey)) { |
||
| 180 | continue; |
||
| 181 | } |
||
| 182 | // Check if there are some record which restrict delete current record |
||
| 183 | $relatedModel = $relation->getReferencedModel(); |
||
| 184 | $mappedFields = $relation->getFields(); |
||
| 185 | $mappedFields = is_array($mappedFields) |
||
| 186 | ? $mappedFields : [$mappedFields]; |
||
| 187 | $referencedFields = $relation->getReferencedFields(); |
||
| 188 | $referencedFields = is_array($referencedFields) |
||
| 189 | ? $referencedFields : [$referencedFields]; |
||
| 190 | $parameters['conditions'] = ''; |
||
| 191 | $parameters['bind'] = []; |
||
| 192 | foreach ($referencedFields as $index => $referencedField) { |
||
| 193 | $parameters['conditions'] .= $index > 0 |
||
| 194 | ? ' OR ' : ''; |
||
| 195 | $parameters['conditions'] .= $referencedField |
||
| 196 | . '= :field' |
||
| 197 | . $index . ':'; |
||
| 198 | $bindField |
||
| 199 | = $mappedFields[$index]; |
||
| 200 | $parameters['bind']['field' . $index] = $currentDeleteRecord->$bindField; |
||
| 201 | } |
||
| 202 | $relatedRecords = $relatedModel::find($parameters); |
||
| 203 | switch ($foreignKey['action']) { |
||
| 204 | case Relation::ACTION_RESTRICT: // Restrict deletion and add message about unsatisfied undeleted links |
||
| 205 | foreach ($relatedRecords as $relatedRecord) { |
||
| 206 | if (serialize($relatedRecord) === serialize($theFirstDeleteRecord)) { |
||
| 207 | continue; // It is checked object |
||
| 208 | } |
||
| 209 | $message = new Message( |
||
| 210 | $theFirstDeleteRecord->t( |
||
| 211 | 'mo_BeforeDeleteFirst', |
||
| 212 | [ |
||
| 213 | 'represent' => $relatedRecord->getRepresent(true), |
||
| 214 | ] |
||
| 215 | ) |
||
| 216 | ); |
||
| 217 | $theFirstDeleteRecord->appendMessage($message); |
||
| 218 | $result = false; |
||
| 219 | } |
||
| 220 | break; |
||
| 221 | case Relation::ACTION_CASCADE: // Удалим все зависимые записи |
||
| 222 | foreach ($relatedRecords as $record) { |
||
| 223 | $result = $result && $record->checkRelationsSatisfaction($theFirstDeleteRecord, $record); |
||
| 224 | if ($result) { |
||
| 225 | $result = $record->delete(); |
||
| 226 | } |
||
| 227 | } |
||
| 228 | break; |
||
| 229 | case Relation::NO_ACTION: // Clear all refs |
||
| 230 | break; |
||
| 231 | default: |
||
| 232 | break; |
||
| 233 | } |
||
| 234 | } |
||
| 235 | |||
| 236 | return $result; |
||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * После сохранения данных любой модели |
||
| 241 | */ |
||
| 242 | public function afterSave(): void |
||
| 246 | } |
||
| 247 | |||
| 248 | /** |
||
| 249 | * Готовит массив действий для перезапуска модулей ядра системы |
||
| 250 | * и Asterisk |
||
| 251 | * |
||
| 252 | * @param $action string быть afterSave или afterDelete |
||
| 253 | */ |
||
| 254 | private function processSettingsChanges(string $action): void |
||
| 284 | } |
||
| 285 | } |
||
| 286 | |||
| 287 | /** |
||
| 288 | * Очистка кешей при сохранении данных в базу |
||
| 289 | * |
||
| 290 | * @param $calledClass string модель, с чей кеш будем чистить в полном формате |
||
| 291 | */ |
||
| 292 | public function clearCache(string $calledClass): void |
||
| 293 | { |
||
| 294 | if ($this->di->has('managedCache')) { |
||
| 295 | $managedCache = $this->di->getShared('managedCache'); |
||
| 296 | $category = explode('\\', $calledClass)[3]; |
||
| 297 | $keys = $managedCache->getAdapter()->getKeys($category); |
||
| 298 | if (count($keys) > 0) { |
||
| 299 | $managedCache->deleteMultiple($keys); |
||
| 300 | } |
||
| 301 | } |
||
| 302 | if ($this->di->has('modelsCache')) { |
||
| 303 | $modelsCache = $this->di->getShared('modelsCache'); |
||
| 304 | $category = explode('\\', $calledClass)[3]; |
||
| 305 | $keys = $modelsCache->getAdapter()->getKeys($category); |
||
| 306 | if (count($keys) > 0) { |
||
| 307 | $modelsCache->deleteMultiple($keys); |
||
| 308 | } |
||
| 309 | } |
||
| 310 | } |
||
| 311 | |||
| 312 | /** |
||
| 313 | * После удаления данных любой модели |
||
| 314 | */ |
||
| 315 | public function afterDelete(): void |
||
| 319 | } |
||
| 320 | |||
| 321 | /** |
||
| 322 | * Возвращает предстваление элемента базы данных |
||
| 323 | * для сообщения об ошибках с ссылкой на элемент или для выбора в списках |
||
| 324 | * строкой |
||
| 325 | * |
||
| 326 | * @param bool $needLink - предстваление с ссылкой |
||
| 327 | * |
||
| 328 | * @return string |
||
| 329 | */ |
||
| 330 | public function getRepresent($needLink = false): string |
||
| 568 | } |
||
| 569 | |||
| 570 | /** |
||
| 571 | * Укорачивает длинные имена |
||
| 572 | * |
||
| 573 | * @param $s |
||
| 574 | * |
||
| 575 | * @return string |
||
| 576 | */ |
||
| 577 | private function trimName($s): string |
||
| 578 | { |
||
| 579 | $max_length = 64; |
||
| 580 | |||
| 581 | if (strlen($s) > $max_length) { |
||
| 582 | $offset = ($max_length - 3) - strlen($s); |
||
| 583 | $s = substr($s, 0, strrpos($s, ' ', $offset)) . '...'; |
||
| 584 | } |
||
| 585 | |||
| 586 | return $s; |
||
| 587 | } |
||
| 588 | |||
| 589 | /** |
||
| 590 | * Return link on database record in web interface |
||
| 591 | * |
||
| 592 | * @return string |
||
| 593 | */ |
||
| 594 | public function getWebInterfaceLink(): string |
||
| 712 | } |
||
| 713 | |||
| 714 | /** |
||
| 715 | * Returns Identity field name for current model |
||
| 716 | * |
||
| 717 | * @return string |
||
| 718 | */ |
||
| 719 | public function getIdentityFieldName(): string |
||
| 724 | } |
||
| 725 | } |
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.