We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
Total Complexity | 56 |
Total Lines | 358 |
Duplicated Lines | 0 % |
Changes | 1 | ||
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 |
||
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') ?? config('backpack.base.useDatabaseTransactions', false)) { |
||
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 | { |
||
36 | $item = $this->model->create($directInputs); |
||
37 | $this->createRelationsForItem($item, $relationInputs); |
||
38 | |||
39 | return $item; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Get all fields needed for the ADD NEW ENTRY form. |
||
44 | * |
||
45 | * @return array The fields with attributes and fake attributes. |
||
46 | */ |
||
47 | public function getCreateFields() |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Get all fields with relation set (model key set on field). |
||
54 | * |
||
55 | * @param array $fields |
||
56 | * @return array The fields with model key set. |
||
57 | */ |
||
58 | public function getRelationFields($fields = []) |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * --------------- |
||
91 | * PRIVATE METHODS |
||
92 | * ---------------. |
||
93 | */ |
||
94 | |||
95 | /** |
||
96 | * Create relations for the provided model. |
||
97 | * |
||
98 | * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model. |
||
99 | * @param array $formattedRelations The form data. |
||
100 | * @return bool|null |
||
101 | */ |
||
102 | private function createRelationsForItem($item, $formattedRelations) |
||
103 | { |
||
104 | // no relations to create |
||
105 | if (empty($formattedRelations)) { |
||
106 | return false; |
||
107 | } |
||
108 | |||
109 | foreach ($formattedRelations as $relationMethod => $relationDetails) { |
||
110 | $relation = $item->{$relationMethod}(); |
||
111 | $relationType = $relationDetails['relation_type']; |
||
112 | |||
113 | switch ($relationType) { |
||
114 | case 'HasOne': |
||
115 | case 'MorphOne': |
||
116 | $this->createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails); |
||
117 | break; |
||
118 | case 'HasMany': |
||
119 | case 'MorphMany': |
||
120 | $relationValues = $relationDetails['values'][$relationMethod]; |
||
121 | // if relation values are null we can only attach, also we check if we sent |
||
122 | // - a single dimensional array: [1,2,3] |
||
123 | // - an array of arrays: [[1][2][3]] |
||
124 | // if is as single dimensional array we can only attach. |
||
125 | if ($relationValues === null || ! is_multidimensional_array($relationValues)) { |
||
126 | $this->attachManyRelation($item, $relation, $relationDetails, $relationValues); |
||
127 | } else { |
||
128 | $this->createManyEntries($item, $relation, $relationMethod, $relationDetails); |
||
129 | } |
||
130 | break; |
||
131 | case 'BelongsToMany': |
||
132 | case 'MorphToMany': |
||
133 | $values = $relationDetails['values'][$relationMethod] ?? []; |
||
134 | $values = is_string($values) ? json_decode($values, true) : $values; |
||
135 | |||
136 | // disabling ConvertEmptyStringsToNull middleware may return null from json_decode() if an empty string is used. |
||
137 | // we need to make sure no null value can go foward so we reassure that values is not null after json_decode() |
||
138 | $values = $values ?? []; |
||
139 | |||
140 | $relationValues = []; |
||
141 | |||
142 | if (is_array($values) && is_multidimensional_array($values)) { |
||
143 | foreach ($values as $value) { |
||
144 | if (isset($value[$relationMethod])) { |
||
145 | $array = Arr::except($value, $relationMethod); |
||
146 | $array[$item->{$relationMethod}()->getRelatedPivotKeyName()] = $value[$relationMethod]; |
||
147 | $relationValues[] = $array; |
||
148 | } |
||
149 | } |
||
150 | } |
||
151 | |||
152 | // if there is no relation data, and the values array is single dimensional we have |
||
153 | // an array of keys with no aditional pivot data. sync those. |
||
154 | if (empty($relationValues)) { |
||
155 | $relationValues = array_values($values); |
||
156 | } |
||
157 | if ($item->{$relationMethod}->count() > 0 && is_multidimensional_array($values)) { |
||
158 | // get the key name of the pivot table (usually id, but could be something else if the dev has set it in the model |
||
159 | $keyName = $item->{$relationMethod}[0]->pivot->getKeyName(); |
||
160 | $items = $item->{$relationMethod}()->withPivot($keyName)->get(); |
||
161 | $items->each(function ($item) use (&$relationValues, $keyName) { |
||
162 | if ($item->pivot) { |
||
163 | $keys = array_column($relationValues, $keyName); |
||
164 | $key = $item->pivot->{$keyName}; |
||
165 | if (! in_array((int) $key, $keys)) { |
||
166 | $item->pivot->delete(); |
||
167 | } else { |
||
168 | $index = array_search($key, $keys); |
||
169 | $item->pivot->update($relationValues[$index]); |
||
170 | unset($relationValues[$index]); |
||
171 | $relationValues = array_values($relationValues); |
||
172 | } |
||
173 | } |
||
174 | }); |
||
175 | $item->{$relationMethod}()->attach($relationValues); |
||
176 | } else { |
||
177 | $item->{$relationMethod}()->sync($relationValues); |
||
178 | } |
||
179 | $item->refresh(); |
||
180 | break; |
||
181 | } |
||
182 | } |
||
183 | } |
||
184 | |||
185 | /** |
||
186 | * Save the attributes of a given HasOne or MorphOne relationship on the |
||
187 | * related entry, create or delete it, depending on what was sent in the form. |
||
188 | * |
||
189 | * For HasOne and MorphOne relationships, the dev might want to a few different things: |
||
190 | * (A) save an attribute on the related entry (eg. passport.number) |
||
191 | * (B) set an attribute on the related entry to NULL (eg. slug.slug) |
||
192 | * (C) save an entire related entry (eg. passport) |
||
193 | * (D) delete the entire related entry (eg. passport) |
||
194 | * |
||
195 | * @param \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation |
||
196 | * @param string $relationMethod The name of the relationship method on the main Model. |
||
197 | * @param array $relationDetails Details about that relationship. For example: |
||
198 | * [ |
||
199 | * 'model' => 'App\Models\Passport', |
||
200 | * 'parent' => 'App\Models\Pet', |
||
201 | * 'entity' => 'passport', |
||
202 | * 'attribute' => 'passport', |
||
203 | * 'values' => **THE TRICKY BIT**, |
||
204 | * ] |
||
205 | * @return Model|null |
||
206 | */ |
||
207 | private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails) |
||
208 | { |
||
209 | // Let's see which scenario we're treating, depending on the contents of $relationDetails: |
||
210 | // - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field) |
||
211 | // - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared) |
||
212 | // - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field) |
||
213 | // - (D) ['passport' => null] (if deleted from the repeatable field) |
||
214 | |||
215 | // Scenario C or D |
||
216 | if (array_key_exists($relationMethod, $relationDetails['values'])) { |
||
217 | $relationMethodValue = $relationDetails['values'][$relationMethod]; |
||
218 | |||
219 | // Scenario D |
||
220 | if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) { |
||
221 | $relation->first()?->delete(); |
||
222 | |||
223 | return null; |
||
224 | } |
||
225 | |||
226 | // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field) |
||
227 | if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) { |
||
228 | $relationMethodValue = $relationMethodValue[0]; |
||
229 | } |
||
230 | } |
||
231 | // saving process |
||
232 | $input = $relationMethodValue ?? $relationDetails['values']; |
||
233 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod); |
||
234 | |||
235 | $item = $relation->updateOrCreate([], $directInputs); |
||
236 | |||
237 | $this->createRelationsForItem($item, $relationInputs); |
||
238 | |||
239 | return $item; |
||
240 | } |
||
241 | |||
242 | /** |
||
243 | * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations. |
||
244 | * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it. |
||
245 | * Here we add the entries that developer added and remove the ones that are not in the list. |
||
246 | * This removal process happens with the following rules: |
||
247 | * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones. |
||
248 | * - `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. |
||
249 | * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us. |
||
250 | * |
||
251 | * @return mixed |
||
252 | */ |
||
253 | private function attachManyRelation($item, $relation, $relationDetails, $relationValues) |
||
288 | } |
||
289 | |||
290 | private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey) |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Handle HasMany/MorphMany relations when used as creatable entries in the crud. |
||
329 | * By using repeatable field, developer can allow the creation of such entries |
||
330 | * in the crud forms. |
||
331 | * |
||
332 | * @param $entry - eg: story |
||
333 | * @param $relation - eg story HasMany monsters |
||
334 | * @param $relationMethod - eg: monsters |
||
335 | * @param $relationDetails - eg: info about relation including submited values |
||
336 | * @return void |
||
337 | */ |
||
338 | private function createManyEntries($entry, $relation, $relationMethod, $relationDetails) |
||
367 | } |
||
368 | } |
||
370 |