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 (#5538)
by Pedro
16:57 queued 02:10
created

Create::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
rs 10
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\Database\Eloquent\Relations\BelongsToMany;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Facades\DB;
9
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);
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

26
        /** @scrutinizer ignore-call */ 
27
        [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input);
Loading history...
27
28
        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

28
        if ($this->/** @scrutinizer ignore-call */ get('create.useDatabaseTransactions') ?? config('backpack.base.useDatabaseTransactions', false)) {
Loading history...
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()
49
    {
50
        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

50
        return $this->/** @scrutinizer ignore-call */ fields();
Loading history...
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();
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

62
            /** @scrutinizer ignore-call */ 
63
            $fields = $this->getCleanStateFields();
Loading history...
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']) &&
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

76
            if ($this->/** @scrutinizer ignore-call */ holdsMultipleInputs($field['name']) &&
Loading history...
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
    {
189
        $attributes[$relation->getForeignPivotKeyName()] = $relatedItemKey;
190
        $attributes[$relation->getRelatedPivotKeyName()] = $attributes[$relation->getRelationName()];
191
        $pivotKeyName = $attributes['pivot_key_name'] ?? 'id';
192
193
        return Arr::except($attributes, [$relation->getRelationName(), 'pivot_key_name', $pivotKeyName]);
194
    }
195
196
    private function preparePivotAttributesForUpdate(array $attributes, BelongsToMany $relation)
197
    {
198
        $pivotKeyName = $attributes['pivot_key_name'] ?? 'id';
199
        $attributes[$relation->getRelatedPivotKeyName()] = $attributes[$relation->getRelationName()];
200
201
        return Arr::except($attributes, [$relation->getRelationName(), 'pivot_key_name', $pivotKeyName, $relation->getForeignPivotKeyName()]);
202
    }
203
204
    /**
205
     * Save the attributes of a given HasOne or MorphOne relationship on the
206
     * related entry, create or delete it, depending on what was sent in the form.
207
     *
208
     * For HasOne and MorphOne relationships, the dev might want to a few different things:
209
     * (A) save an attribute on the related entry (eg. passport.number)
210
     * (B) set an attribute on the related entry to NULL (eg. slug.slug)
211
     * (C) save an entire related entry (eg. passport)
212
     * (D) delete the entire related entry (eg. passport)
213
     *
214
     * @param  \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne  $relation
215
     * @param  string  $relationMethod  The name of the relationship method on the main Model.
216
     * @param  array  $relationDetails  Details about that relationship. For example:
217
     *                                  [
218
     *                                  'model' => 'App\Models\Passport',
219
     *                                  'parent' => 'App\Models\Pet',
220
     *                                  'entity' => 'passport',
221
     *                                  'attribute' => 'passport',
222
     *                                  'values' => **THE TRICKY BIT**,
223
     *                                  ]
224
     * @return Model|null
225
     */
226
    private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails)
227
    {
228
        // Let's see which scenario we're treating, depending on the contents of $relationDetails:
229
        //      - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field)
230
        //      - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared)
231
        //      - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field)
232
        //      - (D) ['passport' => null] (if deleted from the repeatable field)
233
234
        // Scenario C or D
235
        if (array_key_exists($relationMethod, $relationDetails['values'])) {
236
            $relationMethodValue = $relationDetails['values'][$relationMethod];
237
238
            // Scenario D
239
            if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) {
240
                $relation->first()?->delete();
241
242
                return null;
243
            }
244
245
            // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field)
246
            if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) {
247
                $relationMethodValue = $relationMethodValue[0];
248
            }
249
        }
250
        // saving process
251
        $input = $relationMethodValue ?? $relationDetails['values'];
252
        [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod);
253
254
        $item = $relation->updateOrCreate([], $directInputs);
255
256
        $this->createRelationsForItem($item, $relationInputs);
257
258
        return $item;
259
    }
260
261
    /**
262
     * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations.
263
     * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it.
264
     * Here we add the entries that developer added and remove the ones that are not in the list.
265
     * This removal process happens with the following rules:
266
     * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones.
267
     * - `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.
268
     * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us.
269
     *
270
     * @return mixed
271
     */
272
    private function attachManyRelation($item, $relation, $relationDetails, $relationValues)
273
    {
274
        $modelInstance = $relation->getRelated();
275
        $relationForeignKey = $relation->getForeignKeyName();
276
        $relationLocalKey = $relation->getLocalKeyName();
277
278
        if (empty($relationValues)) {
279
            // the developer cleared the selection
280
            // we gonna clear all related values by setting up the value to the fallback id, to null or delete.
281
            return $this->handleManyRelationItemRemoval($modelInstance, $relation, $relationDetails, $relationForeignKey);
282
        }
283
        // we add the new values into the relation, if it is HasMany we only update the foreign_key,
284
        // otherwise (it's a MorphMany) we need to update the morphs keys too
285
        $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...
286
287
        if ($relationDetails['relation_type'] === 'MorphMany') {
288
            $toUpdate[$relation->getQualifiedMorphType()] = $relation->getMorphClass();
289
        }
290
291
        $modelInstance->whereIn($modelInstance->getKeyName(), $relationValues)
292
            ->update($toUpdate);
293
294
        // we clear up any values that were removed from model relation.
295
        // if developer provided a fallback id, we use it
296
        // if column is nullable we set it to null if developer didn't specify `force_delete => true`
297
        // if none of the above we delete the model from database
298
        $removedEntries = $modelInstance->whereNotIn($modelInstance->getKeyName(), $relationValues)
299
                            ->where($relationForeignKey, $item->{$relationLocalKey});
300
301
        // if relation is MorphMany we also match by morph type.
302
        if ($relationDetails['relation_type'] === 'MorphMany') {
303
            $removedEntries->where($relation->getQualifiedMorphType(), $relation->getMorphClass());
304
        }
305
306
        return $this->handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey);
307
    }
308
309
    private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey)
310
    {
311
        $relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey);
312
        $forceDelete = $relationDetails['force_delete'] ?? false;
313
        $fallbackId = $relationDetails['fallback_id'] ?? false;
314
315
        // developer provided a fallback_id he knows what he's doing, just use it.
316
        if ($fallbackId) {
317
            return $removedEntries->update([$relationForeignKey => $fallbackId]);
318
        }
319
320
        // developer set force_delete => true, so we don't care if it's nullable or not,
321
        // we just follow developer's will
322
        if ($forceDelete) {
323
            return $removedEntries->lazy()->each->delete();
324
        }
325
326
        // get the default that could be set at database level.
327
        $dbColumnDefault = $modelInstance->getDbColumnDefault($relationForeignKey);
328
329
        // check if the relation foreign key is in casts, and cast it to the correct type
330
        if ($modelInstance->hasCast($relationForeignKey)) {
331
            $dbColumnDefault = match ($modelInstance->getCasts()[$relationForeignKey]) {
332
                'int', 'integer' => $dbColumnDefault = (int) $dbColumnDefault,
333
                default => $dbColumnDefault = $dbColumnDefault
0 ignored issues
show
Unused Code introduced by
The assignment to $dbColumnDefault is dead and can be removed.
Loading history...
334
            };
335
        }
336
        // if column is not nullable in database, and there is no column default (null),
337
        // we will delete the entry from the database, otherwise it will throw and ugly DB error.
338
        if (! $relationColumnIsNullable && $dbColumnDefault === null) {
339
            return $removedEntries->lazy()->each->delete();
340
        }
341
342
        // if column is nullable we just set it to the column default (null when it does exist, or the default value when it does).
343
        return $removedEntries->update([$relationForeignKey => $dbColumnDefault]);
344
    }
345
346
    /**
347
     * Handle HasMany/MorphMany relations when used as creatable entries in the crud.
348
     * By using repeatable field, developer can allow the creation of such entries
349
     * in the crud forms.
350
     *
351
     * @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...
352
     * @param  $relation  - eg  story HasMany monsters
353
     * @param  $relationMethod  - eg: monsters
354
     * @param  $relationDetails  - eg: info about relation including submited values
355
     * @return void
356
     */
357
    private function createManyEntries($entry, $relation, $relationMethod, $relationDetails)
358
    {
359
        $items = $relationDetails['values'][$relationMethod];
360
361
        $relatedModelLocalKey = $relation->getRelated()->getKeyName();
362
363
        $relatedItemsSent = [];
364
365
        foreach ($items as $item) {
366
            [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($item, $relationDetails, $relationMethod);
367
            // for each item we get the inputs to create and the relations of it.
368
            $relatedModelLocalKeyValue = $item[$relatedModelLocalKey] ?? null;
369
370
            // we either find the matched entry by local_key (usually `id`)
371
            // and update the values from the input
372
            // or create a new item from input
373
            $item = $entry->{$relationMethod}()->updateOrCreate([$relatedModelLocalKey => $relatedModelLocalKeyValue], $directInputs);
374
375
            // we store the item local key so we can match them with database and check if any item was deleted
376
            $relatedItemsSent[] = $item->{$relatedModelLocalKey};
377
378
            // create the item relations if any.
379
            $this->createRelationsForItem($item, $relationInputs);
380
        }
381
382
        // use the collection of sent ids to match against database ids, delete the ones not found in the submitted ids.
383
        if (! empty($relatedItemsSent)) {
384
            // we perform the cleanup of removed database items
385
            $entry->{$relationMethod}()->whereNotIn($relatedModelLocalKey, $relatedItemsSent)->lazy()->each->delete();
386
        }
387
    }
388
}
389