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

Completed
Pull Request — master (#1975)
by Eduard
03:16
created

Create::createRelations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 1
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
use Illuminate\Database\Eloquent\Relations\HasOne;
6
use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
8
trait Create
9
{
10
    /*
11
    |--------------------------------------------------------------------------
12
    |                                   CREATE
13
    |--------------------------------------------------------------------------
14
    */
15
16
    /**
17
     * Insert a row in the database.
18
     *
19
     * @param array $data All input values to be inserted.
20
     *
21
     * @return \Illuminate\Database\Eloquent\Model
22
     */
23 4
    public function create($data)
24
    {
25 4
        $data = $this->decodeJsonCastedAttributes($data, 'create');
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
26 4
        $data = $this->compactFakeFields($data, 'create');
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
27
28
        // omit the n-n relationships when updating the eloquent item
29 4
        $nn_relationships = array_pluck($this->getRelationFieldsWithPivot('create'), 'name');
0 ignored issues
show
Deprecated Code introduced by
The function array_pluck() has been deprecated with message: Arr::pluck() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
30 4
        $item = $this->model->create(array_except($data, $nn_relationships));
0 ignored issues
show
Bug introduced by
The property model does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Deprecated Code introduced by
The function array_except() has been deprecated with message: Arr::except() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
31
32
        // if there are any relationships available, also sync those
33 4
        $this->createRelations($item, $data);
34
35 4
        return $item;
36
    }
37
38
    /**
39
     * Get all fields needed for the ADD NEW ENTRY form.
40
     *
41
     * @return array The fields with attributes and fake attributes.
42
     */
43 25
    public function getCreateFields()
44
    {
45 25
        return $this->create_fields;
0 ignored issues
show
Bug introduced by
The property create_fields does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
46
    }
47
48
    /**
49
     * Get all fields with relation set (model key set on field).
50
     *
51
     * @param string $form create/update/both
52
     *
53
     * @return array The fields with model key set.
54
     */
55 15
    public function getRelationFields($form = 'create')
56
    {
57 15
        if ($form == 'create') {
58 13
            $fields = $this->create_fields;
59
        } else {
60 2
            $fields = $this->update_fields;
0 ignored issues
show
Bug introduced by
The property update_fields does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
61
        }
62
63 15
        $relationFields = [];
64
65 15
        foreach ($fields as $field) {
66 14
            if (isset($field['model'])) {
67 8
                array_push($relationFields, $field);
68
            }
69
70 14
            if (isset($field['subfields']) &&
71 14
                is_array($field['subfields']) &&
72 14
                count($field['subfields'])) {
73
                foreach ($field['subfields'] as $subfield) {
74
                    array_push($relationFields, $subfield);
75
                }
76
            }
77
        }
78
79 15
        return $relationFields;
80
    }
81
82
    /**
83
     * Get all fields with n-n relation set (pivot table is true).
84
     *
85
     * @param string $form create/update/both
86
     *
87
     * @return array The fields with n-n relationships.
88
     */
89 7
    public function getRelationFieldsWithPivot($form = 'create')
90
    {
91 7
        $all_relation_fields = $this->getRelationFields($form);
92
93
        return array_where($all_relation_fields, function ($value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Deprecated Code introduced by
The function array_where() has been deprecated with message: Arr::where() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
94 3
            return isset($value['pivot']) && $value['pivot'];
95 7
        });
96
    }
97
98
    /**
99
     * Create the relations for the current model.
100
     *
101
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
102
     * @param array                               $data The form data.
103
     * @param string                              $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
104
     */
105 5
    public function createRelations($item, $data, $form = 'create')
106
    {
107 5
        $this->syncPivot($item, $data, $form);
108 5
        $this->createOneToOneRelations($item, $data, $form);
109 5
    }
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
     * @param string                              $form  Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
117
     */
118 8
    public function syncPivot($model, $data, $form = 'create')
119
    {
120 8
        $fields_with_relationships = $this->getRelationFields($form);
121
122 8
        foreach ($fields_with_relationships as $key => $field) {
123 4
            if (isset($field['pivot']) && $field['pivot']) {
124 3
                $values = isset($data[$field['name']]) ? $data[$field['name']] : [];
125
126 3
                $relation_data = [];
127 3
                foreach ($values as $pivot_id) {
128 3
                    $pivot_data = [];
129
130 3
                    if (isset($field['pivotFields'])) {
131
                        foreach ($field['pivotFields'] as $pivot_field_name) {
132
                            $pivot_data[$pivot_field_name] = $data[$pivot_field_name][$pivot_id];
133
                        }
134
                    }
135 3
                    $relation_data[$pivot_id] = $pivot_data;
136
                }
137
138 3
                $model->{$field['name']}()->sync($relation_data);
139
            }
140
141 3
            if (isset($field['morph']) && $field['morph'] && isset($data[$field['name']])) {
142
                $values = $data[$field['name']];
143
                $model->{$field['name']}()->sync($values);
144
            }
145
        }
146 7
    }
147
148
    /**
149
     * Create any existing one to one relations for the current model from the form data.
150
     *
151
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
152
     * @param array                               $data The form data.
153
     * @param string                              $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
154
     */
155 5
    private function createOneToOneRelations($item, $data, $form = 'create')
156
    {
157 5
        $relationData = $this->getRelationDataFromFormData($data, $form);
158 5
        $this->createRelationsForItem($item, $relationData);
159 5
    }
160
161
    /**
162
     * Create any existing one to one relations for the current model from the relation data.
163
     *
164
     * @param \Illuminate\Database\Eloquent\Model $item          The current CRUD model.
165
     * @param array                               $formattedData The form data.
166
     *
167
     * @return bool|null
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use false|null.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
168
     */
169 5
    private function createRelationsForItem($item, $formattedData)
170
    {
171 5
        if (! isset($formattedData['relations'])) {
172 4
            return false;
173
        }
174
175 1
        foreach ($formattedData['relations'] as $relationMethod => $relationData) {
176 1
            $model = $relationData['model'];
177 1
            $relation = $item->{$relationMethod}();
178
179 1
            if ($relation instanceof BelongsTo) {
180 1
                $modelInstance = $model::find($relationData['values'])->first();
181 1
                if ($modelInstance != null) {
182 1
                    $relation->associate($modelInstance)->save();
183
                } else {
184 1
                    $relation->dissociate()->save();
185
                }
186
            } elseif ($relation instanceof HasOne) {
187
                if ($item->{$relationMethod} != null) {
188
                    $item->{$relationMethod}->update($relationData['values']);
189
                    $modelInstance = $item->{$relationMethod};
190
                } else {
191
                    $relationModel = new $model();
192
                    $modelInstance = $relationModel->create($relationData['values']);
193
                    $relation->save($modelInstance);
194
                }
195
            } else {
196
                $relationModel = new $model();
197
                $modelInstance = $relationModel->create($relationData['values']);
198
                $relation->save($modelInstance);
199
            }
200
201 1
            if (isset($relationData['relations'])) {
202
                $this->createRelationsForItem($modelInstance, ['relations' => $relationData['relations']]);
203
            }
204
        }
205 1
    }
206
207
    /**
208
     * Get a relation data array from the form data.
209
     * For each relation defined in the fields through the entity attribute, set the model, the parent model and the
210
     * attribute values. For relations defined with the "dot" notations, this will be used to calculate the depth in the
211
     * final array (@see \Illuminate\Support\Arr::set() for more).
212
     *
213
     * @param array  $data The form data.
214
     * @param string $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
215
     *
216
     * @return array The formatted relation data.
217
     */
218 5
    private function getRelationDataFromFormData($data, $form = 'create')
219
    {
220 5
        $relationFields = $this->getRelationFields($form);
221
222 5
        $relationData = [];
223 5
        foreach ($relationFields as $relationField) {
224 2
            $attributeKey = $relationField['name'];
225 2
            if (array_key_exists($attributeKey, $data) && empty($relationField['pivot'])) {
226 1
                $key = implode('.relations.', explode('.', $relationField['entity']));
227 1
                $fieldData = array_get($relationData, 'relations.'.$key, []);
0 ignored issues
show
Deprecated Code introduced by
The function array_get() has been deprecated with message: Arr::get() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
228
229 1
                if (! array_key_exists('model', $fieldData)) {
230 1
                    $fieldData['model'] = $relationField['model'];
231
                }
232
233 1
                if (! array_key_exists('parent', $fieldData)) {
234 1
                    $fieldData['parent'] = $this->getRelationModel($relationField['entity'], -1);
0 ignored issues
show
Bug introduced by
It seems like getRelationModel() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
235
                }
236
237 1
                $fieldData['values'][$attributeKey] = $data[$attributeKey];
238
239 1
                array_set($relationData, 'relations.'.$key, $fieldData);
0 ignored issues
show
Deprecated Code introduced by
The function array_set() has been deprecated with message: Arr::set() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
240
            }
241
        }
242
243 5
        return $relationData;
244
    }
245
}
246