We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
| Total Complexity | 51 | 
| Total Lines | 326 | 
| Duplicated Lines | 0 % | 
| Changes | 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 | ||
| 9 | trait Create | ||
| 10 | { | ||
| 11 | /* | ||
| 12 | |-------------------------------------------------------------------------- | ||
| 13 | | CREATE | ||
| 14 | |-------------------------------------------------------------------------- | ||
| 15 | */ | ||
| 16 | |||
| 17 | /** | ||
| 18 | * Insert a row in the database. | ||
| 19 | * | ||
| 20 | * @param array $input All input values to be inserted. | ||
| 21 | * @return \Illuminate\Database\Eloquent\Model | ||
| 22 | */ | ||
| 23 | public function create($input) | ||
| 24 |     { | ||
| 25 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input); | ||
|  | |||
| 26 | |||
| 27 |         if($this->get('create.useDatabaseTransactions')) { | ||
| 28 | return DB::transaction(fn() => $this->createModelAndRelations($directInputs, $relationInputs)); | ||
| 29 | } | ||
| 30 | |||
| 31 | return $this->createModelAndRelations($directInputs, $relationInputs); | ||
| 32 | } | ||
| 33 | |||
| 34 |     private function createModelAndRelations(array $directInputs, array $relationInputs): Model { | ||
| 35 | $item = $this->model->create($directInputs); | ||
| 36 | $this->createRelationsForItem($item, $relationInputs); | ||
| 37 | return $item; | ||
| 38 | } | ||
| 39 | |||
| 40 | /** | ||
| 41 | * Get all fields needed for the ADD NEW ENTRY form. | ||
| 42 | * | ||
| 43 | * @return array The fields with attributes and fake attributes. | ||
| 44 | */ | ||
| 45 | public function getCreateFields() | ||
| 48 | } | ||
| 49 | |||
| 50 | /** | ||
| 51 | * Get all fields with relation set (model key set on field). | ||
| 52 | * | ||
| 53 | * @param array $fields | ||
| 54 | * @return array The fields with model key set. | ||
| 55 | */ | ||
| 56 | public function getRelationFields($fields = []) | ||
| 57 |     { | ||
| 58 |         if (empty($fields)) { | ||
| 59 | $fields = $this->getCleanStateFields(); | ||
| 60 | } | ||
| 61 | |||
| 62 | $relationFields = []; | ||
| 63 | |||
| 64 |         foreach ($fields as $field) { | ||
| 65 |             if (isset($field['model']) && $field['model'] !== false && $field['entity'] !== false) { | ||
| 66 | array_push($relationFields, $field); | ||
| 67 | } | ||
| 68 | |||
| 69 | // if a field has an array name AND subfields | ||
| 70 | // then take those fields into account (check if they have relationships); | ||
| 71 | // this is done in particular for the checklist_dependency field, | ||
| 72 | // but other fields could use it too, in the future; | ||
| 73 | if ($this->holdsMultipleInputs($field['name']) && | ||
| 74 | isset($field['subfields']) && | ||
| 75 |                 is_array($field['subfields'])) { | ||
| 76 |                 foreach ($field['subfields'] as $subfield) { | ||
| 77 |                     if (isset($subfield['model']) && $subfield['model'] !== false) { | ||
| 78 | array_push($relationFields, $subfield); | ||
| 79 | } | ||
| 80 | } | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | return $relationFields; | ||
| 85 | } | ||
| 86 | |||
| 87 | /** | ||
| 88 | * --------------- | ||
| 89 | * PRIVATE METHODS | ||
| 90 | * ---------------. | ||
| 91 | */ | ||
| 92 | |||
| 93 | /** | ||
| 94 | * Create relations for the provided model. | ||
| 95 | * | ||
| 96 | * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model. | ||
| 97 | * @param array $formattedRelations The form data. | ||
| 98 | * @return bool|null | ||
| 99 | */ | ||
| 100 | private function createRelationsForItem($item, $formattedRelations) | ||
| 101 |     { | ||
| 102 | // no relations to create | ||
| 103 |         if (empty($formattedRelations)) { | ||
| 104 | return false; | ||
| 105 | } | ||
| 106 | |||
| 107 |         foreach ($formattedRelations as $relationMethod => $relationDetails) { | ||
| 108 |             $relation = $item->{$relationMethod}(); | ||
| 109 | $relationType = $relationDetails['relation_type']; | ||
| 110 | |||
| 111 |             switch ($relationType) { | ||
| 112 | case 'HasOne': | ||
| 113 | case 'MorphOne': | ||
| 114 | $this->createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails); | ||
| 115 | break; | ||
| 116 | case 'HasMany': | ||
| 117 | case 'MorphMany': | ||
| 118 | $relationValues = $relationDetails['values'][$relationMethod]; | ||
| 119 | // if relation values are null we can only attach, also we check if we sent | ||
| 120 | // - a single dimensional array: [1,2,3] | ||
| 121 | // - an array of arrays: [[1][2][3]] | ||
| 122 | // if is as single dimensional array we can only attach. | ||
| 123 |                     if ($relationValues === null || ! is_multidimensional_array($relationValues)) { | ||
| 124 | $this->attachManyRelation($item, $relation, $relationDetails, $relationValues); | ||
| 125 |                     } else { | ||
| 126 | $this->createManyEntries($item, $relation, $relationMethod, $relationDetails); | ||
| 127 | } | ||
| 128 | break; | ||
| 129 | case 'BelongsToMany': | ||
| 130 | case 'MorphToMany': | ||
| 131 | $values = $relationDetails['values'][$relationMethod] ?? []; | ||
| 132 | $values = is_string($values) ? json_decode($values, true) : $values; | ||
| 133 | |||
| 134 | // disabling ConvertEmptyStringsToNull middleware may return null from json_decode() if an empty string is used. | ||
| 135 | // we need to make sure no null value can go foward so we reassure that values is not null after json_decode() | ||
| 136 | $values = $values ?? []; | ||
| 137 | |||
| 138 | $relationValues = []; | ||
| 139 | |||
| 140 |                     if (is_array($values) && is_multidimensional_array($values)) { | ||
| 141 |                         foreach ($values as $value) { | ||
| 142 |                             if (isset($value[$relationMethod])) { | ||
| 143 | $relationValues[$value[$relationMethod]] = Arr::except($value, $relationMethod); | ||
| 144 | } | ||
| 145 | } | ||
| 146 | } | ||
| 147 | |||
| 148 | // if there is no relation data, and the values array is single dimensional we have | ||
| 149 | // an array of keys with no aditional pivot data. sync those. | ||
| 150 |                     if (empty($relationValues)) { | ||
| 151 | $relationValues = array_values($values); | ||
| 152 | } | ||
| 153 | |||
| 154 |                     $item->{$relationMethod}()->sync($relationValues); | ||
| 155 | break; | ||
| 156 | } | ||
| 157 | } | ||
| 158 | } | ||
| 159 | |||
| 160 | /** | ||
| 161 | * Save the attributes of a given HasOne or MorphOne relationship on the | ||
| 162 | * related entry, create or delete it, depending on what was sent in the form. | ||
| 163 | * | ||
| 164 | * For HasOne and MorphOne relationships, the dev might want to a few different things: | ||
| 165 | * (A) save an attribute on the related entry (eg. passport.number) | ||
| 166 | * (B) set an attribute on the related entry to NULL (eg. slug.slug) | ||
| 167 | * (C) save an entire related entry (eg. passport) | ||
| 168 | * (D) delete the entire related entry (eg. passport) | ||
| 169 | * | ||
| 170 | * @param \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation | ||
| 171 | * @param string $relationMethod The name of the relationship method on the main Model. | ||
| 172 | * @param array $relationDetails Details about that relationship. For example: | ||
| 173 | * [ | ||
| 174 | * 'model' => 'App\Models\Passport', | ||
| 175 | * 'parent' => 'App\Models\Pet', | ||
| 176 | * 'entity' => 'passport', | ||
| 177 | * 'attribute' => 'passport', | ||
| 178 | * 'values' => **THE TRICKY BIT**, | ||
| 179 | * ] | ||
| 180 | * @return Model|null | ||
| 181 | */ | ||
| 182 | private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails) | ||
| 183 |     { | ||
| 184 | // Let's see which scenario we're treating, depending on the contents of $relationDetails: | ||
| 185 | // - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field) | ||
| 186 | // - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared) | ||
| 187 | // - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field) | ||
| 188 | // - (D) ['passport' => null] (if deleted from the repeatable field) | ||
| 189 | |||
| 190 | // Scenario C or D | ||
| 191 |         if (array_key_exists($relationMethod, $relationDetails['values'])) { | ||
| 192 | $relationMethodValue = $relationDetails['values'][$relationMethod]; | ||
| 193 | |||
| 194 | // Scenario D | ||
| 195 |             if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) { | ||
| 196 | $relation->first()?->delete(); | ||
| 197 | |||
| 198 | return null; | ||
| 199 | } | ||
| 200 | |||
| 201 | // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field) | ||
| 202 |             if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) { | ||
| 203 | $relationMethodValue = $relationMethodValue[0]; | ||
| 204 | } | ||
| 205 | } | ||
| 206 | // saving process | ||
| 207 | $input = $relationMethodValue ?? $relationDetails['values']; | ||
| 208 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod); | ||
| 209 | |||
| 210 | $item = $relation->updateOrCreate([], $directInputs); | ||
| 211 | |||
| 212 | $this->createRelationsForItem($item, $relationInputs); | ||
| 213 | |||
| 214 | return $item; | ||
| 215 | } | ||
| 216 | |||
| 217 | /** | ||
| 218 | * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations. | ||
| 219 | * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it. | ||
| 220 | * Here we add the entries that developer added and remove the ones that are not in the list. | ||
| 221 | * This removal process happens with the following rules: | ||
| 222 | * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones. | ||
| 223 | * - `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. | ||
| 224 | * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us. | ||
| 225 | * | ||
| 226 | * @return mixed | ||
| 227 | */ | ||
| 228 | private function attachManyRelation($item, $relation, $relationDetails, $relationValues) | ||
| 263 | } | ||
| 264 | |||
| 265 | private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey) | ||
| 293 | } | ||
| 294 | |||
| 295 | /** | ||
| 296 | * Handle HasMany/MorphMany relations when used as creatable entries in the crud. | ||
| 297 | * By using repeatable field, developer can allow the creation of such entries | ||
| 298 | * in the crud forms. | ||
| 299 | * | ||
| 300 | * @param $entry - eg: story | ||
| 301 | * @param $relation - eg story HasMany monsters | ||
| 302 | * @param $relationMethod - eg: monsters | ||
| 303 | * @param $relationDetails - eg: info about relation including submited values | ||
| 304 | * @return void | ||
| 305 | */ | ||
| 306 | private function createManyEntries($entry, $relation, $relationMethod, $relationDetails) | ||
| 335 | } | ||
| 336 | } | ||
| 338 |