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
Push — belongs-to-many-save-duplicate... ( ca7a94 )
by Pedro
12:45
created

Create::preparePivotAttributesForCreate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
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
        $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)
269
    {
270
        $modelInstance = $relation->getRelated();
271
        $relationForeignKey = $relation->getForeignKeyName();
272
        $relationLocalKey = $relation->getLocalKeyName();
273
274
        if (empty($relationValues)) {
275
            // the developer cleared the selection
276
            // we gonna clear all related values by setting up the value to the fallback id, to null or delete.
277
            return $this->handleManyRelationItemRemoval($modelInstance, $relation, $relationDetails, $relationForeignKey);
278
        }
279
        // we add the new values into the relation, if it is HasMany we only update the foreign_key,
280
        // otherwise (it's a MorphMany) we need to update the morphs keys too
281
        $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...
282
283
        if ($relationDetails['relation_type'] === 'MorphMany') {
284
            $toUpdate[$relation->getQualifiedMorphType()] = $relation->getMorphClass();
285
        }
286
287
        $modelInstance->whereIn($modelInstance->getKeyName(), $relationValues)
288
            ->update($toUpdate);
289
290
        // we clear up any values that were removed from model relation.
291
        // if developer provided a fallback id, we use it
292
        // if column is nullable we set it to null if developer didn't specify `force_delete => true`
293
        // if none of the above we delete the model from database
294
        $removedEntries = $modelInstance->whereNotIn($modelInstance->getKeyName(), $relationValues)
295
                            ->where($relationForeignKey, $item->{$relationLocalKey});
296
297
        // if relation is MorphMany we also match by morph type.
298
        if ($relationDetails['relation_type'] === 'MorphMany') {
299
            $removedEntries->where($relation->getQualifiedMorphType(), $relation->getMorphClass());
300
        }
301
302
        return $this->handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey);
303
    }
304
305
    private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey)
306
    {
307
        $relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey);
308
        $forceDelete = $relationDetails['force_delete'] ?? false;
309
        $fallbackId = $relationDetails['fallback_id'] ?? false;
310
311
        // developer provided a fallback_id he knows what he's doing, just use it.
312
        if ($fallbackId) {
313
            return $removedEntries->update([$relationForeignKey => $fallbackId]);
314
        }
315
316
        // developer set force_delete => true, so we don't care if it's nullable or not,
317
        // we just follow developer's will
318
        if ($forceDelete) {
319
            return $removedEntries->lazy()->each->delete();
320
        }
321
322
        // get the default that could be set at database level.
323
        $dbColumnDefault = $modelInstance->getDbColumnDefault($relationForeignKey);
324
325
        // check if the relation foreign key is in casts, and cast it to the correct type
326
        if ($modelInstance->hasCast($relationForeignKey)) {
327
            $dbColumnDefault = match ($modelInstance->getCasts()[$relationForeignKey]) {
328
                'int', 'integer' => $dbColumnDefault = (int) $dbColumnDefault,
329
                default => $dbColumnDefault = $dbColumnDefault
0 ignored issues
show
Unused Code introduced by
The assignment to $dbColumnDefault is dead and can be removed.
Loading history...
330
            };
331
        }
332
        // if column is not nullable in database, and there is no column default (null),
333
        // we will delete the entry from the database, otherwise it will throw and ugly DB error.
334
        if (! $relationColumnIsNullable && $dbColumnDefault === null) {
335
            return $removedEntries->lazy()->each->delete();
336
        }
337
338
        // if column is nullable we just set it to the column default (null when it does exist, or the default value when it does).
339
        return $removedEntries->update([$relationForeignKey => $dbColumnDefault]);
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
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...
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)
354
    {
355
        $items = $relationDetails['values'][$relationMethod];
356
357
        $relatedModelLocalKey = $relation->getRelated()->getKeyName();
358
359
        $relatedItemsSent = [];
360
361
        foreach ($items as $item) {
362
            [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($item, $relationDetails, $relationMethod);
363
            // for each item we get the inputs to create and the relations of it.
364
            $relatedModelLocalKeyValue = $item[$relatedModelLocalKey] ?? null;
365
366
            // we either find the matched entry by local_key (usually `id`)
367
            // and update the values from the input
368
            // or create a new item from input
369
            $item = $entry->{$relationMethod}()->updateOrCreate([$relatedModelLocalKey => $relatedModelLocalKeyValue], $directInputs);
370
371
            // we store the item local key so we can match them with database and check if any item was deleted
372
            $relatedItemsSent[] = $item->{$relatedModelLocalKey};
373
374
            // create the item relations if any.
375
            $this->createRelationsForItem($item, $relationInputs);
376
        }
377
378
        // use the collection of sent ids to match against database ids, delete the ones not found in the submitted ids.
379
        if (! empty($relatedItemsSent)) {
380
            // we perform the cleanup of removed database items
381
            $entry->{$relationMethod}()->whereNotIn($relatedModelLocalKey, $relatedItemsSent)->lazy()->each->delete();
382
        }
383
    }
384
}
385