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 — use-db-transactions ( f233f9 )
by Pedro
31:23
created

Create::attachManyRelation()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 35
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
c 0
b 0
f 0
nc 5
nop 4
dl 0
loc 35
rs 9.7666
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')) {
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')) {
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
        $item = $this->model->create($directInputs);
36
        $this->createRelationsForItem($item, $relationInputs);
37
        return $item;
38
    }
39
40
    /**
41
     * Get all fields needed for the ADD NEW ENTRY form.
42
     *
43
     * @return array The fields with attributes and fake attributes.
44
     */
45
    public function getCreateFields()
46
    {
47
        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

47
        return $this->/** @scrutinizer ignore-call */ fields();
Loading history...
48
    }
49
50
    /**
51
     * Get all fields with relation set (model key set on field).
52
     *
53
     * @param  array  $fields
54
     * @return array The fields with model key set.
55
     */
56
    public function getRelationFields($fields = [])
57
    {
58
        if (empty($fields)) {
59
            $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

59
            /** @scrutinizer ignore-call */ 
60
            $fields = $this->getCleanStateFields();
Loading history...
60
        }
61
62
        $relationFields = [];
63
64
        foreach ($fields as $field) {
65
            if (isset($field['model']) && $field['model'] !== false && $field['entity'] !== false) {
66
                array_push($relationFields, $field);
67
            }
68
69
            // if a field has an array name AND subfields
70
            // then take those fields into account (check if they have relationships);
71
            // this is done in particular for the checklist_dependency field,
72
            // but other fields could use it too, in the future;
73
            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

73
            if ($this->/** @scrutinizer ignore-call */ holdsMultipleInputs($field['name']) &&
Loading history...
74
                isset($field['subfields']) &&
75
                is_array($field['subfields'])) {
76
                foreach ($field['subfields'] as $subfield) {
77
                    if (isset($subfield['model']) && $subfield['model'] !== false) {
78
                        array_push($relationFields, $subfield);
79
                    }
80
                }
81
            }
82
        }
83
84
        return $relationFields;
85
    }
86
87
    /**
88
     * ---------------
89
     * PRIVATE METHODS
90
     * ---------------.
91
     */
92
93
    /**
94
     * Create relations for the provided model.
95
     *
96
     * @param  \Illuminate\Database\Eloquent\Model  $item  The current CRUD model.
97
     * @param  array  $formattedRelations  The form data.
98
     * @return bool|null
99
     */
100
    private function createRelationsForItem($item, $formattedRelations)
101
    {
102
        // no relations to create
103
        if (empty($formattedRelations)) {
104
            return false;
105
        }
106
107
        foreach ($formattedRelations as $relationMethod => $relationDetails) {
108
            $relation = $item->{$relationMethod}();
109
            $relationType = $relationDetails['relation_type'];
110
111
            switch ($relationType) {
112
                case 'HasOne':
113
                case 'MorphOne':
114
                    $this->createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails);
115
                    break;
116
                case 'HasMany':
117
                case 'MorphMany':
118
                    $relationValues = $relationDetails['values'][$relationMethod];
119
                    // if relation values are null we can only attach, also we check if we sent
120
                    // - a single dimensional array: [1,2,3]
121
                    // - an array of arrays: [[1][2][3]]
122
                    // if is as single dimensional array we can only attach.
123
                    if ($relationValues === null || ! is_multidimensional_array($relationValues)) {
124
                        $this->attachManyRelation($item, $relation, $relationDetails, $relationValues);
125
                    } else {
126
                        $this->createManyEntries($item, $relation, $relationMethod, $relationDetails);
127
                    }
128
                    break;
129
                case 'BelongsToMany':
130
                case 'MorphToMany':
131
                    $values = $relationDetails['values'][$relationMethod] ?? [];
132
                    $values = is_string($values) ? json_decode($values, true) : $values;
133
134
                    // disabling ConvertEmptyStringsToNull middleware may return null from json_decode() if an empty string is used.
135
                    // we need to make sure no null value can go foward so we reassure that values is not null after json_decode()
136
                    $values = $values ?? [];
137
138
                    $relationValues = [];
139
140
                    if (is_array($values) && is_multidimensional_array($values)) {
141
                        foreach ($values as $value) {
142
                            if (isset($value[$relationMethod])) {
143
                                $relationValues[$value[$relationMethod]] = Arr::except($value, $relationMethod);
144
                            }
145
                        }
146
                    }
147
148
                    // if there is no relation data, and the values array is single dimensional we have
149
                    // an array of keys with no aditional pivot data. sync those.
150
                    if (empty($relationValues)) {
151
                        $relationValues = array_values($values);
152
                    }
153
154
                    $item->{$relationMethod}()->sync($relationValues);
155
                    break;
156
            }
157
        }
158
    }
159
160
    /**
161
     * Save the attributes of a given HasOne or MorphOne relationship on the
162
     * related entry, create or delete it, depending on what was sent in the form.
163
     *
164
     * For HasOne and MorphOne relationships, the dev might want to a few different things:
165
     * (A) save an attribute on the related entry (eg. passport.number)
166
     * (B) set an attribute on the related entry to NULL (eg. slug.slug)
167
     * (C) save an entire related entry (eg. passport)
168
     * (D) delete the entire related entry (eg. passport)
169
     *
170
     * @param  \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne  $relation
171
     * @param  string  $relationMethod  The name of the relationship method on the main Model.
172
     * @param  array  $relationDetails  Details about that relationship. For example:
173
     *                                  [
174
     *                                  'model' => 'App\Models\Passport',
175
     *                                  'parent' => 'App\Models\Pet',
176
     *                                  'entity' => 'passport',
177
     *                                  'attribute' => 'passport',
178
     *                                  'values' => **THE TRICKY BIT**,
179
     *                                  ]
180
     * @return Model|null
181
     */
182
    private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails)
183
    {
184
        // Let's see which scenario we're treating, depending on the contents of $relationDetails:
185
        //      - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field)
186
        //      - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared)
187
        //      - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field)
188
        //      - (D) ['passport' => null] (if deleted from the repeatable field)
189
190
        // Scenario C or D
191
        if (array_key_exists($relationMethod, $relationDetails['values'])) {
192
            $relationMethodValue = $relationDetails['values'][$relationMethod];
193
194
            // Scenario D
195
            if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) {
196
                $relation->first()?->delete();
197
198
                return null;
199
            }
200
201
            // Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field)
202
            if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) {
203
                $relationMethodValue = $relationMethodValue[0];
204
            }
205
        }
206
        // saving process
207
        $input = $relationMethodValue ?? $relationDetails['values'];
208
        [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod);
209
210
        $item = $relation->updateOrCreate([], $directInputs);
211
212
        $this->createRelationsForItem($item, $relationInputs);
213
214
        return $item;
215
    }
216
217
    /**
218
     * When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations.
219
     * Since HasMany/MorphMany does not have the `sync` method, we manually re-create it.
220
     * Here we add the entries that developer added and remove the ones that are not in the list.
221
     * This removal process happens with the following rules:
222
     * - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones.
223
     * - `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.
224
     * - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us.
225
     *
226
     * @return mixed
227
     */
228
    private function attachManyRelation($item, $relation, $relationDetails, $relationValues)
229
    {
230
        $modelInstance = $relation->getRelated();
231
        $relationForeignKey = $relation->getForeignKeyName();
232
        $relationLocalKey = $relation->getLocalKeyName();
233
234
        if (empty($relationValues)) {
235
            // the developer cleared the selection
236
            // we gonna clear all related values by setting up the value to the fallback id, to null or delete.
237
            return $this->handleManyRelationItemRemoval($modelInstance, $relation, $relationDetails, $relationForeignKey);
238
        }
239
        // we add the new values into the relation, if it is HasMany we only update the foreign_key,
240
        // otherwise (it's a MorphMany) we need to update the morphs keys too
241
        $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...
242
243
        if ($relationDetails['relation_type'] === 'MorphMany') {
244
            $toUpdate[$relation->getQualifiedMorphType()] = $relation->getMorphClass();
245
        }
246
247
        $modelInstance->whereIn($modelInstance->getKeyName(), $relationValues)
248
            ->update($toUpdate);
249
250
        // we clear up any values that were removed from model relation.
251
        // if developer provided a fallback id, we use it
252
        // if column is nullable we set it to null if developer didn't specify `force_delete => true`
253
        // if none of the above we delete the model from database
254
        $removedEntries = $modelInstance->whereNotIn($modelInstance->getKeyName(), $relationValues)
255
                            ->where($relationForeignKey, $item->{$relationLocalKey});
256
257
        // if relation is MorphMany we also match by morph type.
258
        if ($relationDetails['relation_type'] === 'MorphMany') {
259
            $removedEntries->where($relation->getQualifiedMorphType(), $relation->getMorphClass());
260
        }
261
262
        return $this->handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey);
263
    }
264
265
    private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey)
266
    {
267
        $relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey);
268
        $forceDelete = $relationDetails['force_delete'] ?? false;
269
        $fallbackId = $relationDetails['fallback_id'] ?? false;
270
271
        // developer provided a fallback_id he knows what he's doing, just use it.
272
        if ($fallbackId) {
273
            return $removedEntries->update([$relationForeignKey => $fallbackId]);
274
        }
275
276
        // developer set force_delete => true, so we don't care if it's nullable or not,
277
        // we just follow developer's will
278
        if ($forceDelete) {
279
            return $removedEntries->lazy()->each->delete();
280
        }
281
282
        // get the default that could be set at database level.
283
        $dbColumnDefault = $modelInstance->getDbColumnDefault($relationForeignKey);
284
285
        // if column is not nullable in database, and there is no column default (null),
286
        // we will delete the entry from the database, otherwise it will throw and ugly DB error.
287
        if (! $relationColumnIsNullable && $dbColumnDefault === null) {
288
            return $removedEntries->lazy()->each->delete();
289
        }
290
291
        // if column is nullable we just set it to the column default (null when it does exist, or the default value when it does).
292
        return $removedEntries->update([$relationForeignKey => $dbColumnDefault]);
293
    }
294
295
    /**
296
     * Handle HasMany/MorphMany relations when used as creatable entries in the crud.
297
     * By using repeatable field, developer can allow the creation of such entries
298
     * in the crud forms.
299
     *
300
     * @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...
301
     * @param  $relation  - eg  story HasMany monsters
302
     * @param  $relationMethod  - eg: monsters
303
     * @param  $relationDetails  - eg: info about relation including submited values
304
     * @return void
305
     */
306
    private function createManyEntries($entry, $relation, $relationMethod, $relationDetails)
307
    {
308
        $items = $relationDetails['values'][$relationMethod];
309
310
        $relatedModelLocalKey = $relation->getRelated()->getKeyName();
311
312
        $relatedItemsSent = [];
313
314
        foreach ($items as $item) {
315
            [$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($item, $relationDetails, $relationMethod);
316
            // for each item we get the inputs to create and the relations of it.
317
            $relatedModelLocalKeyValue = $item[$relatedModelLocalKey] ?? null;
318
319
            // we either find the matched entry by local_key (usually `id`)
320
            // and update the values from the input
321
            // or create a new item from input
322
            $item = $entry->{$relationMethod}()->updateOrCreate([$relatedModelLocalKey => $relatedModelLocalKeyValue], $directInputs);
323
324
            // we store the item local key so we can match them with database and check if any item was deleted
325
            $relatedItemsSent[] = $item->{$relatedModelLocalKey};
326
327
            // create the item relations if any.
328
            $this->createRelationsForItem($item, $relationInputs);
329
        }
330
331
        // use the collection of sent ids to match against database ids, delete the ones not found in the submitted ids.
332
        if (! empty($relatedItemsSent)) {
333
            // we perform the cleanup of removed database items
334
            $entry->{$relationMethod}()->whereNotIn($relatedModelLocalKey, $relatedItemsSent)->lazy()->each->delete();
335
        }
336
    }
337
}
338