| Total Complexity | 58 |
| Total Lines | 536 |
| Duplicated Lines | 0 % |
| Changes | 12 | ||
| Bugs | 0 | Features | 0 |
Complex classes like ReasonsService 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 ReasonsService, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 47 | class ReasonsService extends Component |
||
| 48 | { |
||
| 49 | |||
| 50 | /** @var int */ |
||
| 51 | const CACHE_TTL = 1800; |
||
| 52 | |||
| 53 | /** @var FieldInterface[] */ |
||
| 54 | protected $allFields; |
||
| 55 | |||
| 56 | /** @var FieldInterface[] */ |
||
| 57 | protected $toggleFields; |
||
| 58 | |||
| 59 | /** @var array */ |
||
| 60 | protected $sources; |
||
| 61 | |||
| 62 | /** @var int[] */ |
||
| 63 | protected $fieldIdsByUid; |
||
| 64 | |||
| 65 | /** @var string[] */ |
||
| 66 | protected $fieldUidsById; |
||
| 67 | |||
| 68 | // Public Methods |
||
| 69 | // ========================================================================= |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Saves a field layout's conditionals, via the Project Config |
||
| 73 | * |
||
| 74 | * @param FieldLayout $layout |
||
| 75 | * @param string|array $conditionals |
||
| 76 | * @return bool |
||
| 77 | * @throws \yii\base\ErrorException |
||
| 78 | * @throws \yii\base\Exception |
||
| 79 | * @throws \yii\base\NotSupportedException |
||
| 80 | * @throws \yii\web\ServerErrorHttpException |
||
| 81 | */ |
||
| 82 | public function saveFieldLayoutConditionals(FieldLayout $layout, $conditionals): bool |
||
| 83 | { |
||
| 84 | |||
| 85 | $uid = (new Query()) |
||
| 86 | ->select(['uid']) |
||
| 87 | ->from('{{%reasons}}') |
||
| 88 | ->where(['fieldLayoutId' => $layout->id]) |
||
| 89 | ->scalar(); |
||
| 90 | |||
| 91 | $isNew = !$uid; |
||
| 92 | if ($isNew) { |
||
| 93 | $uid = StringHelper::UUID(); |
||
| 94 | } |
||
| 95 | |||
| 96 | $conditionals = $this->prepConditionalsForProjectConfig($conditionals); |
||
| 97 | |||
| 98 | // Save it to the project config |
||
| 99 | $path = "reasons_conditionals.{$uid}"; |
||
| 100 | Craft::$app->getProjectConfig()->set($path, [ |
||
| 101 | 'fieldLayoutUid' => $layout->uid, |
||
| 102 | 'conditionals' => $conditionals, |
||
| 103 | ]); |
||
| 104 | |||
| 105 | return true; |
||
| 106 | } |
||
| 107 | |||
| 108 | /** |
||
| 109 | * Deletes a field layout's conditionals, via the Project Config |
||
| 110 | * |
||
| 111 | * @param FieldLayout $layout |
||
| 112 | * @return bool |
||
| 113 | */ |
||
| 114 | public function deleteFieldLayoutConditionals(FieldLayout $layout): bool |
||
| 115 | { |
||
| 116 | |||
| 117 | $uid = (new Query()) |
||
| 118 | ->select(['uid']) |
||
| 119 | ->from('{{%reasons}}') |
||
| 120 | ->where(['fieldLayoutId' => $layout->id]) |
||
| 121 | ->scalar(); |
||
| 122 | |||
| 123 | if (!$uid) { |
||
| 124 | return false; |
||
| 125 | } |
||
| 126 | |||
| 127 | // Remove it from the project config |
||
| 128 | $path = "reasons_conditionals.{$uid}"; |
||
| 129 | Craft::$app->getProjectConfig()->remove($path); |
||
| 130 | |||
| 131 | return true; |
||
| 132 | } |
||
| 133 | |||
| 134 | /** |
||
| 135 | * @param ConfigEvent $event |
||
| 136 | * @return void |
||
| 137 | * @throws \Throwable |
||
| 138 | * @throws \yii\db\Exception |
||
| 139 | */ |
||
| 140 | public function onProjectConfigChange(ConfigEvent $event) |
||
| 141 | { |
||
| 142 | |||
| 143 | $this->clearCache(); |
||
| 144 | |||
| 145 | $uid = $event->tokenMatches[0]; |
||
| 146 | $data = $event->newValue; |
||
| 147 | |||
| 148 | $id = (new Query()) |
||
| 149 | ->select(['id']) |
||
| 150 | ->from('{{%reasons}}') |
||
| 151 | ->where(['uid' => $uid]) |
||
| 152 | ->scalar(); |
||
| 153 | |||
| 154 | $isNew = empty($id); |
||
| 155 | |||
| 156 | if ($isNew) { |
||
| 157 | |||
| 158 | // Save new conditionals |
||
| 159 | $fieldLayoutId = Db::idByUid(Table::FIELDLAYOUTS, $data['fieldLayoutUid']); |
||
| 160 | |||
| 161 | if ($fieldLayoutId === null) { |
||
| 162 | // The field layout might not've synced yet. Defer to Project Config |
||
| 163 | Craft::$app->getProjectConfig()->defer($event, [$this, __FUNCTION__]); |
||
| 164 | return; |
||
| 165 | } |
||
| 166 | |||
| 167 | $transaction = Craft::$app->getDb()->beginTransaction(); |
||
| 168 | |||
| 169 | try { |
||
| 170 | Craft::$app->db->createCommand() |
||
| 171 | ->insert('{{%reasons}}', [ |
||
| 172 | 'fieldLayoutId' => $fieldLayoutId, |
||
| 173 | 'conditionals' => $data['conditionals'], |
||
| 174 | 'uid' => $uid, |
||
| 175 | ]) |
||
| 176 | ->execute(); |
||
| 177 | $transaction->commit(); |
||
| 178 | } catch (\Throwable $e) { |
||
| 179 | $transaction->rollBack(); |
||
| 180 | throw $e; |
||
| 181 | } |
||
| 182 | |||
| 183 | } else { |
||
| 184 | |||
| 185 | // Update existing conditionals |
||
| 186 | $transaction = Craft::$app->getDb()->beginTransaction(); |
||
| 187 | |||
| 188 | try { |
||
| 189 | Craft::$app->db->createCommand() |
||
| 190 | ->update('{{%reasons}}', [ |
||
| 191 | 'conditionals' => $data['conditionals'], |
||
| 192 | ], ['id' => $id]) |
||
| 193 | ->execute(); |
||
| 194 | $transaction->commit(); |
||
| 195 | } catch (\Throwable $e) { |
||
| 196 | $transaction->rollBack(); |
||
| 197 | throw $e; |
||
| 198 | } |
||
| 199 | } |
||
| 200 | |||
| 201 | } |
||
| 202 | |||
| 203 | /** |
||
| 204 | * @param ConfigEvent $event |
||
| 205 | * @return void |
||
| 206 | * @throws \Throwable |
||
| 207 | * @throws \yii\db\Exception |
||
| 208 | */ |
||
| 209 | public function onProjectConfigDelete(ConfigEvent $event) |
||
| 210 | { |
||
| 211 | |||
| 212 | $this->clearCache(); |
||
| 213 | |||
| 214 | $uid = $event->tokenMatches[0]; |
||
| 215 | |||
| 216 | $id = (new Query()) |
||
| 217 | ->select(['id']) |
||
| 218 | ->from('{{%reasons}}') |
||
| 219 | ->where(['uid' => $uid]) |
||
| 220 | ->scalar(); |
||
| 221 | |||
| 222 | if ($id) { |
||
| 223 | |||
| 224 | $transaction = Craft::$app->getDb()->beginTransaction(); |
||
| 225 | |||
| 226 | try { |
||
| 227 | Craft::$app->db->createCommand() |
||
| 228 | ->delete('{{%reasons}}', ['id' => $id]) |
||
| 229 | ->execute(); |
||
| 230 | $transaction->commit(); |
||
| 231 | } catch (\Throwable $e) { |
||
| 232 | $transaction->rollBack(); |
||
| 233 | throw $e; |
||
| 234 | } |
||
| 235 | } |
||
| 236 | |||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * @param RebuildConfigEvent $event |
||
| 241 | * @return void |
||
| 242 | */ |
||
| 243 | public function onProjectConfigRebuild(RebuildConfigEvent $event) |
||
| 244 | { |
||
| 245 | |||
| 246 | Craft::$app->getProjectConfig()->remove('reasons_conditionals'); |
||
| 247 | |||
| 248 | $event->config['reasons_conditionals'] = []; |
||
| 249 | |||
| 250 | $rows = (new Query()) |
||
| 251 | ->select(['reasons.uid', 'reasons.conditionals', 'fieldlayouts.uid AS fieldLayoutUid']) |
||
| 252 | ->from('{{%reasons}} AS reasons') |
||
| 253 | ->innerJoin(['fieldlayouts' => Table::FIELDLAYOUTS], '[[fieldlayouts.id]] = [[reasons.fieldLayoutId]]') |
||
| 254 | ->all(); |
||
| 255 | |||
| 256 | foreach ($rows as $row) { |
||
| 257 | $uid = $row['uid'] ?? null; |
||
| 258 | $conditionals = $row['conditionals'] ?? null; |
||
| 259 | $fieldLayoutUid = $row['fieldLayoutUid'] ?? null; |
||
| 260 | if (!$uid || !$conditionals || !$fieldLayoutUid) { |
||
| 261 | continue; |
||
| 262 | } |
||
| 263 | $event->config['reasons_conditionals'][$uid] = [ |
||
| 264 | 'conditionals' => $conditionals, |
||
| 265 | 'fieldLayoutUid' => $fieldLayoutUid, |
||
| 266 | ]; |
||
| 267 | } |
||
| 268 | |||
| 269 | $this->clearCache(); |
||
| 270 | } |
||
| 271 | |||
| 272 | /** |
||
| 273 | * Clears Reasons' data caches |
||
| 274 | * |
||
| 275 | * @return void |
||
| 276 | */ |
||
| 277 | public function clearCache() |
||
| 278 | { |
||
| 279 | Craft::$app->getCache()->delete($this->getCacheKey()); |
||
| 280 | } |
||
| 281 | |||
| 282 | /** |
||
| 283 | * @return array|mixed |
||
| 284 | */ |
||
| 285 | public function getData() |
||
| 286 | { |
||
| 287 | $doCacheData = !Craft::$app->getConfig()->getGeneral()->devMode; |
||
| 288 | $cacheKey = $this->getCacheKey(); |
||
| 289 | |||
| 290 | if ($doCacheData && $data = Craft::$app->getCache()->get($cacheKey)) { |
||
| 291 | return $data; |
||
| 292 | } |
||
| 293 | |||
| 294 | $data = [ |
||
| 295 | 'conditionals' => $this->getConditionals(), |
||
| 296 | 'toggleFieldTypes' => $this->getToggleFieldTypes(), |
||
| 297 | 'toggleFields' => $this->getToggleFields(), |
||
| 298 | 'fieldIds' => $this->getFieldIdsByHandle(), |
||
| 299 | ]; |
||
| 300 | |||
| 301 | if ($doCacheData) { |
||
| 302 | Craft::$app->getCache()->set($cacheKey, $data, self::CACHE_TTL); |
||
| 303 | } |
||
| 304 | |||
| 305 | return $data; |
||
| 306 | } |
||
| 307 | |||
| 308 | /** |
||
| 309 | * @param string|array $conditionals |
||
| 310 | * @return string|null |
||
| 311 | */ |
||
| 312 | protected function prepConditionalsForProjectConfig($conditionals): ?string |
||
| 313 | { |
||
| 314 | if (!$conditionals) { |
||
| 315 | return null; |
||
| 316 | } |
||
| 317 | $return = []; |
||
| 318 | $conditionals = Json::decodeIfJson($conditionals); |
||
| 319 | foreach ($conditionals as $targetFieldId => $statements) { |
||
| 320 | $targetFieldId = (int)$targetFieldId; |
||
| 321 | $targetFieldUid = $this->getFieldUidById($targetFieldId); |
||
| 322 | $return[$targetFieldUid] = \array_map(function (array $rules) { |
||
| 323 | return \array_map(function (array $rule) { |
||
| 324 | $fieldId = (int)$rule['fieldId']; |
||
| 325 | return [ |
||
| 326 | 'field' => $this->getFieldUidById($fieldId), |
||
| 327 | 'compare' => $rule['compare'], |
||
| 328 | 'value' => $rule['value'], |
||
| 329 | ]; |
||
| 330 | }, $rules); |
||
| 331 | }, $statements); |
||
| 332 | } |
||
| 333 | return Json::encode($return); |
||
| 334 | } |
||
| 335 | |||
| 336 | /** |
||
| 337 | * @param string|array $conditionals |
||
| 338 | * @return array|null |
||
| 339 | */ |
||
| 340 | protected function normalizeConditionalsFromProjectConfig($conditionals): ?array |
||
| 365 | } |
||
| 366 | |||
| 367 | /** |
||
| 368 | * Returns all conditionals, mapped by source key |
||
| 369 | * |
||
| 370 | * @return array |
||
| 371 | */ |
||
| 372 | protected function getConditionals(): array |
||
| 373 | { |
||
| 374 | |||
| 375 | // Get all conditionals from database |
||
| 376 | $rows = (new Query()) |
||
| 377 | ->select(['reasons.id', 'reasons.fieldLayoutId', 'reasons.conditionals']) |
||
| 378 | ->from('{{%reasons}} AS reasons') |
||
| 379 | ->innerJoin(['fieldlayouts' => Table::FIELDLAYOUTS], '[[fieldlayouts.id]] = [[reasons.fieldLayoutId]]') |
||
| 380 | ->all(); |
||
| 381 | |||
| 382 | // Map conditionals to field layouts, and convert field uids to ids |
||
| 383 | $conditionals = []; |
||
| 384 | foreach ($rows as $row) { |
||
| 385 | $conditionals["fieldLayout:{$row['fieldLayoutId']}"] = $this->normalizeConditionalsFromProjectConfig($row['conditionals']); |
||
| 386 | } |
||
| 387 | |||
| 388 | // Map conditionals to sources |
||
| 389 | $conditionalsBySources = []; |
||
| 390 | $sources = $this->getSources(); |
||
| 391 | foreach ($sources as $sourceId => $fieldLayoutId) { |
||
| 392 | if (!isset($conditionals["fieldLayout:{$fieldLayoutId}"])) { |
||
| 393 | continue; |
||
| 394 | } |
||
| 395 | $conditionalsBySources[$sourceId] = $conditionals["fieldLayout:{$fieldLayoutId}"]; |
||
| 396 | } |
||
| 397 | |||
| 398 | return $conditionalsBySources; |
||
| 399 | } |
||
| 400 | |||
| 401 | /** |
||
| 402 | * @return array |
||
| 403 | */ |
||
| 404 | protected function getSources(): array |
||
| 405 | { |
||
| 406 | |||
| 407 | if (!isset($this->sources)) { |
||
| 408 | |||
| 409 | $sources = []; |
||
| 410 | |||
| 411 | $entryTypeRecords = EntryType::find()->all(); |
||
| 412 | /** @var EntryType $entryTypeRecord */ |
||
| 413 | foreach ($entryTypeRecords as $entryTypeRecord) { |
||
| 414 | $sources["entryType:{$entryTypeRecord->id}"] = (int)$entryTypeRecord->fieldLayoutId; |
||
| 415 | $sources["section:{$entryTypeRecord->sectionId}"] = (int)$entryTypeRecord->fieldLayoutId; |
||
| 416 | } |
||
| 417 | |||
| 418 | $categoryGroups = Craft::$app->getCategories()->getAllGroups(); |
||
| 419 | foreach ($categoryGroups as $categoryGroup) { |
||
| 420 | $sources["categoryGroup:{$categoryGroup->id}"] = (int)$categoryGroup->fieldLayoutId; |
||
| 421 | } |
||
| 422 | |||
| 423 | $tagGroups = Craft::$app->getTags()->getAllTagGroups(); |
||
| 424 | foreach ($tagGroups as $tagGroup) { |
||
| 425 | $sources["tagGroup:{$tagGroup->id}"] = (int)$tagGroup->fieldLayoutId; |
||
| 426 | } |
||
| 427 | |||
| 428 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
| 429 | foreach ($volumes as $volume) { |
||
| 430 | $sources["assetSource:{$volume->id}"] = (int)$volume->fieldLayoutId; |
||
| 431 | } |
||
| 432 | |||
| 433 | $globalSets = Craft::$app->getGlobals()->getAllSets(); |
||
| 434 | foreach ($globalSets as $globalSet) { |
||
| 435 | $sources["globalSet:{$globalSet->id}"] = (int)$globalSet->fieldLayoutId; |
||
| 436 | } |
||
| 437 | |||
| 438 | $usersFieldLayout = Craft::$app->getFields()->getLayoutByType(User::class); |
||
| 439 | $sources['users'] = $usersFieldLayout->id; |
||
| 440 | |||
| 441 | $this->sources = $sources; |
||
| 442 | |||
| 443 | } |
||
| 444 | |||
| 445 | return $this->sources; |
||
| 446 | } |
||
| 447 | |||
| 448 | /** |
||
| 449 | * Returns all toggleable fields |
||
| 450 | * |
||
| 451 | * @return array |
||
| 452 | */ |
||
| 453 | protected function getToggleFields(): array |
||
| 477 | } |
||
| 478 | |||
| 479 | /** |
||
| 480 | * Returns all toggleable fieldtype classnames |
||
| 481 | * |
||
| 482 | * @return string[] |
||
| 483 | */ |
||
| 484 | protected function getToggleFieldTypes(): array |
||
| 485 | { |
||
| 486 | return [ |
||
| 487 | Lightswitch::class, |
||
| 499 | ]; |
||
| 500 | } |
||
| 501 | |||
| 502 | /** |
||
| 503 | * Returns all global field IDs, indexed by handle |
||
| 504 | * |
||
| 505 | * @return array |
||
| 506 | */ |
||
| 507 | protected function getFieldIdsByHandle(): array |
||
| 508 | { |
||
| 509 | $handles = []; |
||
| 510 | $fields = $this->getAllFields(); |
||
| 511 | foreach ($fields as $field) { |
||
| 512 | if (!$fields instanceof Field) { |
||
| 513 | continue; |
||
| 514 | } |
||
| 515 | $handles[$field->handle] = (int)$field->id; |
||
| 516 | } |
||
| 517 | return $handles; |
||
| 518 | } |
||
| 519 | |||
| 520 | /** |
||
| 521 | * @return FieldInterface[] |
||
| 522 | */ |
||
| 523 | protected function getAllFields(): array |
||
| 529 | } |
||
| 530 | |||
| 531 | /** |
||
| 532 | * Return the UID for a field, based on its database ID |
||
| 533 | * |
||
| 534 | * @param int $fieldId |
||
| 535 | * @return string |
||
| 536 | */ |
||
| 537 | protected function getFieldUidById(int $fieldId): string |
||
| 538 | { |
||
| 539 | if (!isset($this->fieldUidsById)) { |
||
| 540 | $allFields = $this->getAllFields(); |
||
| 541 | $this->fieldUidsById = \array_reduce($allFields, function (array $carry, FieldInterface $field) { |
||
| 542 | if (!$field instanceof Field) { |
||
| 543 | return $carry; |
||
| 544 | } |
||
| 545 | $carry["{$field->id}"] = $field->uid; |
||
| 546 | return $carry; |
||
| 547 | }, []); |
||
| 548 | } |
||
| 549 | return $this->fieldUidsById["$fieldId"]; |
||
| 550 | } |
||
| 551 | |||
| 552 | /** |
||
| 553 | * Return the database ID for a field, based on its UID |
||
| 554 | * |
||
| 555 | * @param string $fieldUid |
||
| 556 | * @return int |
||
| 557 | */ |
||
| 558 | protected function getFieldIdByUid(string $fieldUid): int |
||
| 571 | } |
||
| 572 | |||
| 573 | /** |
||
| 574 | * @return string |
||
| 575 | */ |
||
| 576 | protected function getCacheKey(): string |
||
| 583 | ]); |
||
| 584 | } |
||
| 585 | } |
||
| 586 |