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 (#1859)
by Wesley
03:16
created

Fields::addField()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9.0117

Importance

Changes 0
Metric Value
cc 9
nc 96
nop 2
dl 0
loc 44
ccs 18
cts 19
cp 0.9474
crap 9.0117
rs 7.6604
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
     * @return self
18
     */
19 68
    public function addField($field, $form = 'both')
20
    {
21 68
        if (! empty($field['form'])) {
22
            $form = $field['form'];
23
        }
24
        // 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...
25
        // set some default values, so the field will still work
26 68
        if (is_string($field)) {
27 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...
28
        } else {
29 64
            $completeFieldsArray = $field;
30
        }
31
32
        // if this is a relation type field and no corresponding model was specified, get it from the relation method
33
        // defined in the main model
34 68
        if (isset($completeFieldsArray['entity']) && ! isset($completeFieldsArray['model'])) {
35 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...
36
        }
37
38
        // if the label is missing, we should set it
39 68
        if (! isset($completeFieldsArray['label'])) {
40 50
            $completeFieldsArray['label'] = mb_ucfirst(str_replace('_', ' ', $completeFieldsArray['name']));
41
        }
42
43
        // if the field type is missing, we should set it
44 67
        if (! isset($completeFieldsArray['type'])) {
45 63
            $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...
46
        }
47
48
        // if a tab was mentioned, we should enable it
49 67
        if (isset($completeFieldsArray['tab'])) {
50 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...
51 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...
52
            }
53
        }
54
55
        $this->transformFields($form, function ($fields) use ($completeFieldsArray) {
56 67
            $fields[$completeFieldsArray['name']] = $completeFieldsArray;
57
58 67
            return $fields;
59 67
        });
60
61 67
        return $this;
62
    }
63
64
    /**
65
     * Add multiple fields to the create/update form or both.
66
     *
67
     * @param array  $fields The new fields.
68
     * @param string $form   The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
69
     */
70 62
    public function addFields($fields, $form = 'both')
71
    {
72 62
        if (count($fields)) {
73 62
            foreach ($fields as $field) {
74 62
                $this->addField($field, $form);
75
            }
76
        }
77 61
    }
78
79
    /**
80
     * Move the most recently added field after the given target field.
81
     *
82
     * @param string $targetFieldName The target field name.
83
     * @param string $form            The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
84
     */
85 6
    public function afterField($targetFieldName, $form = 'both')
86
    {
87
        $this->transformFields($form, function ($fields) use ($targetFieldName) {
88 6
            return $this->moveField($fields, $targetFieldName, false);
89 6
        });
90 6
    }
91
92
    /**
93
     * Move the most recently added field before the given target field.
94
     *
95
     * @param string $targetFieldName The target field name.
96
     * @param string $form            The CRUD form. Can be 'create', 'update' or 'both'. Default is 'both'.
97
     */
98 7
    public function beforeField($targetFieldName, $form = 'both')
99
    {
100
        $this->transformFields($form, function ($fields) use ($targetFieldName) {
101 7
            return $this->moveField($fields, $targetFieldName, true);
102 7
        });
103 7
    }
104
105
    /**
106
     * Move the most recently added field before or after the given target field. Default is before.
107
     *
108
     * @param array  $fields          The form fields.
109
     * @param string $targetFieldName The target field name.
110
     * @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 132 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...
111
     *
112
     * @return array
113
     */
114 13
    private function moveField($fields, $targetFieldName, $before = true)
115
    {
116 13
        if (array_key_exists($targetFieldName, $fields)) {
117 11
            $targetFieldPosition = $before ? array_search($targetFieldName, array_keys($fields))
118 11
                : array_search($targetFieldName, array_keys($fields)) + 1;
119
120 11
            if ($targetFieldPosition >= (count($fields) - 1)) {
121
                // target field name is same as element
122 3
                return $fields;
123
            }
124
125 9
            $element = array_pop($fields);
126 9
            $beginningArrayPart = array_slice($fields, 0, $targetFieldPosition, true);
127 9
            $endingArrayPart = array_slice($fields, $targetFieldPosition, null, true);
128
129 9
            $fields = array_merge($beginningArrayPart, [$element['name'] => $element], $endingArrayPart);
130
        }
131
132 11
        return $fields;
133
    }
134
135
    /**
136
     * Remove a certain field from the create/update/both forms by its name.
137
     *
138
     * @param string $name Field name (as defined with the addField() procedure)
139
     * @param string $form update/create/both
140
     */
141 4
    public function removeField($name, $form = 'both')
142
    {
143
        $this->transformFields($form, function ($fields) use ($name) {
144 4
            array_forget($fields, $name);
0 ignored issues
show
Deprecated Code introduced by
The function array_forget() has been deprecated with message: Arr::forget() 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...
145
146 4
            return $fields;
147 4
        });
148 4
    }
149
150
    /**
151
     * Remove many fields from the create/update/both forms by their name.
152
     *
153
     * @param array  $array_of_names A simple array of the names of the fields to be removed.
154
     * @param string $form           update/create/both
155
     */
156 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...
157
    {
158 4
        if (! empty($array_of_names)) {
159 4
            foreach ($array_of_names as $name) {
160 4
                $this->removeField($name, $form);
161
            }
162
        }
163 4
    }
164
165
    /**
166
     * Remove all fields from the create/update/both forms.
167
     *
168
     * @param string $form update/create/both
169
     */
170
    public function removeAllFields($form = 'both')
171
    {
172
        $current_fields = $this->getCurrentFields();
173
        if (! empty($current_fields)) {
174
            foreach ($current_fields as $field) {
175
                $this->removeField($field['name'], $form);
176
            }
177
        }
178
    }
179
180
    /**
181
     * Update value of a given key for a current field.
182
     *
183
     * @param string $field         The field
184
     * @param array  $modifications An array of changes to be made.
185
     * @param string $form          update/create/both
186
     */
187
    public function modifyField($field, $modifications, $form = 'both')
188
    {
189
        foreach ($modifications as $key => $newValue) {
190
            switch (strtolower($form)) {
191
          case 'create':
192
              $this->create_fields[$field][$key] = $newValue;
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...
193
              break;
194
195
          case 'update':
196
              $this->update_fields[$field][$key] = $newValue;
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...
197
              break;
198
199
          default:
200
              $this->create_fields[$field][$key] = $newValue;
201
              $this->update_fields[$field][$key] = $newValue;
202
              break;
203
        }
204
        }
205
    }
206
207
    /**
208
     * Set label for a specific field.
209
     *
210
     * @param string $field
211
     * @param string $label
212
     */
213
    public function setFieldLabel($field, $label)
214
    {
215
        if (isset($this->create_fields[$field])) {
216
            $this->create_fields[$field]['label'] = $label;
217
        }
218
        if (isset($this->update_fields[$field])) {
219
            $this->update_fields[$field]['label'] = $label;
220
        }
221
    }
222
223
    /**
224
     * Check if field is the first of its type in the given fields array.
225
     * 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...
226
     *
227
     * @param array $field        The current field being tested if it's the first of its type.
228
     *
229
     * @return bool true/false
230
     */
231 3
    public function checkIfFieldIsFirstOfItsType($field)
232
    {
233 3
        $fields_array = $this->getCurrentFields();
234 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...
235
236 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...
237 1
            return true;
238
        }
239
240 2
        return false;
241
    }
242
243
    /**
244
     * Decode attributes that are casted as array/object/json in the model.
245
     * So that they are not json_encoded twice before they are stored in the db
246
     * (once by Backpack in front-end, once by Laravel Attribute Casting).
247
     */
248 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...
249
    {
250
        // get the right fields according to the form type (create/update)
251 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...
252 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...
253
254 5
        foreach ($fields as $field) {
255
256
            // Test the field is castable
257 5
            if (isset($field['name']) && array_key_exists($field['name'], $casted_attributes)) {
258
259
                // Handle JSON field types
260 5
                $jsonCastables = ['array', 'object', 'json'];
261 5
                $fieldCasting = $casted_attributes[$field['name']];
262
263 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...
264
                    try {
265
                        $data[$field['name']] = json_decode($data[$field['name']]);
266
                    } catch (\Exception $e) {
267 5
                        $data[$field['name']] = [];
268
                    }
269
                }
270
            }
271
        }
272
273 5
        return $data;
274
    }
275
276
    /**
277
     * @return array
278
     */
279 12
    public function getCurrentFields()
280
    {
281 12
        if ($this->entry) {
282 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...
283
        }
284
285 11
        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...
286
    }
287
288
    /**
289
     * Order the CRUD fields in the given form. If certain fields are missing from the given order array, they will be
290
     * pushed to the new fields array in the original order.
291
     *
292
     * @param array  $order An array of field names in the desired order.
293
     * @param string $form  The CRUD form. Can be 'create', 'update' or 'both'.
294
     */
295 7
    public function orderFields($order, $form = 'both')
296
    {
297
        $this->transformFields($form, function ($fields) use ($order) {
298 7
            return $this->applyOrderToFields($fields, $order);
299 7
        });
300 7
    }
301
302
    /**
303
     * Apply the given order to the fields and return the new array.
304
     *
305
     * @param array $fields The fields array.
306
     * @param array $order  The desired field order array.
307
     *
308
     * @return array The ordered fields array.
309
     */
310 7
    private function applyOrderToFields($fields, $order)
311
    {
312 7
        $orderedFields = [];
313 7
        foreach ($order as $fieldName) {
314 6
            if (array_key_exists($fieldName, $fields)) {
315 6
                $orderedFields[$fieldName] = $fields[$fieldName];
316
            }
317
        }
318
319 7
        if (empty($orderedFields)) {
320 2
            return $fields;
321
        }
322
323 5
        $remaining = array_diff_key($fields, $orderedFields);
324
325 5
        return array_merge($orderedFields, $remaining);
326
    }
327
328
    /**
329
     * Set the order of the CRUD fields.
330
     *
331
     * @param array $fields Fields order.
332
     *
333
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
334
     * @see        Fields::orderFields() to order the CRUD fields.
335
     */
336
    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...
337
    {
338
        // not implemented
339
    }
340
341
    /**
342
     * Set the order of the CRUD fields.
343
     *
344
     * @param array $fields Fields order.
345
     *
346
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
347
     * @see        Fields::orderFields() to order the CRUD fields.
348
     */
349
    public function setFieldsOrder($fields)
350
    {
351
        $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...
352
    }
353
354
    /**
355
     * Apply the given callback to the form fields.
356
     *
357
     * @param string   $form     The CRUD form. Can be 'create', 'update' or 'both'.
358
     * @param callable $callback The callback function to run for the given form fields.
359
     */
360 67
    private function transformFields($form, callable $callback)
361
    {
362 67
        switch (strtolower($form)) {
363 67
            case 'create':
364 14
                $this->create_fields = $callback($this->create_fields);
365 14
                break;
366
367 59
            case 'update':
368 15
                $this->update_fields = $callback($this->update_fields);
369 15
                break;
370
371
            default:
372 50
                $this->create_fields = $callback($this->create_fields);
373 50
                $this->update_fields = $callback($this->update_fields);
374 50
                break;
375
        }
376 67
    }
377
}
378