Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Passed
Pull Request — main (#5535)
by
unknown
19:17 queued 04:18
created

Create::handleManyRelationItemRemoval()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 35
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 6
nop 4
dl 0
loc 35
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Facades\DB;
8
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);
0 ignored issues
show
Bug introduced by
It seems like splitInputIntoDirectAndRelations() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

25
        /** @scrutinizer ignore-call */ 
26
        [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input);
Loading history...
26
27
        if ($this->get('create.useDatabaseTransactions') ?? config('backpack.base.useDatabaseTransactions', false)) {
0 ignored issues
show
Bug introduced by
It seems like get() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

27
        if ($this->/** @scrutinizer ignore-call */ get('create.useDatabaseTransactions') ?? config('backpack.base.useDatabaseTransactions', false)) {
Loading history...
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()
48
    {
49
        return $this->fields();
0 ignored issues
show
Bug introduced by
It seems like fields() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

49
        return $this->/** @scrutinizer ignore-call */ fields();
Loading history...
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();
0 ignored issues
show
Bug introduced by
It seems like getCleanStateFields() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
            /** @scrutinizer ignore-call */ 
62
            $fields = $this->getCleanStateFields();
Loading history...
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']) &&
0 ignored issues
show
Bug introduced by
It seems like holdsMultipleInputs() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

75
            if ($this->/** @scrutinizer ignore-call */ holdsMultipleInputs($field['name']) &&
Loading history...
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
                                $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)
254
    {
255
        $modelInstance = $relation->getRelated();
256
        $relationForeignKey = $relation->getForeignKeyName();
257
        $relationLocalKey = $relation->getLocalKeyName();
258
259
        if (empty($relationValues)) {
260
            // the developer cleared the selection
261
            // we gonna clear all related values by setting up the value to the fallback id, to null or delete.
262
            return $this->handleManyRelationItemRemoval($modelInstance, $relation, $relationDetails, $relationForeignKey);
263
        }
264
        // we add the new values into the relation, if it is HasMany we only update the foreign_key,
265
        // otherwise (it's a MorphMany) we need to update the morphs keys too
266
        $toUpdate[$relationForeignKey] = $item->{$relationLocalKey};
0 ignored issues
show
Comprehensibility Best Practice introduced by
$toUpdate was never initialized. Although not strictly required by PHP, it is generally a good practice to add $toUpdate = array(); before regardless.
Loading history...
267
268
        if ($relationDetails['relation_type'] === 'MorphMany') {
269
            $toUpdate[$relation->getQualifiedMorphType()] = $relation->getMorphClass();
270
        }
271
272
        $modelInstance->whereIn($modelInstance->getKeyName(), $relationValues)
273
            ->update($toUpdate);
274
275
        // we clear up any values that were removed from model relation.
276
        // if developer provided a fallback id, we use it
277
        // if column is nullable we set it to null if developer didn't specify `force_delete => true`
278
        // if none of the above we delete the model from database
279
        $removedEntries = $modelInstance->whereNotIn($modelInstance->getKeyName(), $relationValues)
280
                            ->where($relationForeignKey, $item->{$relationLocalKey});
281
282
        // if relation is MorphMany we also match by morph type.
283
        if ($relationDetails['relation_type'] === 'MorphMany') {
284
            $removedEntries->where($relation->getQualifiedMorphType(), $relation->getMorphClass());
285
        }
286
287
        return $this->handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey);
288
    }
289
290
    private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey)
291
    {
292
        $relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey);
293
        $forceDelete = $relationDetails['force_delete'] ?? false;
294
        $fallbackId = $relationDetails['fallback_id'] ?? false;
295
296
        // developer provided a fallback_id he knows what he's doing, just use it.
297
        if ($fallbackId) {
298
            return $removedEntries->update([$relationForeignKey => $fallbackId]);
299
        }
300
301
        // developer set force_delete => true, so we don't care if it's nullable or not,
302
        // we just follow developer's will
303
        if ($forceDelete) {
304
            return $removedEntries->lazy()->each->delete();
305
        }
306
307
        // get the default that could be set at database level.
308
        $dbColumnDefault = $modelInstance->getDbColumnDefault($relationForeignKey);
309
310
        // check if the relation foreign key is in casts, and cast it to the correct type
311
        if ($modelInstance->hasCast($relationForeignKey)) {
312
            $dbColumnDefault = match ($modelInstance->getCasts()[$relationForeignKey]) {
313
                'int', 'integer' => $dbColumnDefault = (int) $dbColumnDefault,
314
                default => $dbColumnDefault = $dbColumnDefault
0 ignored issues
show
Unused Code introduced by
The assignment to $dbColumnDefault is dead and can be removed.
Loading history...
315
            };
316
        }
317
        // if column is not nullable in database, and there is no column default (null),
318
        // we will delete the entry from the database, otherwise it will throw and ugly DB error.
319
        if (! $relationColumnIsNullable && $dbColumnDefault === null) {
320
            return $removedEntries->lazy()->each->delete();
321
        }
322
323
        // if column is nullable we just set it to the column default (null when it does exist, or the default value when it does).
324
        return $removedEntries->update([$relationForeignKey => $dbColumnDefault]);
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
0 ignored issues
show
Documentation Bug introduced by
The doc comment - at position 0 could not be parsed: Unknown type name '-' at position 0 in -.
Loading history...
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)
339
    {
340
        $items = $relationDetails['values'][$relationMethod];
341
342
        $relatedModelLocalKey = $relation->getRelated()->getKeyName();
343
344
        $relatedItemsSent = [];
345
346
        foreach ($items as $item) {
347
            [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($item, $relationDetails, $relationMethod);
348
            // for each item we get the inputs to create and the relations of it.
349
            $relatedModelLocalKeyValue = $item[$relatedModelLocalKey] ?? null;
350
351
            // we either find the matched entry by local_key (usually `id`)
352
            // and update the values from the input
353
            // or create a new item from input
354
            $item = $entry->{$relationMethod}()->updateOrCreate([$relatedModelLocalKey => $relatedModelLocalKeyValue], $directInputs);
355
356
            // we store the item local key so we can match them with database and check if any item was deleted
357
            $relatedItemsSent[] = $item->{$relatedModelLocalKey};
358
359
            // create the item relations if any.
360
            $this->createRelationsForItem($item, $relationInputs);
361
        }
362
363
        // use the collection of sent ids to match against database ids, delete the ones not found in the submitted ids.
364
        if (! empty($relatedItemsSent)) {
365
            // we perform the cleanup of removed database items
366
            $entry->{$relationMethod}()->whereNotIn($relatedModelLocalKey, $relatedItemsSent)->lazy()->each->delete();
367
        }
368
    }
369
}
370