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

Test Failed
Pull Request — master (#3410)
by
unknown
21:29 queued 06:53
created

Create::createRelationsForItem()   C

Complexity

Conditions 13
Paths 29

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 32
c 1
b 0
f 0
nc 29
nop 2
dl 0
loc 53
rs 6.6166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\HasMany;
7
use Illuminate\Database\Eloquent\Relations\HasOne;
8
use Illuminate\Database\Eloquent\Relations\MorphMany;
9
use Illuminate\Database\Eloquent\Relations\MorphOne;
10
use Illuminate\Support\Arr;
11
12
trait Create
13
{
14
    /*
15
    |--------------------------------------------------------------------------
16
    |                                   CREATE
17
    |--------------------------------------------------------------------------
18
    */
19
20
    /**
21
     * Insert a row in the database.
22
     *
23
     * @param array $data All input values to be inserted.
24
     *
25
     * @return \Illuminate\Database\Eloquent\Model
26
     */
27
    public function create($data)
28
    {
29
        $data = $this->decodeJsonCastedAttributes($data);
0 ignored issues
show
Bug introduced by
It seems like decodeJsonCastedAttributes() 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

29
        /** @scrutinizer ignore-call */ 
30
        $data = $this->decodeJsonCastedAttributes($data);
Loading history...
30
        $data = $this->compactFakeFields($data);
0 ignored issues
show
Bug introduced by
It seems like compactFakeFields() 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

30
        /** @scrutinizer ignore-call */ 
31
        $data = $this->compactFakeFields($data);
Loading history...
31
32
        // omit the n-n relationships when updating the eloquent item
33
        $relationships = Arr::pluck($this->getRelationFields(), 'name');
34
35
        // init and fill model
36
        $item = $this->model->make(Arr::except($data, $relationships));
37
38
        // handle BelongsTo 1:1 relations
39
        $item = $this->associateOrDissociateBelongsToRelations($item, $data);
40
        $item->save();
41
42
        // if there are any other relations create them.
43
        $this->createRelations($item, $data);
44
45
        return $item;
46
    }
47
48
    /**
49
     * Get all fields needed for the ADD NEW ENTRY form.
50
     *
51
     * @return array The fields with attributes and fake attributes.
52
     */
53
    public function getCreateFields()
54
    {
55
        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

55
        return $this->/** @scrutinizer ignore-call */ fields();
Loading history...
56
    }
57
58
    /**
59
     * Get all fields with relation set (model key set on field).
60
     *
61
     * @return array The fields with model key set.
62
     */
63
    public function getRelationFields()
64
    {
65
        $fields = $this->fields();
66
        $relationFields = [];
67
68
        foreach ($fields as $field) {
69
            if (isset($field['model']) && $field['model'] !== false) {
70
                array_push($relationFields, $field);
71
            }
72
73
            if (isset($field['subfields']) &&
74
                is_array($field['subfields']) &&
75
                count($field['subfields'])) {
76
                foreach ($field['subfields'] as $subfield) {
77
                    array_push($relationFields, $subfield);
78
                }
79
            }
80
        }
81
82
        return $relationFields;
83
    }
84
85
    /**
86
     * Get all fields with n-n relation set (pivot table is true).
87
     *
88
     * @return array The fields with n-n relationships.
89
     */
90
    public function getRelationFieldsWithPivot()
91
    {
92
        $all_relation_fields = $this->getRelationFields();
93
94
        return Arr::where($all_relation_fields, function ($value, $key) {
95
            return isset($value['pivot']) && $value['pivot'];
96
        });
97
    }
98
99
    /**
100
     * Create the relations for the current model.
101
     *
102
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
103
     * @param array                               $data The form data.
104
     */
105
    public function createRelations($item, $data)
106
    {
107
        $this->syncPivot($item, $data);
108
        $this->createOneToOneRelations($item, $data);
109
    }
110
111
    /**
112
     * Sync the declared many-to-many associations through the pivot field.
113
     *
114
     * @param \Illuminate\Database\Eloquent\Model $model The current CRUD model.
115
     * @param array                               $data  The form data.
116
     */
117
    public function syncPivot($model, $data)
118
    {
119
        $fields_with_relationships = $this->getRelationFieldsWithPivot();
120
        foreach ($fields_with_relationships as $key => $field) {
121
            $values = isset($data[$field['name']]) ? $data[$field['name']] : [];
122
123
            // if a JSON was passed instead of an array, turn it into an array
124
            if (is_string($values)) {
125
                $decoded_values = json_decode($values, true);
126
                $values = [];
127
                //array is not multidimensional
128
                if (count($decoded_values) != count($decoded_values, COUNT_RECURSIVE)) {
129
                    foreach ($decoded_values as $value) {
130
                        $values[] = $value[$field['name']];
131
                    }
132
                } else {
133
                    $values = $decoded_values;
134
                }
135
            }
136
137
            $relation_data = [];
138
139
            foreach ($values as $pivot_id) {
140
                if ($pivot_id != '') {
141
                    $pivot_data = [];
142
143
                    if (isset($field['pivotFields'])) {
144
                        //array is not multidimensional
145
                        if (count($field['pivotFields']) == count($field['pivotFields'], COUNT_RECURSIVE)) {
146
                            foreach ($field['pivotFields'] as $pivot_field_name) {
147
                                $pivot_data[$pivot_field_name] = $data[$pivot_field_name][$pivot_id];
148
                            }
149
                        } else {
150
                            $field_data = json_decode($data[$field['name']], true);
151
152
                            //we grab from the parsed data the specific values for this pivot
153
                            $pivot_data = Arr::first(Arr::where($field_data, function ($item) use ($pivot_id, $field) {
154
                                return $item[$field['name']] === $pivot_id;
155
                            }));
156
157
                            //we remove the relation field from extra pivot data as we already have the relation.
158
                            unset($pivot_data[$field['name']]);
159
                        }
160
                    }
161
162
                    $relation_data[$pivot_id] = $pivot_data;
163
                }
164
165
                $model->{$field['name']}()->sync($relation_data);
166
167
                if (isset($field['morph']) && $field['morph'] && isset($data[$field['name']])) {
168
                    $values = $data[$field['name']];
169
                    $model->{$field['name']}()->sync($values);
170
                }
171
            }
172
        }
173
    }
174
175
    /**
176
     * Create any existing one to one relations and subsquent relations for the item.
177
     *
178
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
179
     * @param array                               $data The form data.
180
     */
181
    private function createOneToOneRelations($item, $data)
182
    {
183
        $relationData = $this->getRelationDataFromFormData($data);
184
        $this->createRelationsForItem($item, $relationData);
185
    }
186
187
    /**
188
     * Create any existing one to one relations and subsquent relations from form data.
189
     *
190
     * @param \Illuminate\Database\Eloquent\Model $item          The current CRUD model.
191
     * @param array                               $formattedData The form data.
192
     *
193
     * @return bool|null
194
     */
195
    private function createRelationsForItem($item, $formattedData)
196
    {
197
        if (! isset($formattedData['relations'])) {
198
            return false;
199
        }
200
201
        foreach ($formattedData['relations'] as $relationMethod => $relationData) {
202
            if (! isset($relationData['model'])) {
203
                continue;
204
            }
205
206
            $relation = $item->{$relationMethod}();
207
            $relation_type = get_class($relation);
208
209
            switch ($relation_type) {
210
                case HasOne::class:
211
                case MorphOne::class:
212
                    // we first check if there are relations of the relation
213
                    if (isset($relationData['relations'])) {
214
                        $belongsToRelations = Arr::where($relationData['relations'], function ($relation_data) {
215
                            return $relation_data['relation_type'] == 'BelongsTo';
216
                        });
217
                        // adds the values of the BelongsTo relations of this entity to the array of values that will
218
                        // be saved at the same time like we do in parent entity belongs to relations
219
                        $valuesWithRelations = $this->associateHasOneBelongsTo($belongsToRelations, $relationData['values'], $relation->getModel());
220
221
                        $relationData['relations'] = Arr::where($relationData['relations'], function ($item) {
222
                            return $item['relation_type'] != 'BelongsTo';
223
                        });
224
225
                        $modelInstance = $relation->updateOrCreate([], $valuesWithRelations);
226
                    } else {
227
                        $modelInstance = $relation->updateOrCreate([], $relationData['values']);
228
                    }
229
                break;
230
                case HasMany::class:
231
                case MorphMany::class:
232
                    $relation_values = $relationData['values'][$relationMethod];
233
234
                    if (is_string($relation_values)) {
235
                        $relation_values = json_decode($relationData['values'][$relationMethod], true);
236
                    }
237
238
                    if (is_null($relation_values) || count($relation_values) == count($relation_values, COUNT_RECURSIVE)) {
239
                        $this->attachManyRelation($item, $relation, $relationMethod, $relationData, $relation_values);
240
                    } else {
241
                        $this->createManyEntries($item, $relation, $relationMethod, $relationData);
242
                    }
243
                break;
244
            }
245
246
            if (isset($relationData['relations'])) {
247
                $this->createRelationsForItem($modelInstance, ['relations' => $relationData['relations']]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $modelInstance does not seem to be defined for all execution paths leading up to this point.
Loading history...
248
            }
249
        }
250
    }
251
252
    /**
253
     * Associate and dissociate BelongsTo relations in the model.
254
     *
255
     * @param  Model
256
     * @param  array The form data.
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Library\CrudPanel\Traits\The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
257
     * @return Model Model with relationships set up.
258
     */
259
    protected function associateOrDissociateBelongsToRelations($item, array $data)
260
    {
261
        $belongsToFields = $this->getFieldsWithRelationType('BelongsTo');
0 ignored issues
show
Bug introduced by
It seems like getFieldsWithRelationType() 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

261
        /** @scrutinizer ignore-call */ 
262
        $belongsToFields = $this->getFieldsWithRelationType('BelongsTo');
Loading history...
262
263
        foreach ($belongsToFields as $relationField) {
264
            if (method_exists($item, $this->getOnlyRelationEntity($relationField))) {
0 ignored issues
show
Bug introduced by
It seems like getOnlyRelationEntity() 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

264
            if (method_exists($item, $this->/** @scrutinizer ignore-call */ getOnlyRelationEntity($relationField))) {
Loading history...
265
                $relatedId = Arr::get($data, $relationField['name']);
266
                $related = $relationField['model']::find($relatedId);
267
268
                $item->{$this->getOnlyRelationEntity($relationField)}()->associate($related);
269
            }
270
        }
271
272
        return $item;
273
    }
274
275
    /**
276
     * Associate the nested HasOne -> BelongsTo relations by adding the "connecting key"
277
     * to the array of values that is going to be saved with HasOne relation.
278
     *
279
     * @param array $belongsToRelations
280
     * @param array $modelValues
281
     * @param Model $modelInstance
282
     * @return array
283
     */
284
    private function associateHasOneBelongsTo($belongsToRelations, $modelValues, $modelInstance)
285
    {
286
        foreach ($belongsToRelations as $methodName => $values) {
287
            $relation = $modelInstance->{$methodName}();
288
            $modelValues[$relation->getForeignKeyName()] = $values['values'][$methodName];
289
        }
290
291
        return $modelValues;
292
    }
293
294
    /**
295
     * Get a relation data array from the form data.
296
     * For each relation defined in the fields through the entity attribute, set the model, the parent model and the
297
     * attribute values.
298
     *
299
     * We traverse this relation array later to create the relations, for example:
300
     *
301
     * Current model HasOne Address, this Address (line_1, country_id) BelongsTo Country through country_id in Address Model.
302
     *
303
     * So when editing current model crud user have two fields address.line_1 and address.country (we infer country_id from relation)
304
     *
305
     * Those will be nested accordingly in this relation array, so address relation will have a nested relation with country.
306
     *
307
     *
308
     * @param array $data The form data.
309
     *
310
     * @return array The formatted relation data.
311
     */
312
    private function getRelationDataFromFormData($data)
313
    {
314
        // exclude the already attached belongs to relations but include nested belongs to.
315
        $relation_fields = Arr::where($this->getRelationFields(), function ($field, $key) {
316
            return $field['relation_type'] !== 'BelongsTo' || $this->isNestedRelation($field);
0 ignored issues
show
Bug introduced by
It seems like isNestedRelation() 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

316
            return $field['relation_type'] !== 'BelongsTo' || $this->/** @scrutinizer ignore-call */ isNestedRelation($field);
Loading history...
317
        });
318
319
        $relationData = [];
320
321
        foreach ($relation_fields as $relation_field) {
322
            $attributeKey = $this->parseRelationFieldNamesFromHtml([$relation_field])[0]['name'];
0 ignored issues
show
Bug introduced by
It seems like parseRelationFieldNamesFromHtml() 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

322
            $attributeKey = $this->/** @scrutinizer ignore-call */ parseRelationFieldNamesFromHtml([$relation_field])[0]['name'];
Loading history...
323
            if (isset($relation_field['pivot']) && $relation_field['pivot'] !== true) {
324
                $key = implode('.relations.', explode('.', $this->getOnlyRelationEntity($relation_field)));
325
                $fieldData = Arr::get($relationData, 'relations.'.$key, []);
326
                if (! array_key_exists('model', $fieldData)) {
327
                    $fieldData['model'] = $relation_field['model'];
328
                }
329
                if (! array_key_exists('parent', $fieldData)) {
330
                    $fieldData['parent'] = $this->getRelationModel($attributeKey, -1);
0 ignored issues
show
Bug introduced by
The method getRelationModel() does not exist on Backpack\CRUD\app\Library\CrudPanel\Traits\Create. Did you maybe mean getRelationFields()? ( Ignorable by Annotation )

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

330
                    /** @scrutinizer ignore-call */ 
331
                    $fieldData['parent'] = $this->getRelationModel($attributeKey, -1);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
331
                }
332
333
                // when using HasMany/MorphMany if fallback_id is provided instead of deleting the models
334
                // from database we resort to this fallback provided by developer
335
                if (array_key_exists('fallback_id', $relation_field)) {
336
                    $fieldData['fallback_id'] = $relation_field['fallback_id'];
337
                }
338
339
                // when using HasMany/MorphMany and column is nullable, by default backpack sets the value to null.
340
                // this allow developers to override that behavior and force deletion from database
341
                $fieldData['force_delete'] = $relation_field['force_delete'] ?? false;
342
343
                if (! array_key_exists('relation_type', $fieldData)) {
344
                    $fieldData['relation_type'] = $relation_field['relation_type'];
345
                }
346
                $relatedAttribute = Arr::last(explode('.', $attributeKey));
347
                $fieldData['values'][$relatedAttribute] = Arr::get($data, $attributeKey);
348
349
                Arr::set($relationData, 'relations.'.$key, $fieldData);
350
            }
351
        }
352
353
        return $relationData;
354
    }
355
356
    /**
357
     * When using the HasMany/MorphMany relations as selectable elements we use this function to sync those relations.
358
     * Here we allow for different functionality than when creating. Developer could use this relation as a
359
     * selectable list of items that can belong to one/none entity at any given time.
360
     *
361
     * @return void
362
     */
363
    public function attachManyRelation($item, $relation, $relationMethod, $relationData, $relation_values)
364
    {
365
        $model_instance = $relation->getRelated();
366
        $force_delete = $relationData['force_delete'];
367
        $relation_foreign_key = $relation->getForeignKeyName();
368
        $relation_local_key = $relation->getLocalKeyName();
369
370
        $relation_column_is_nullable = $model_instance->isColumnNullable($relation_foreign_key);
371
372
        if (! is_null($relation_values) && $relationData['values'][$relationMethod][0] !== null) {
373
            //we add the new values into the relation
374
            $model_instance->whereIn($model_instance->getKeyName(), $relation_values)
375
           ->update([$relation_foreign_key => $item->{$relation_local_key}]);
376
377
            //we clear up any values that were removed from model relation.
378
            //if developer provided a fallback id, we use it
379
            //if column is nullable we set it to null
380
            //if none of the above we delete the model from database
381
            if (isset($relationData['fallback_id'])) {
382
                $model_instance->whereNotIn($model_instance->getKeyName(), $relation_values)
383
                            ->where($relation_foreign_key, $item->{$relation_local_key})
384
                            ->update([$relation_foreign_key => $relationData['fallback_id']]);
385
            } else {
386
                if (! $relation_column_is_nullable || $force_delete) {
387
                    $model_instance->whereNotIn($model_instance->getKeyName(), $relation_values)
388
                            ->where($relation_foreign_key, $item->{$relation_local_key})
389
                            ->delete();
390
                } else {
391
                    $model_instance->whereNotIn($model_instance->getKeyName(), $relation_values)
392
                            ->where($relation_foreign_key, $item->{$relation_local_key})
393
                            ->update([$relation_foreign_key => null]);
394
                }
395
            }
396
        } else {
397
            //the developer cleared the selection
398
            //we gonna clear all related values by setting up the value to the fallback id, to null or delete.
399
            if (isset($relationData['fallback_id'])) {
400
                $model_instance->where($relation_foreign_key, $item->{$relation_local_key})
401
                            ->update([$relation_foreign_key => $relationData['fallback_id']]);
402
            } else {
403
                if (! $relation_column_is_nullable || $force_delete) {
404
                    $model_instance->where($relation_foreign_key, $item->{$relation_local_key})->delete();
405
                } else {
406
                    $model_instance->where($relation_foreign_key, $item->{$relation_local_key})
407
                            ->update([$relation_foreign_key => null]);
408
                }
409
            }
410
        }
411
    }
412
413
    /**
414
     * Handle HasMany/MorphMany relations when used as creatable entries in the crud.
415
     * By using repeatable field, developer can allow the creation of such entries
416
     * in the crud forms.
417
     *
418
     * @return void
419
     */
420
    public function createManyEntries($entry, $relation, $relationMethod, $relationData)
421
    {
422
        $items = collect(json_decode($relationData['values'][$relationMethod], true));
423
        $relatedModel = $relation->getRelated();
424
        //if the collection is empty we clear all previous values in database if any.
425
        if ($items->isEmpty()) {
426
            $entry->{$relationMethod}()->sync([]);
427
        } else {
428
            $items->each(function (&$item, $key) use ($relatedModel, $entry, $relationMethod) {
429
                if (isset($item[$relatedModel->getKeyName()])) {
430
                    $entry->{$relationMethod}()->updateOrCreate([$relatedModel->getKeyName() => $item[$relatedModel->getKeyName()]], $item);
431
                } else {
432
                    $entry->{$relationMethod}()->updateOrCreate([], $item);
433
                }
434
            });
435
436
            $relatedItemsSent = $items->pluck($relatedModel->getKeyName());
437
438
            if (! $relatedItemsSent->isEmpty()) {
439
                //we perform the cleanup of removed database items
440
                $entry->{$relationMethod}->each(function ($item, $key) use ($relatedItemsSent) {
441
                    if (! $relatedItemsSent->contains($item->getKey())) {
442
                        $item->delete();
443
                    }
444
                });
445
            }
446
        }
447
    }
448
}
449