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
Push — master ( 0be2ba...247314 )
by Cristian
04:16
created

Fields::removeFields()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
trait Fields
6
{
7
    // ------------
8
    // FIELDS
9
    // ------------
10
11
    /**
12
     * Add a field to the create/update form or both.
13
     *
14
     * @param string|array $field The new field.
15
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
16
     */
17 67
    public function addField($field, $form = 'both')
18
    {
19
        // if the field_definition_array array is a string, it means the programmer was lazy and has only passed the name
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
20
        // set some default values, so the field will still work
21 67
        if (is_string($field)) {
22 4
            $completeFieldsArray['name'] = $field;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$completeFieldsArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $completeFieldsArray = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
23
        } else {
24 63
            $completeFieldsArray = $field;
25
        }
26
27
        // if this is a relation type field and no corresponding model was specified, get it from the relation method
28
        // defined in the main model
29 67
        if (isset($completeFieldsArray['entity']) && ! isset($completeFieldsArray['model'])) {
30 8
            $completeFieldsArray['model'] = $this->getRelationModel($completeFieldsArray['entity']);
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...
31
        }
32
33
        // if the label is missing, we should set it
34 67
        if (! isset($completeFieldsArray['label'])) {
35 49
            $completeFieldsArray['label'] = ucfirst($completeFieldsArray['name']);
36
        }
37
38
        // if the field type is missing, we should set it
39 66
        if (! isset($completeFieldsArray['type'])) {
40 62
            $completeFieldsArray['type'] = $this->getFieldTypeFromDbColumnType($completeFieldsArray['name']);
0 ignored issues
show
Bug introduced by
It seems like getFieldTypeFromDbColumnType() 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...
41
        }
42
43
        // if a tab was mentioned, we should enable it
44 66
        if (isset($completeFieldsArray['tab'])) {
45 7
            if (! $this->tabsEnabled()) {
0 ignored issues
show
Bug introduced by
It seems like tabsEnabled() 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...
46 7
                $this->enableTabs();
0 ignored issues
show
Bug introduced by
It seems like enableTabs() 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...
47
            }
48
        }
49
50 66
        $this->transformFields($form, function ($fields) use ($completeFieldsArray) {
51 66
            $fields[$completeFieldsArray['name']] = $completeFieldsArray;
52
53 66
            return $fields;
54 66
        });
55
56 66
        return $this;
57
    }
58
59
    /**
60
     * Add multiple fields to the create/update form or both.
61
     *
62
     * @param array $fields The new fields.
63
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
64
     */
65 61
    public function addFields($fields, $form = 'both')
66
    {
67 61
        if (count($fields)) {
68 61
            foreach ($fields as $field) {
69 61
                $this->addField($field, $form);
70
            }
71
        }
72 60
    }
73
74
    /**
75
     * Move the most recently added field after the given target field.
76
     *
77
     * @param string $targetFieldName The target field name.
78
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
79
     */
80
    public function afterField($targetFieldName, $form = 'both')
81
    {
82 6
        $this->transformFields($form, function ($fields) use ($targetFieldName) {
83 6
            return $this->moveField($fields, $targetFieldName, false);
84 6
        });
85 6
    }
86
87
    /**
88
     * Move the most recently added field before the given target field.
89
     *
90
     * @param string $targetFieldName The target field name.
91
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
92
     */
93
    public function beforeField($targetFieldName, $form = 'both')
94
    {
95 7
        $this->transformFields($form, function ($fields) use ($targetFieldName) {
96 7
            return $this->moveField($fields, $targetFieldName, true);
97 7
        });
98 7
    }
99
100
    /**
101
     * Move the most recently added field before or after the given target field. Default is before.
102
     *
103
     * @param array $fields The form fields.
104
     * @param string $targetFieldName The target field name.
105
     * @param bool $before If true, the field will be moved before the target field, otherwise it will be moved after it.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
106
     * @return array
107
     */
108 13
    private function moveField($fields, $targetFieldName, $before = true)
109
    {
110 13
        if (array_key_exists($targetFieldName, $fields)) {
111 11
            $targetFieldPosition = $before ? array_search($targetFieldName, array_keys($fields))
112 11
                : array_search($targetFieldName, array_keys($fields)) + 1;
113
114 11
            if ($targetFieldPosition >= (count($fields) - 1)) {
115
                // target field name is same as element
116 3
                return $fields;
117
            }
118
119 9
            $element = array_pop($fields);
120 9
            $beginningArrayPart = array_slice($fields, 0, $targetFieldPosition, true);
121 9
            $endingArrayPart = array_slice($fields, $targetFieldPosition, null, true);
122
123 9
            $fields = array_merge($beginningArrayPart, [$element['name'] => $element], $endingArrayPart);
124
        }
125
126 11
        return $fields;
127
    }
128
129
    /**
130
     * Remove a certain field from the create/update/both forms by its name.
131
     *
132
     * @param string $name Field name (as defined with the addField() procedure)
133
     * @param string $form update/create/both
134
     */
135
    public function removeField($name, $form = 'both')
136
    {
137 4
        $this->transformFields($form, function ($fields) use ($name) {
138 4
            array_forget($fields, $name);
139
140 4
            return $fields;
141 4
        });
142 4
    }
143
144
    /**
145
     * Remove many fields from the create/update/both forms by their name.
146
     *
147
     * @param array  $array_of_names A simple array of the names of the fields to be removed.
148
     * @param string $form           update/create/both
149
     */
150 4
    public function removeFields($array_of_names, $form = 'both')
0 ignored issues
show
Coding Style Naming introduced by
The parameter $array_of_names is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
151
    {
152 4
        if (! empty($array_of_names)) {
153 4
            foreach ($array_of_names as $name) {
154 4
                $this->removeField($name, $form);
155
            }
156
        }
157 4
    }
158
159
    /**
160
     * Set label for a specific field.
161
     *
162
     * @param string $field
163
     * @param string $label
164
     */
165
    public function setFieldLabel($field, $label)
166
    {
167
        if (isset($this->create_fields[$field])) {
168
            $this->create_fields[$field]['label'] = $label;
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...
169
        }
170
        if (isset($this->update_fields[$field])) {
171
            $this->update_fields[$field]['label'] = $label;
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...
172
        }
173
    }
174
175
    /**
176
     * Check if field is the first of its type in the given fields array.
177
     * It's used in each field_type.blade.php to determine wether to push the css and js content or not (we only need to push the js and css for a field the first time it's loaded in the form, not any subsequent times).
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 219 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...
178
     *
179
     * @param array $field        The current field being tested if it's the first of its type.
180
     * @param array $fields_array All the fields in that particular form.
181
     *
182
     * @return bool true/false
183
     */
184 3
    public function checkIfFieldIsFirstOfItsType($field, $fields_array)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $fields_array is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
185
    {
186 3
        $first_field = $this->getFirstOfItsTypeInArray($field['type'], $fields_array);
0 ignored issues
show
Bug introduced by
It seems like getFirstOfItsTypeInArray() 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...
187
188 2
        if ($field['name'] == $first_field['name']) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $field['name'] == $first_field['name'];.
Loading history...
189 1
            return true;
190
        }
191
192 2
        return false;
193
    }
194
195
    /**
196
     * Decode attributes that are casted as array/object/json in the model.
197
     * So that they are not json_encoded twice before they are stored in the db
198
     * (once by Backpack in front-end, once by Laravel Attribute Casting).
199
     */
200 6
    public function decodeJsonCastedAttributes($data, $form, $id = false)
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...
201
    {
202
        // get the right fields according to the form type (create/update)
203 6
        $fields = $this->getFields($form, $id);
0 ignored issues
show
Bug introduced by
It seems like getFields() 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...
204 5
        $casted_attributes = $this->model->getCastedAttributes();
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...
205
206 5
        foreach ($fields as $field) {
207
208
            // Test the field is castable
209 5
            if (isset($field['name']) && array_key_exists($field['name'], $casted_attributes)) {
210
211
                // Handle JSON field types
212 5
                $jsonCastables = ['array', 'object', 'json'];
213 5
                $fieldCasting = $casted_attributes[$field['name']];
214
215 5
                if (in_array($fieldCasting, $jsonCastables) && isset($data[$field['name']]) && ! empty($data[$field['name']]) && ! is_array($data[$field['name']])) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 165 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...
216
                    try {
217
                        $data[$field['name']] = json_decode($data[$field['name']]);
218
                    } catch (\Exception $e) {
219 5
                        $data[$field['name']] = [];
220
                    }
221
                }
222
            }
223
        }
224
225 5
        return $data;
226
    }
227
228 9
    public function getCurrentFields()
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...
229
    {
230 9
        if ($this->entry) {
231 1
            return $this->getUpdateFields($this->entry->getKey());
0 ignored issues
show
Bug introduced by
The property entry 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...
Bug introduced by
It seems like getUpdateFields() 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...
232
        }
233
234 8
        return $this->getCreateFields();
0 ignored issues
show
Bug introduced by
It seems like getCreateFields() 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
    /**
238
     * Order the CRUD fields in the given form. If certain fields are missing from the given order array, they will be
239
     * pushed to the new fields array in the original order.
240
     *
241
     * @param array $order An array of field names in the desired order.
242
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'.
243
     */
244
    public function orderFields($order, $form = 'both')
245
    {
246 7
        $this->transformFields($form, function ($fields) use ($order) {
247 7
            return $this->applyOrderToFields($fields, $order);
248 7
        });
249 7
    }
250
251
    /**
252
     * Apply the given order to the fields and return the new array.
253
     *
254
     * @param array $fields The fields array.
255
     * @param array $order The desired field order array.
256
     * @return array The ordered fields array.
257
     */
258 7
    private function applyOrderToFields($fields, $order)
259
    {
260 7
        $orderedFields = [];
261 7
        foreach ($order as $fieldName) {
262 6
            if (array_key_exists($fieldName, $fields)) {
263 6
                $orderedFields[$fieldName] = $fields[$fieldName];
264
            }
265
        }
266
267 7
        if (empty($orderedFields)) {
268 2
            return $fields;
269
        }
270
271 5
        $remaining = array_diff_key($fields, $orderedFields);
272
273 5
        return array_merge($orderedFields, $remaining);
274
    }
275
276
    /**
277
     * Set the order of the CRUD fields.
278
     *
279
     * @param array $fields Fields order.
280
     *
281
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
282
     * @see Fields::orderFields() to order the CRUD fields.
283
     */
284
    public function setFieldOrder($fields)
0 ignored issues
show
Unused Code introduced by
The parameter $fields 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...
285
    {
286
        // not implemented
287
    }
288
289
    /**
290
     * Set the order of the CRUD fields.
291
     *
292
     * @param array $fields Fields order.
293
     *
294
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
295
     * @see Fields::orderFields() to order the CRUD fields.
296
     */
297
    public function setFieldsOrder($fields)
298
    {
299
        $this->setFieldOrder($fields);
0 ignored issues
show
Deprecated Code introduced by
The method Backpack\CRUD\PanelTraits\Fields::setFieldOrder() has been deprecated with message: This method was not and will not be implemented since its a duplicate of the orderFields method.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

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

Loading history...
300
    }
301
302
    /**
303
     * Apply the given callback to the form fields.
304
     *
305
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'.
306
     * @param callable $callback The callback function to run for the given form fields.
307
     */
308 66
    private function transformFields($form, callable $callback)
309
    {
310 66
        switch (strtolower($form)) {
311 66
            case 'create':
312 14
                $this->create_fields = $callback($this->create_fields);
313 14
                break;
314
315 58
            case 'update':
316 15
                $this->update_fields = $callback($this->update_fields);
317 15
                break;
318
319
            default:
320 49
                $this->create_fields = $callback($this->create_fields);
321 49
                $this->update_fields = $callback($this->update_fields);
322 49
                break;
323
        }
324 66
    }
325
}
326