We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
| Total Complexity | 71 |
| Total Lines | 437 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| Bugs | 1 | Features | 0 |
Complex classes like Create 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 Create, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 12 | trait Create |
||
| 13 | { |
||
| 14 | /* |
||
| 15 | |-------------------------------------------------------------------------- |
||
| 16 | | CREATE |
||
| 17 | |-------------------------------------------------------------------------- |
||
| 18 | */ |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Insert a row in the database. |
||
| 22 | * |
||
| 23 | * @param array $data All input values to be inserted. |
||
| 24 | * |
||
| 25 | * @return \Illuminate\Database\Eloquent\Model |
||
| 26 | */ |
||
| 27 | public function create($data) |
||
| 28 | { |
||
| 29 | $data = $this->decodeJsonCastedAttributes($data); |
||
|
|
|||
| 30 | $data = $this->compactFakeFields($data); |
||
| 31 | |||
| 32 | // omit the n-n relationships when updating the eloquent item |
||
| 33 | $relationships = Arr::pluck($this->getRelationFields(), 'name'); |
||
| 34 | |||
| 35 | // init and fill model |
||
| 36 | $item = $this->model->make(Arr::except($data, $relationships)); |
||
| 37 | |||
| 38 | // handle BelongsTo 1:1 relations |
||
| 39 | $item = $this->associateOrDissociateBelongsToRelations($item, $data); |
||
| 40 | $item->save(); |
||
| 41 | |||
| 42 | // if there are any other relations create them. |
||
| 43 | $this->createRelations($item, $data); |
||
| 44 | |||
| 45 | return $item; |
||
| 46 | } |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Get all fields needed for the ADD NEW ENTRY form. |
||
| 50 | * |
||
| 51 | * @return array The fields with attributes and fake attributes. |
||
| 52 | */ |
||
| 53 | public function getCreateFields() |
||
| 54 | { |
||
| 55 | return $this->fields(); |
||
| 56 | } |
||
| 57 | |||
| 58 | /** |
||
| 59 | * Get all fields with relation set (model key set on field). |
||
| 60 | * |
||
| 61 | * @return array The fields with model key set. |
||
| 62 | */ |
||
| 63 | public function getRelationFields() |
||
| 83 | } |
||
| 84 | |||
| 85 | /** |
||
| 86 | * Get all fields with n-n relation set (pivot table is true). |
||
| 87 | * |
||
| 88 | * @return array The fields with n-n relationships. |
||
| 89 | */ |
||
| 90 | public function getRelationFieldsWithPivot() |
||
| 96 | }); |
||
| 97 | } |
||
| 98 | |||
| 99 | /** |
||
| 100 | * Create the relations for the current model. |
||
| 101 | * |
||
| 102 | * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model. |
||
| 103 | * @param array $data The form data. |
||
| 104 | */ |
||
| 105 | public function createRelations($item, $data) |
||
| 114 | } |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Sync the declared many-to-many associations through the pivot field. |
||
| 118 | * |
||
| 119 | * @param \Illuminate\Database\Eloquent\Model $model The current CRUD model. |
||
| 120 | * @param array $data The form data. |
||
| 121 | */ |
||
| 122 | public function syncPivot($model, $data) |
||
| 123 | { |
||
| 124 | $fields_with_relationships = $this->getRelationFieldsWithPivot(); |
||
| 125 | foreach ($fields_with_relationships as $field) { |
||
| 126 | $values = isset($data[$field['name']]) ? $data[$field['name']] : []; |
||
| 127 | |||
| 128 | // if a JSON was passed instead of an array, turn it into an array |
||
| 129 | if (is_string($values)) { |
||
| 130 | $decoded_values = json_decode($values, true); |
||
| 131 | $values = []; |
||
| 132 | // array is not multidimensional |
||
| 133 | if (count($decoded_values) != count($decoded_values, COUNT_RECURSIVE)) { |
||
| 134 | foreach ($decoded_values as $value) { |
||
| 135 | $values[] = $value[$field['name']]; |
||
| 136 | } |
||
| 137 | } else { |
||
| 138 | $values = $decoded_values; |
||
| 139 | } |
||
| 140 | } |
||
| 141 | |||
| 142 | $relation_data = []; |
||
| 143 | |||
| 144 | foreach ($values as $pivot_id) { |
||
| 145 | if ($pivot_id != '') { |
||
| 146 | $pivot_data = []; |
||
| 147 | |||
| 148 | if (isset($field['pivotFields'])) { |
||
| 149 | // array is not multidimensional |
||
| 150 | if (count($field['pivotFields']) == count($field['pivotFields'], COUNT_RECURSIVE)) { |
||
| 151 | foreach ($field['pivotFields'] as $pivot_field_name) { |
||
| 152 | $pivot_data[$pivot_field_name] = $data[$pivot_field_name][$pivot_id]; |
||
| 153 | } |
||
| 154 | } else { |
||
| 155 | $field_data = json_decode($data[$field['name']], true); |
||
| 156 | |||
| 157 | // we grab from the parsed data the specific values for this pivot |
||
| 158 | $pivot_data = Arr::first($field_data, function ($item) use ($pivot_id, $field) { |
||
| 159 | return $item[$field['name']] === $pivot_id; |
||
| 160 | }); |
||
| 161 | |||
| 162 | // we remove the relation field from extra pivot data as we already have the relation. |
||
| 163 | unset($pivot_data[$field['name']]); |
||
| 164 | } |
||
| 165 | } |
||
| 166 | |||
| 167 | $relation_data[$pivot_id] = $pivot_data; |
||
| 168 | } |
||
| 169 | |||
| 170 | $model->{$field['name']}()->sync($relation_data); |
||
| 171 | |||
| 172 | if (isset($field['morph']) && $field['morph'] && isset($data[$field['name']])) { |
||
| 173 | $values = $data[$field['name']]; |
||
| 174 | $model->{$field['name']}()->sync($values); |
||
| 175 | } |
||
| 176 | } |
||
| 177 | } |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * Handles 1-1 and 1-n relations. In case 1-1 it handles subsequent relations in connected models |
||
| 182 | * For example, a Monster > HasOne Address > BelongsTo a Country. |
||
| 183 | * |
||
| 184 | * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model. |
||
| 185 | * @param array $formattedData The form data. |
||
| 186 | * |
||
| 187 | * @return bool|null |
||
| 188 | */ |
||
| 189 | private function createRelationsForItem($item, $formattedData) |
||
| 190 | { |
||
| 191 | if (! isset($formattedData['relations'])) { |
||
| 192 | return false; |
||
| 193 | } |
||
| 194 | |||
| 195 | foreach ($formattedData['relations'] as $relationMethod => $relationData) { |
||
| 196 | if (! isset($relationData['model'])) { |
||
| 197 | continue; |
||
| 198 | } |
||
| 199 | |||
| 200 | $relation = $item->{$relationMethod}(); |
||
| 201 | $relation_type = get_class($relation); |
||
| 202 | |||
| 203 | switch ($relation_type) { |
||
| 204 | case HasOne::class: |
||
| 205 | case MorphOne::class: |
||
| 206 | // we first check if there are relations of the relation |
||
| 207 | if (isset($relationData['relations'])) { |
||
| 208 | // if there are nested relations, we first add the BelongsTo like in main entry |
||
| 209 | $belongsToRelations = Arr::where($relationData['relations'], function ($relation_data) { |
||
| 210 | return $relation_data['relation_type'] == 'BelongsTo'; |
||
| 211 | }); |
||
| 212 | |||
| 213 | // adds the values of the BelongsTo relations of this entity to the array of values that will |
||
| 214 | // be saved at the same time like we do in parent entity belongs to relations |
||
| 215 | $valuesWithRelations = $this->associateHasOneBelongsTo($belongsToRelations, $relationData['values'], $relation->getModel()); |
||
| 216 | |||
| 217 | // remove previously added BelongsTo relations from relation data. |
||
| 218 | $relationData['relations'] = Arr::where($relationData['relations'], function ($item) { |
||
| 219 | return $item['relation_type'] != 'BelongsTo'; |
||
| 220 | }); |
||
| 221 | |||
| 222 | $modelInstance = $relation->updateOrCreate([], $valuesWithRelations); |
||
| 223 | } else { |
||
| 224 | $modelInstance = $relation->updateOrCreate([], $relationData['values']); |
||
| 225 | } |
||
| 226 | break; |
||
| 227 | case HasMany::class: |
||
| 228 | case MorphMany::class: |
||
| 229 | |||
| 230 | $relation_values = $relationData['values'][$relationMethod]; |
||
| 231 | |||
| 232 | if (is_string($relation_values)) { |
||
| 233 | $relation_values = json_decode($relationData['values'][$relationMethod], true); |
||
| 234 | } |
||
| 235 | |||
| 236 | if ($relation_values === null || count($relation_values) == count($relation_values, COUNT_RECURSIVE)) { |
||
| 237 | $this->attachManyRelation($item, $relation, $relationMethod, $relationData, $relation_values); |
||
| 238 | } else { |
||
| 239 | $this->createManyEntries($item, $relation, $relationMethod, $relationData); |
||
| 240 | } |
||
| 241 | break; |
||
| 242 | } |
||
| 243 | |||
| 244 | if (isset($relationData['relations'])) { |
||
| 245 | $this->createRelationsForItem($modelInstance, ['relations' => $relationData['relations']]); |
||
| 246 | } |
||
| 247 | } |
||
| 248 | } |
||
| 249 | |||
| 250 | /** |
||
| 251 | * Associate and dissociate BelongsTo relations in the model. |
||
| 252 | * |
||
| 253 | * @param Model $item |
||
| 254 | * @param array $data The form data. |
||
| 255 | * @return Model Model with relationships set up. |
||
| 256 | */ |
||
| 257 | protected function associateOrDissociateBelongsToRelations($item, array $data) |
||
| 258 | { |
||
| 259 | $belongsToFields = $this->getFieldsWithRelationType('BelongsTo'); |
||
| 260 | |||
| 261 | foreach ($belongsToFields as $relationField) { |
||
| 262 | if (method_exists($item, $this->getOnlyRelationEntity($relationField))) { |
||
| 263 | $relatedId = Arr::get($data, $relationField['name']); |
||
| 264 | if (isset($relatedId) && $relatedId !== null) { |
||
| 265 | $related = $relationField['model']::find($relatedId); |
||
| 266 | |||
| 267 | $item->{$this->getOnlyRelationEntity($relationField)}()->associate($related); |
||
| 268 | } else { |
||
| 269 | $item->{$this->getOnlyRelationEntity($relationField)}()->dissociate(); |
||
| 270 | } |
||
| 271 | } |
||
| 272 | } |
||
| 273 | |||
| 274 | return $item; |
||
| 275 | } |
||
| 276 | |||
| 277 | /** |
||
| 278 | * Associate the nested HasOne -> BelongsTo relations by adding the "connecting key" |
||
| 279 | * to the array of values that is going to be saved with HasOne relation. |
||
| 280 | * |
||
| 281 | * @param array $belongsToRelations |
||
| 282 | * @param array $modelValues |
||
| 283 | * @param Model $relationInstance |
||
| 284 | * @return array |
||
| 285 | */ |
||
| 286 | private function associateHasOneBelongsTo($belongsToRelations, $modelValues, $modelInstance) |
||
| 287 | { |
||
| 288 | foreach ($belongsToRelations as $methodName => $values) { |
||
| 289 | $relation = $modelInstance->{$methodName}(); |
||
| 290 | |||
| 291 | $modelValues[$relation->getForeignKeyName()] = $values['values'][$methodName]; |
||
| 292 | } |
||
| 293 | |||
| 294 | return $modelValues; |
||
| 295 | } |
||
| 296 | |||
| 297 | /** |
||
| 298 | * Get a relation data array from the form data. |
||
| 299 | * For each relation defined in the fields through the entity attribute, set the model, the parent model and the |
||
| 300 | * attribute values. |
||
| 301 | * |
||
| 302 | * We traverse this relation array later to create the relations, for example: |
||
| 303 | * |
||
| 304 | * Current model HasOne Address, this Address (line_1, country_id) BelongsTo Country through country_id in Address Model. |
||
| 305 | * |
||
| 306 | * So when editing current model crud user have two fields address.line_1 and address.country (we infer country_id from relation) |
||
| 307 | * |
||
| 308 | * Those will be nested accordingly in this relation array, so address relation will have a nested relation with country. |
||
| 309 | * |
||
| 310 | * |
||
| 311 | * @param array $data The form data. |
||
| 312 | * |
||
| 313 | * @return array The formatted relation data. |
||
| 314 | */ |
||
| 315 | private function getRelationDataFromFormData($data) |
||
| 316 | { |
||
| 317 | // exclude the already attached belongs to relations but include nested belongs to. |
||
| 318 | $relation_fields = Arr::where($this->getRelationFields(), function ($field, $key) { |
||
| 319 | return $field['relation_type'] !== 'BelongsTo' || $this->isNestedRelation($field); |
||
| 320 | }); |
||
| 321 | |||
| 322 | $relationData = []; |
||
| 323 | |||
| 324 | foreach ($relation_fields as $relation_field) { |
||
| 325 | $attributeKey = $this->parseRelationFieldNamesFromHtml([$relation_field])[0]['name']; |
||
| 326 | if (isset($relation_field['pivot']) && $relation_field['pivot'] !== true) { |
||
| 327 | $key = implode('.relations.', explode('.', $this->getOnlyRelationEntity($relation_field))); |
||
| 328 | $fieldData = Arr::get($relationData, 'relations.'.$key, []); |
||
| 329 | if (! array_key_exists('model', $fieldData)) { |
||
| 330 | $fieldData['model'] = $relation_field['model']; |
||
| 331 | } |
||
| 332 | if (! array_key_exists('parent', $fieldData)) { |
||
| 333 | $fieldData['parent'] = $this->getRelationModel($attributeKey, -1); |
||
| 334 | } |
||
| 335 | |||
| 336 | // when using HasMany/MorphMany if fallback_id is provided instead of deleting the models |
||
| 337 | // from database we resort to this fallback provided by developer |
||
| 338 | if (array_key_exists('fallback_id', $relation_field)) { |
||
| 339 | $fieldData['fallback_id'] = $relation_field['fallback_id']; |
||
| 340 | } |
||
| 341 | |||
| 342 | // when using HasMany/MorphMany and column is nullable, by default backpack sets the value to null. |
||
| 343 | // this allow developers to override that behavior and force deletion from database |
||
| 344 | $fieldData['force_delete'] = $relation_field['force_delete'] ?? false; |
||
| 345 | |||
| 346 | if (! array_key_exists('relation_type', $fieldData)) { |
||
| 347 | $fieldData['relation_type'] = $relation_field['relation_type']; |
||
| 348 | } |
||
| 349 | $relatedAttribute = Arr::last(explode('.', $attributeKey)); |
||
| 350 | $fieldData['values'][$relatedAttribute] = Arr::get($data, $attributeKey); |
||
| 351 | |||
| 352 | Arr::set($relationData, 'relations.'.$key, $fieldData); |
||
| 353 | } |
||
| 354 | } |
||
| 355 | |||
| 356 | return $relationData; |
||
| 357 | } |
||
| 358 | |||
| 359 | /** |
||
| 360 | * When using the HasMany/MorphMany relations as selectable elements we use this function to sync those relations. |
||
| 361 | * Here we allow for different functionality than when creating. Developer could use this relation as a |
||
| 362 | * selectable list of items that can belong to one/none entity at any given time. |
||
| 363 | * |
||
| 364 | * @return void |
||
| 365 | */ |
||
| 366 | public function attachManyRelation($item, $relation, $relationMethod, $relationData, $relation_values) |
||
| 411 | } |
||
| 412 | } |
||
| 413 | } |
||
| 414 | } |
||
| 415 | |||
| 416 | /** |
||
| 417 | * Handle HasMany/MorphMany relations when used as creatable entries in the crud. |
||
| 418 | * By using repeatable field, developer can allow the creation of such entries |
||
| 419 | * in the crud forms. |
||
| 420 | * |
||
| 421 | * @return void |
||
| 422 | */ |
||
| 423 | public function createManyEntries($entry, $relation, $relationMethod, $relationData) |
||
| 449 | } |
||
| 450 | } |
||
| 451 | } |
||
| 452 | } |
||
| 453 |