We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
| Total Complexity | 59 |
| Total Lines | 374 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | 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 |
||
| 11 | trait Create |
||
| 12 | { |
||
| 13 | /* |
||
| 14 | |-------------------------------------------------------------------------- |
||
| 15 | | CREATE |
||
| 16 | |-------------------------------------------------------------------------- |
||
| 17 | */ |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Insert a row in the database. |
||
| 21 | * |
||
| 22 | * @param array $input All input values to be inserted. |
||
| 23 | * @return Model |
||
| 24 | */ |
||
| 25 | public function create($input) |
||
| 26 | { |
||
| 27 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input); |
||
|
|
|||
| 28 | |||
| 29 | if ($this->get('create.useDatabaseTransactions') ?? config('backpack.base.useDatabaseTransactions', false)) { |
||
| 30 | return DB::transaction(fn () => $this->createModelAndRelations($directInputs, $relationInputs)); |
||
| 31 | } |
||
| 32 | |||
| 33 | return $this->createModelAndRelations($directInputs, $relationInputs); |
||
| 34 | } |
||
| 35 | |||
| 36 | private function createModelAndRelations(array $directInputs, array $relationInputs): Model |
||
| 37 | { |
||
| 38 | $item = $this->model->create($directInputs); |
||
| 39 | $this->createRelationsForItem($item, $relationInputs); |
||
| 40 | |||
| 41 | return $item; |
||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * Get all fields needed for the ADD NEW ENTRY form. |
||
| 46 | * |
||
| 47 | * @return array The fields with attributes and fake attributes. |
||
| 48 | */ |
||
| 49 | public function getCreateFields() |
||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Get all fields with relation set (model key set on field). |
||
| 56 | * |
||
| 57 | * @param array $fields |
||
| 58 | * @return array The fields with model key set. |
||
| 59 | */ |
||
| 60 | public function getRelationFields($fields = []) |
||
| 89 | } |
||
| 90 | |||
| 91 | /** |
||
| 92 | * --------------- |
||
| 93 | * PRIVATE METHODS |
||
| 94 | * ---------------. |
||
| 95 | */ |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Create relations for the provided model. |
||
| 99 | * |
||
| 100 | * @param Model $item The current CRUD model. |
||
| 101 | * @param array $formattedRelations The form data. |
||
| 102 | * @return bool|null |
||
| 103 | */ |
||
| 104 | private function createRelationsForItem($item, $formattedRelations) |
||
| 105 | { |
||
| 106 | // no relations to create |
||
| 107 | if (empty($formattedRelations)) { |
||
| 108 | return false; |
||
| 109 | } |
||
| 110 | |||
| 111 | foreach ($formattedRelations as $relationMethod => $relationDetails) { |
||
| 112 | $relation = $item->{$relationMethod}(); |
||
| 113 | $relationType = $relationDetails['relation_type']; |
||
| 114 | |||
| 115 | switch ($relationType) { |
||
| 116 | case 'HasOne': |
||
| 117 | case 'MorphOne': |
||
| 118 | $this->createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails); |
||
| 119 | break; |
||
| 120 | case 'HasMany': |
||
| 121 | case 'MorphMany': |
||
| 122 | $relationValues = $relationDetails['values'][$relationMethod]; |
||
| 123 | // if relation values are null we can only attach, also we check if we sent |
||
| 124 | // - a single dimensional array: [1,2,3] |
||
| 125 | // - an array of arrays: [[1][2][3]] |
||
| 126 | // if is as single dimensional array we can only attach. |
||
| 127 | if ($relationValues === null || ! is_multidimensional_array($relationValues)) { |
||
| 128 | $this->attachManyRelation($item, $relation, $relationDetails, $relationValues); |
||
| 129 | } else { |
||
| 130 | $this->createManyEntries($item, $relation, $relationMethod, $relationDetails); |
||
| 131 | } |
||
| 132 | break; |
||
| 133 | case 'BelongsToMany': |
||
| 134 | case 'MorphToMany': |
||
| 135 | $values = $relationDetails['values'][$relationMethod] ?? []; |
||
| 136 | $values = is_string($values) ? (json_decode($values, true) ?? []) : $values; |
||
| 137 | $field = $relationDetails['crudFields'][0] ?? []; |
||
| 138 | |||
| 139 | // if the values are multidimensional, we have additional pivot data. |
||
| 140 | if (is_array($values) && is_multidimensional_array($values)) { |
||
| 141 | // if the field allow duplicated pivots, we can't use sync or attach from laravel, we need to manually handle the pivot data. |
||
| 142 | if ($field['allow_duplicate_pivots'] ?? false) { |
||
| 143 | $keyName = $field['pivot_key_name'] ?? 'id'; |
||
| 144 | $sentIds = array_filter(array_column($values, $keyName)); |
||
| 145 | $dbValues = $relation->newPivotQuery()->pluck($keyName)->toArray(); |
||
| 146 | |||
| 147 | $toDelete = array_diff($dbValues, $sentIds); |
||
| 148 | |||
| 149 | if (! empty($toDelete)) { |
||
| 150 | foreach ($toDelete as $id) { |
||
| 151 | $relation->newPivot()->where($keyName, $id)->delete(); |
||
| 152 | } |
||
| 153 | } |
||
| 154 | foreach ($values as $value) { |
||
| 155 | // if it's an existing pivot, update it |
||
| 156 | $attributes = $this->preparePivotAttributesForSave($value, $relation, $item->getKey(), $keyName); |
||
| 157 | if (isset($value[$keyName])) { |
||
| 158 | $relation->newPivot()->where($keyName, $value[$keyName])->update($attributes); |
||
| 159 | } else { |
||
| 160 | $relation->newPivot()->create($attributes); |
||
| 161 | } |
||
| 162 | } |
||
| 163 | break; |
||
| 164 | } |
||
| 165 | |||
| 166 | $relationToManyValues = []; |
||
| 167 | |||
| 168 | foreach ($values as $value) { |
||
| 169 | if (isset($value[$relationMethod])) { |
||
| 170 | $relationToManyValues[$value[$relationMethod]] = Arr::except($value, $relationMethod); |
||
| 171 | } |
||
| 172 | } |
||
| 173 | |||
| 174 | $item->{$relationMethod}()->sync($relationToManyValues); |
||
| 175 | unset($relationToManyValues); |
||
| 176 | break; |
||
| 177 | } |
||
| 178 | |||
| 179 | // if there is no relation data, and the values array is single dimensional we have |
||
| 180 | // an array of keys with no additional pivot data. sync those. |
||
| 181 | if (empty($relationToManyValues)) { |
||
| 182 | $relationToManyValues = array_values($values); |
||
| 183 | } |
||
| 184 | $item->{$relationMethod}()->sync($relationToManyValues); |
||
| 185 | unset($relationToManyValues); |
||
| 186 | break; |
||
| 187 | } |
||
| 188 | } |
||
| 189 | } |
||
| 190 | |||
| 191 | private function preparePivotAttributesForSave(array $attributes, BelongsToMany|MorphToMany $relation, string|int $relatedItemKey, $pivotKeyName) |
||
| 201 | } |
||
| 202 | |||
| 203 | /** |
||
| 204 | * Save the attributes of a given HasOne or MorphOne relationship on the |
||
| 205 | * related entry, create or delete it, depending on what was sent in the form. |
||
| 206 | * |
||
| 207 | * For HasOne and MorphOne relationships, the dev might want to a few different things: |
||
| 208 | * (A) save an attribute on the related entry (eg. passport.number) |
||
| 209 | * (B) set an attribute on the related entry to NULL (eg. slug.slug) |
||
| 210 | * (C) save an entire related entry (eg. passport) |
||
| 211 | * (D) delete the entire related entry (eg. passport) |
||
| 212 | * |
||
| 213 | * @param \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation |
||
| 214 | * @param string $relationMethod The name of the relationship method on the main Model. |
||
| 215 | * @param array $relationDetails Details about that relationship. For example: |
||
| 216 | * [ |
||
| 217 | * 'model' => 'App\Models\Passport', |
||
| 218 | * 'parent' => 'App\Models\Pet', |
||
| 219 | * 'entity' => 'passport', |
||
| 220 | * 'attribute' => 'passport', |
||
| 221 | * 'values' => **THE TRICKY BIT**, |
||
| 222 | * ] |
||
| 223 | * @return Model|null |
||
| 224 | */ |
||
| 225 | private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails) |
||
| 226 | { |
||
| 227 | // Let's see which scenario we're treating, depending on the contents of $relationDetails: |
||
| 228 | // - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field) |
||
| 229 | // - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared) |
||
| 230 | // - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field) |
||
| 231 | // - (D) ['passport' => null] (if deleted from the repeatable field) |
||
| 232 | |||
| 233 | // Scenario C or D |
||
| 234 | if (array_key_exists($relationMethod, $relationDetails['values'])) { |
||
| 235 | $relationMethodValue = $relationDetails['values'][$relationMethod]; |
||
| 236 | |||
| 237 | // Scenario D |
||
| 238 | if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) { |
||
| 239 | $relation->first()?->delete(); |
||
| 240 | |||
| 241 | return null; |
||
| 242 | } |
||
| 243 | |||
| 244 | // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field) |
||
| 245 | if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) { |
||
| 246 | $relationMethodValue = $relationMethodValue[0]; |
||
| 247 | } |
||
| 248 | } |
||
| 249 | // saving process |
||
| 250 | $input = $relationMethodValue ?? $relationDetails['values']; |
||
| 251 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod); |
||
| 252 | |||
| 253 | $item = $relation->updateOrCreate([], $directInputs); |
||
| 254 | |||
| 255 | $this->createRelationsForItem($item, $relationInputs); |
||
| 256 | |||
| 257 | return $item; |
||
| 258 | } |
||
| 259 | |||
| 260 | /** |
||
| 261 | * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations. |
||
| 262 | * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it. |
||
| 263 | * Here we add the entries that developer added and remove the ones that are not in the list. |
||
| 264 | * This removal process happens with the following rules: |
||
| 265 | * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones. |
||
| 266 | * - `force_delete` is configurable in the field, it's `true` by default. When false, if connecting column is nullable instead of deleting the row we set the column to null. |
||
| 267 | * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us. |
||
| 268 | * |
||
| 269 | * @return mixed |
||
| 270 | */ |
||
| 271 | private function attachManyRelation($item, $relation, $relationDetails, $relationValues) |
||
| 306 | } |
||
| 307 | |||
| 308 | private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey) |
||
| 343 | } |
||
| 344 | |||
| 345 | /** |
||
| 346 | * Handle HasMany/MorphMany relations when used as creatable entries in the crud. |
||
| 347 | * By using repeatable field, developer can allow the creation of such entries |
||
| 348 | * in the crud forms. |
||
| 349 | * |
||
| 350 | * @param $entry - eg: story |
||
| 351 | * @param $relation - eg story HasMany monsters |
||
| 352 | * @param $relationMethod - eg: monsters |
||
| 353 | * @param $relationDetails - eg: info about relation including submitted values |
||
| 354 | * @return void |
||
| 355 | */ |
||
| 356 | private function createManyEntries($entry, $relation, $relationMethod, $relationDetails) |
||
| 385 | } |
||
| 386 | } |
||
| 388 |