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