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 (#1453)
by Oliver
05:13 queued 47s
created

Create   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 85.86%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 243
ccs 85
cts 99
cp 0.8586
rs 8.2769
wmc 41
lcom 1
cbo 5

9 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 14 1
A getCreateFields() 0 4 1
C getRelationFields() 0 26 8
A getRelationFieldsWithPivot() 0 8 2
A createRelations() 0 5 1
C syncPivot() 0 24 11
A createDirectRelations() 0 5 1
D createRelationsForItem() 0 45 9
C getRelationDataFromFormData() 0 31 7

How to fix   Complexity   

Complex Class

Complex classes like Create often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Create, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\HasOne;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
10
trait Create
11
{
12
    /*
13
    |--------------------------------------------------------------------------
14
    |                                   CREATE
15
    |--------------------------------------------------------------------------
16
    */
17
18
    /**
19
     * Insert a row in the database.
20
     *
21
     * @param  [Request] All input values to be inserted.
22
     *
23
     * @return [Eloquent Collection]
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
24
     */
25 5
    public function create($data)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
26
    {
27 5
        $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...
28 5
        $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...
29
30
        // omit the n-n relationships when updating the eloquent item
31 5
        $nn_relationships = array_pluck($this->getRelationFieldsWithPivot('create'), 'name');
32 5
        $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...
33
34
        // if there are any relationships available, also sync those
35 5
        $this->createRelations($item, $data);
36
37 5
        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.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
44
     */
45 23
    public function getCreateFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
46
    {
47 23
        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...
48
    }
49
50
    /**
51
     * Get all fields with relation set (model key set on field).
52
     *
53
     * @param [string: create/update/both]
54
     *
55
     * @return [array] The fields with model key set.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
56
     */
57 16
    public function getRelationFields($form = 'create')
58
    {
59 16
        if ($form == 'create') {
60 14
            $fields = $this->create_fields;
61
        } else {
62 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...
63
        }
64
65 16
        $relationFields = [];
66
67 16
        foreach ($fields as $field) {
68 15
            if (isset($field['model'])) {
69 9
                array_push($relationFields, $field);
70
            }
71
72 15
            if (isset($field['subfields']) &&
73 15
                is_array($field['subfields']) &&
74 15
                count($field['subfields'])) {
75
                foreach ($field['subfields'] as $subfield) {
76 15
                    array_push($relationFields, $subfield);
77
                }
78
            }
79
        }
80
81 16
        return $relationFields;
82
    }
83
84
    /**
85
     * Get all fields with n-n relation set (pivot table is true).
86
     *
87
     * @param [string: create/update/both]
88
     *
89
     * @return [array] The fields with n-n relationships.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
90
     */
91 8
    public function getRelationFieldsWithPivot($form = 'create')
92
    {
93 8
        $all_relation_fields = $this->getRelationFields($form);
94
95 8
        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...
96 4
            return isset($value['pivot']) && $value['pivot'];
97 8
        });
98
    }
99
100
    /**
101
     * Create the relations for the current model.
102
     *
103
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
104
     * @param array $data The form data.
105
     * @param string $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
106
     */
107 6
    public function createRelations($item, $data, $form = 'create')
108
    {
109 6
        $this->syncPivot($item, $data, $form);
110 6
        $this->createDirectRelations($item, $data, $form);
111 6
    }
112
113
    /**
114
     * Sync the declared many-to-many associations through the pivot field.
115
     *
116
     * @param \Illuminate\Database\Eloquent\Model $model The current CRUD model.
117
     * @param array $data The form data.
118
     * @param string $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
119
     */
120 9
    public function syncPivot($model, $data, $form = 'create')
121
    {
122 9
        $fields_with_relationships = $this->getRelationFields($form);
123
124 9
        foreach ($fields_with_relationships as $key => $field) {
125 5
            if (isset($field['pivot']) && $field['pivot']) {
126 4
                $values = isset($data[$field['name']]) ? $data[$field['name']] : [];
127 4
                $model->{$field['name']}()->sync($values);
128
129 3
                if (isset($field['pivotFields'])) {
130
                    foreach ($field['pivotFields'] as $pivotField) {
131
                        foreach ($data[$pivotField] as $pivot_id => $pivot_field) {
132
                            $model->{$field['name']}()->updateExistingPivot($pivot_id, [$pivotField => $pivot_field]);
133
                        }
134
                    }
135
                }
136
            }
137
138 4
            if (isset($field['morph']) && $field['morph'] && isset($data[$field['name']])) {
139
                $values = $data[$field['name']];
140 4
                $model->{$field['name']}()->sync($values);
141
            }
142
        }
143 8
    }
144
145
    /**
146
     * Create any existing direct (not n:n) relations for the current model from the form data.
147
     *
148
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
149
     * @param array $data The form data.
150
     * @param string $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
151
     */
152 6
    private function createDirectRelations($item, $data, $form = 'create')
153
    {
154 6
        $relationData = $this->getRelationDataFromFormData($data, $form);
155 6
        $this->createRelationsForItem($item, $relationData);
156 6
    }
157
158
    /**
159
     * Create any existing one to one relations for the current model from the relation data.
160
     *
161
     * @param \Illuminate\Database\Eloquent\Model $item The current CRUD model.
162
     * @param array $formattedData The form data.
163
     */
164 6
    private function createRelationsForItem($item, $formattedData)
165
    {
166 6
        if (! isset($formattedData['relations'])) {
167 4
            return false;
168
        }
169
170 2
        foreach ($formattedData['relations'] as $relationMethod => $relationData) {
171 2
            $model = $relationData['model'];
172 2
            $relation = $item->{$relationMethod}();
173 2
            if ($relation instanceof BelongsTo) {
174 1
                $modelInstance = $model::find($relationData['values'])->first();
175 1
                if ($modelInstance != null) {
176 1
                    $relation->associate($modelInstance)->save();
177
                } else {
178 1
                    $relation->dissociate()->save();
179
                }
180 1
            } elseif ($relation instanceof HasOne) {
181
                if ($item->{$relationMethod} != null) {
182
                    $item->{$relationMethod}->update([$relation->getForeignKeyName() => $relationData['fallback_id'] ?? null]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
183
                }
184
185
                $modelInstance = $model::find($relationData['values'][$relationMethod]);
186
                $relation->save($modelInstance);
187
                $modelInstance = $item->{$relationMethod};
188 1
            } elseif ($relation instanceof HasMany) {
189 1
                $related_ids = collect($relationData['values'][$relationMethod]);
190 1
                $old_ids = $item->{$relationMethod}->pluck($relation->getRelated()->getKeyName());
191 1
                $removed = $old_ids->diff($related_ids);
192 1
                $added = $related_ids->diff($old_ids);
193
194 1
                $instance = new $model();
195 1
                $model::whereIn($instance->getKeyName(), $removed)->update([$relation->getForeignKeyName() => $relationData['fallback_id'] ?? null]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 149 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
196 1
                $model::whereIn($instance->getKeyName(), $added)->update([$relation->getForeignKeyName() => $item->getKey()]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
197 1
                $item = $item->load($relationMethod);
198
            } else {
199
                $relationModel = new $model();
200
                $modelInstance = $relationModel->create($relationData['values']);
201
                $relation->save($modelInstance);
202
            }
203
204 2
            if (isset($relationData['relations'])) {
205 2
                $this->createRelationsForItem($modelInstance, ['relations' => $relationData['relations']]);
0 ignored issues
show
Bug introduced by
The variable $modelInstance does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
206
            }
207
        }
208 2
    }
209
210
    /**
211
     * Get a relation data array from the form data.
212
     * For each relation defined in the fields through the entity attribute, set the model, the parent model and the
213
     * attribute values. For relations defined with the "dot" notations, this will be used to calculate the depth in the
214
     * final array (@see \Illuminate\Support\Arr::set() for more).
215
     *
216
     * @param array $data The form data.
217
     * @param string $form Optional form type. Can be either 'create', 'update' or 'both'. Default is 'create'.
218
     *
219
     * @return array The formatted relation data.
220
     */
221 6
    private function getRelationDataFromFormData($data, $form = 'create')
222
    {
223 6
        $relationFields = $this->getRelationFields($form);
224
225 6
        $relationData = [];
226 6
        foreach ($relationFields as $relationField) {
227 3
            $attributeKey = $relationField['name'];
228 3
            if (array_key_exists($attributeKey, $data) && empty($relationField['pivot'])) {
229 2
                $key = implode('.relations.', explode('.', $relationField['entity']));
230 2
                $fieldData = array_get($relationData, 'relations.'.$key, []);
231
232 2
                if (! array_key_exists('model', $fieldData)) {
233 2
                    $fieldData['model'] = $relationField['model'];
234
                }
235
236 2
                if (! array_key_exists('parent', $fieldData)) {
237 2
                    $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...
238
                }
239
240 2
                if (array_key_exists('fallback_id', $relationField)) {
241
                    $fieldData['fallback_id'] = $relationField['fallback_id'];
242
                }
243
244 2
                $fieldData['values'][$attributeKey] = $data[$attributeKey];
245
246 3
                array_set($relationData, 'relations.'.$key, $fieldData);
247
            }
248
        }
249
250 6
        return $relationData;
251
    }
252
}
253