We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
Total Complexity | 52 |
Total Lines | 335 |
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') ?? 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 = []) |
||
59 | { |
||
60 | if (empty($fields)) { |
||
61 | $fields = $this->getCleanStateFields(); |
||
62 | } |
||
63 | |||
64 | $relationFields = []; |
||
65 | |||
66 | foreach ($fields as $field) { |
||
67 | if (isset($field['model']) && $field['model'] !== false && $field['entity'] !== false) { |
||
68 | array_push($relationFields, $field); |
||
69 | } |
||
70 | |||
71 | // if a field has an array name AND subfields |
||
72 | // then take those fields into account (check if they have relationships); |
||
73 | // this is done in particular for the checklist_dependency field, |
||
74 | // but other fields could use it too, in the future; |
||
75 | if ($this->holdsMultipleInputs($field['name']) && |
||
76 | isset($field['subfields']) && |
||
77 | is_array($field['subfields'])) { |
||
78 | foreach ($field['subfields'] as $subfield) { |
||
79 | if (isset($subfield['model']) && $subfield['model'] !== false) { |
||
80 | array_push($relationFields, $subfield); |
||
81 | } |
||
82 | } |
||
83 | } |
||
84 | } |
||
85 | |||
86 | return $relationFields; |
||
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 | $relationValues[$value[$relationMethod]] = Arr::except($value, $relationMethod); |
||
146 | } |
||
147 | } |
||
148 | } |
||
149 | |||
150 | // if there is no relation data, and the values array is single dimensional we have |
||
151 | // an array of keys with no aditional pivot data. sync those. |
||
152 | if (empty($relationValues)) { |
||
153 | $relationValues = array_values($values); |
||
154 | } |
||
155 | |||
156 | $item->{$relationMethod}()->sync($relationValues); |
||
157 | break; |
||
158 | } |
||
159 | } |
||
160 | } |
||
161 | |||
162 | /** |
||
163 | * Save the attributes of a given HasOne or MorphOne relationship on the |
||
164 | * related entry, create or delete it, depending on what was sent in the form. |
||
165 | * |
||
166 | * For HasOne and MorphOne relationships, the dev might want to a few different things: |
||
167 | * (A) save an attribute on the related entry (eg. passport.number) |
||
168 | * (B) set an attribute on the related entry to NULL (eg. slug.slug) |
||
169 | * (C) save an entire related entry (eg. passport) |
||
170 | * (D) delete the entire related entry (eg. passport) |
||
171 | * |
||
172 | * @param \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation |
||
173 | * @param string $relationMethod The name of the relationship method on the main Model. |
||
174 | * @param array $relationDetails Details about that relationship. For example: |
||
175 | * [ |
||
176 | * 'model' => 'App\Models\Passport', |
||
177 | * 'parent' => 'App\Models\Pet', |
||
178 | * 'entity' => 'passport', |
||
179 | * 'attribute' => 'passport', |
||
180 | * 'values' => **THE TRICKY BIT**, |
||
181 | * ] |
||
182 | * @return Model|null |
||
183 | */ |
||
184 | private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails) |
||
185 | { |
||
186 | // Let's see which scenario we're treating, depending on the contents of $relationDetails: |
||
187 | // - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field) |
||
188 | // - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared) |
||
189 | // - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field) |
||
190 | // - (D) ['passport' => null] (if deleted from the repeatable field) |
||
191 | |||
192 | // Scenario C or D |
||
193 | if (array_key_exists($relationMethod, $relationDetails['values'])) { |
||
194 | $relationMethodValue = $relationDetails['values'][$relationMethod]; |
||
195 | |||
196 | // Scenario D |
||
197 | if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) { |
||
198 | $relation->first()?->delete(); |
||
199 | |||
200 | return null; |
||
201 | } |
||
202 | |||
203 | // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field) |
||
204 | if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) { |
||
205 | $relationMethodValue = $relationMethodValue[0]; |
||
206 | } |
||
207 | } |
||
208 | // saving process |
||
209 | $input = $relationMethodValue ?? $relationDetails['values']; |
||
210 | [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod); |
||
211 | |||
212 | $item = $relation->updateOrCreate([], $directInputs); |
||
213 | |||
214 | $this->createRelationsForItem($item, $relationInputs); |
||
215 | |||
216 | return $item; |
||
217 | } |
||
218 | |||
219 | /** |
||
220 | * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations. |
||
221 | * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it. |
||
222 | * Here we add the entries that developer added and remove the ones that are not in the list. |
||
223 | * This removal process happens with the following rules: |
||
224 | * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones. |
||
225 | * - `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. |
||
226 | * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us. |
||
227 | * |
||
228 | * @return mixed |
||
229 | */ |
||
230 | private function attachManyRelation($item, $relation, $relationDetails, $relationValues) |
||
265 | } |
||
266 | |||
267 | private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey) |
||
268 | { |
||
269 | $relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey); |
||
302 | } |
||
303 | |||
304 | /** |
||
305 | * Handle HasMany/MorphMany relations when used as creatable entries in the crud. |
||
306 | * By using repeatable field, developer can allow the creation of such entries |
||
307 | * in the crud forms. |
||
308 | * |
||
309 | * @param $entry - eg: story |
||
310 | * @param $relation - eg story HasMany monsters |
||
311 | * @param $relationMethod - eg: monsters |
||
312 | * @param $relationDetails - eg: info about relation including submited values |
||
313 | * @return void |
||
314 | */ |
||
315 | private function createManyEntries($entry, $relation, $relationMethod, $relationDetails) |
||
347 |