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 (#1505)
by Oliver
05:09
created

Fields::checkIfFieldIsFirstOfItsType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
ccs 4
cts 6
cp 0.6667
crap 2.1481
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
     * Remove all fields from the create/update/both forms.
161
     *
162
     * @param string $form           update/create/both
163
     */
164
    public function removeAllFields($form = 'both')
165
    {
166
        $current_fields = $this->getCurrentFields();
167
        if (! empty($current_fields)) {
168
            foreach ($current_fields as $field) {
169
                $this->removeField($field['name'], $form);
170
            }
171
        }
172
    }
173
174
    /**
175
     * Update value of a given key for a current field.
176
     *
177
     * @param string $field         The field
178
     * @param array  $modifications An array of changes to be made.
179
     * @param string $form          update/create/both
180
     */
181
    public function modifyField($field, $modifications, $form = 'both')
182
    {
183
        foreach ($modifications as $key => $newValue) {
184
            switch (strtolower($form)) {
185
          case 'create':
186
              $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...
187
              break;
188
189
          case 'update':
190
              $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...
191
              break;
192
193
          default:
194
              $this->create_fields[$field][$key] = $newValue;
195
              $this->update_fields[$field][$key] = $newValue;
196
              break;
197
        }
198
        }
199 3
    }
200
201 3
    /**
202
     * Set label for a specific field.
203 2
     *
204 1
     * @param string $field
205
     * @param string $label
206
     */
207 2
    public function setFieldLabel($field, $label)
208
    {
209
        if (isset($this->create_fields[$field])) {
210
            $this->create_fields[$field]['label'] = $label;
211
        }
212
        if (isset($this->update_fields[$field])) {
213
            $this->update_fields[$field]['label'] = $label;
214
        }
215 6
    }
216
217
    /**
218 6
     * Check if field is the first of its type in the given fields array.
219 5
     * 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...
220
     *
221 5
     * @param array $field        The current field being tested if it's the first of its type.
222
     * @param array $fields_array All the fields in that particular form.
223
     *
224 5
     * @return bool true/false
225
     */
226
    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...
227 5
    {
228 5
        $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...
229
230 5
        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...
231
            return true;
232
        }
233
234 5
        return false;
235
    }
236
237
    /**
238
     * Decode attributes that are casted as array/object/json in the model.
239
     * So that they are not json_encoded twice before they are stored in the db
240 5
     * (once by Backpack in front-end, once by Laravel Attribute Casting).
241
     */
242
    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...
243 9
    {
244
        // get the right fields according to the form type (create/update)
245 9
        $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...
246 1
        $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...
247
248
        foreach ($fields as $field) {
249 8
250
            // Test the field is castable
251
            if (isset($field['name']) && array_key_exists($field['name'], $casted_attributes)) {
252
253
                // Handle JSON field types
254
                $jsonCastables = ['array', 'object', 'json'];
255
                $fieldCasting = $casted_attributes[$field['name']];
256
257
                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...
258
                    try {
259
                        $data[$field['name']] = json_decode($data[$field['name']]);
260
                    } catch (\Exception $e) {
261 7
                        $data[$field['name']] = [];
262 7
                    }
263 7
                }
264 7
            }
265
        }
266
267
        return $data;
268
    }
269
270
    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...
271
    {
272
        if ($this->entry) {
273 7
            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...
274
        }
275 7
276 7
        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...
277 6
    }
278 6
279
    /**
280
     * Order the CRUD fields in the given form. If certain fields are missing from the given order array, they will be
281
     * pushed to the new fields array in the original order.
282 7
     *
283 2
     * @param array $order An array of field names in the desired order.
284
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'.
285
     */
286 5
    public function orderFields($order, $form = 'both')
287
    {
288 5
        $this->transformFields($form, function ($fields) use ($order) {
289
            return $this->applyOrderToFields($fields, $order);
290
        });
291
    }
292
293
    /**
294
     * Apply the given order to the fields and return the new array.
295
     *
296
     * @param array $fields The fields array.
297
     * @param array $order The desired field order array.
298
     * @return array The ordered fields array.
299
     */
300
    private function applyOrderToFields($fields, $order)
301
    {
302
        $orderedFields = [];
303
        foreach ($order as $fieldName) {
304
            if (array_key_exists($fieldName, $fields)) {
305
                $orderedFields[$fieldName] = $fields[$fieldName];
306
            }
307
        }
308
309
        if (empty($orderedFields)) {
310
            return $fields;
311
        }
312
313
        $remaining = array_diff_key($fields, $orderedFields);
314
315
        return array_merge($orderedFields, $remaining);
316
    }
317
318
    /**
319
     * Set the order of the CRUD fields.
320
     *
321
     * @param array $fields Fields order.
322
     *
323 66
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
324
     * @see Fields::orderFields() to order the CRUD fields.
325 66
     */
326 66
    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...
327 14
    {
328 14
        // not implemented
329
    }
330 58
331 15
    /**
332 15
     * Set the order of the CRUD fields.
333
     *
334
     * @param array $fields Fields order.
335 49
     *
336 49
     * @deprecated This method was not and will not be implemented since its a duplicate of the orderFields method.
337 49
     * @see Fields::orderFields() to order the CRUD fields.
338
     */
339 66
    public function setFieldsOrder($fields)
340
    {
341
        $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...
342
    }
343
344
    /**
345
     * Apply the given callback to the form fields.
346
     *
347
     * @param string $form The CRUD form. Can be 'create', 'update' or 'both'.
348
     * @param callable $callback The callback function to run for the given form fields.
349
     */
350
    private function transformFields($form, callable $callback)
351
    {
352
        switch (strtolower($form)) {
353
            case 'create':
354
                $this->create_fields = $callback($this->create_fields);
355
                break;
356
357
            case 'update':
358
                $this->update_fields = $callback($this->update_fields);
359
                break;
360
361
            default:
362
                $this->create_fields = $callback($this->create_fields);
363
                $this->update_fields = $callback($this->update_fields);
364
                break;
365
        }
366
    }
367
}
368