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