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 (#282)
by Cristian
03:23
created

Fields::decodeJsonCastedAttributes()   D

Complexity

Conditions 9
Paths 5

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 12
nc 5
nop 3
dl 0
loc 26
rs 4.909
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   $form    The form to add the field to (create/update/both)
15
     */
16
    public function addField($field, $form = 'both')
17
    {
18
        // if the field_defition_array array is a string, it means the programmer was lazy and has only passed the name
19
        // set some default values, so the field will still work
20
        if (is_string($field)) {
21
            $complete_field_array['name'] = $field;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$complete_field_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $complete_field_array = 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...
22
        } else {
23
            $complete_field_array = $field;
24
        }
25
26
        // if the label is missing, we should set it
27
        if (! isset($complete_field_array['label'])) {
28
            $complete_field_array['label'] = ucfirst($complete_field_array['name']);
29
        }
30
31
        // if the field type is missing, we should set it
32
        if (! isset($complete_field_array['type'])) {
33
            $complete_field_array['type'] = $this->getFieldTypeFromDbColumnType($complete_field_array['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...
34
        }
35
36
        // store the field information into the correct variable on the CRUD object
37
        switch (strtolower($form)) {
38
            case 'create':
39
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
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...
40
                break;
41
42
            case 'update':
43
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
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...
44
                break;
45
46
            default:
47
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
48
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
49
                break;
50
        }
51
52
        return $this;
53
    }
54
55
    public function addFields($fields, $form = 'both')
56
    {
57
        if (count($fields)) {
58
            foreach ($fields as $field) {
59
                $this->addField($field, $form);
60
            }
61
        }
62
    }
63
64
    /**
65
     * Moves the recently added field to 'after' the $target_field.
66
     *
67
     * @param $target_field
68
     */
69
    public function afterField($target_field)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $target_field 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...
70
    {
71 View Code Duplication
        foreach ($this->create_fields as $field => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
            if ($value['name'] == $target_field) {
73
                array_splice($this->create_fields, $field + 1, 0, [$field => array_pop($this->create_fields)]);
74
                break;
75
            }
76
        }
77 View Code Duplication
        foreach ($this->update_fields as $field => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
            if ($value['name'] == $target_field) {
79
                array_splice($this->update_fields, $field + 1, 0, [$field => array_pop($this->update_fields)]);
80
                break;
81
            }
82
        }
83
    }
84
85
    /**
86
     * Moves the recently added field to 'before' the $target_field.
87
     *
88
     * @param $target_field
89
     */
90
    public function beforeField($target_field)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $target_field 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...
91
    {
92
        $key = 0;
93 View Code Duplication
        foreach ($this->create_fields as $field => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
            if ($value['name'] == $target_field) {
95
                array_splice($this->create_fields, $key, 0, [$field => array_pop($this->create_fields)]);
96
                break;
97
            }
98
            $key++;
99
        }
100
        $key = 0;
101 View Code Duplication
        foreach ($this->update_fields as $field => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
            if ($value['name'] == $target_field) {
103
                array_splice($this->update_fields, $key, 0, [$field => array_pop($this->update_fields)]);
104
                break;
105
            }
106
            $key++;
107
        }
108
    }
109
110
    /**
111
     * Remove a certain field from the create/update/both forms by its name.
112
     *
113
     * @param string $name Field name (as defined with the addField() procedure)
114
     * @param string $form update/create/both
115
     */
116
    public function removeField($name, $form = 'both')
117
    {
118
        switch (strtolower($form)) {
119
            case 'create':
120
                array_forget($this->create_fields, $name);
121
                break;
122
123
            case 'update':
124
                array_forget($this->update_fields, $name);
125
                break;
126
127
            default:
128
                array_forget($this->create_fields, $name);
129
                array_forget($this->update_fields, $name);
130
                break;
131
        }
132
    }
133
134
    /**
135
     * Remove many fields from the create/update/both forms by their name.
136
     *
137
     * @param array  $array_of_names A simple array of the names of the fields to be removed.
138
     * @param string $form           update/create/both
139
     */
140
    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...
141
    {
142
        if (! empty($array_of_names)) {
143
            foreach ($array_of_names as $name) {
144
                $this->removeField($name, $form);
145
            }
146
        }
147
    }
148
149
    /**
150
     * Check if field is the first of its type in the given fields array.
151
     * 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...
152
     *
153
     * @param array $field        The current field being tested if it's the first of its type.
154
     * @param array $fields_array All the fields in that particular form.
155
     *
156
     * @return bool true/false
157
     */
158
    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...
159
    {
160
        if ($field['name'] == $this->getFirstOfItsTypeInArray($field['type'], $fields_array)['name']) {
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...
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $field['name'] ==...$fields_array)['name'];.
Loading history...
161
            return true;
162
        }
163
164
        return false;
165
    }
166
167
    /**
168
     * Order the fields in a certain way.
169
     *
170
     * @param [string] Column name.
171
     * @param [attributes and values array]
172
     */
173
    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...
174
    {
175
        // TODO
176
    }
177
178
    // ALIAS of setFieldOrder($fields)
179
    public function setFieldsOrder($fields)
180
    {
181
        $this->setFieldOrder($fields);
182
    }
183
184
    /**
185
     * Decode attributes that are casted as array/object/json in the model.
186
     * So that they are not json_encoded twice before they are stored in the db
187
     * (once by Backpack in front-end, once by Laravel Attribute Casting).
188
     */
189
    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...
190
    {
191
        // get the right fields according to the form type (create/update)
192
        $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...
193
194
        foreach ($fields as $field) {
195
196
            // Test the field is castable
197
            if (isset($field['name']) && array_key_exists($field['name'], $this->model->getCasts())) {
198
199
                // Handle JSON field types
200
                $jsonCastables = ['array', 'object', 'json'];
201
                $fieldCasting = $this->model->getCasts()[$field['name']];
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...
202
203
                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 164 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...
204
                    try {
205
                        $data[$field['name']] = json_decode($data[$field['name']]);
206
                    } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Backpack\CRUD\PanelTraits\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
207
                        $data[$field['name']] = [];
208
                    }
209
                }
210
            }
211
        }
212
213
        return $data;
214
    }
215
216
    // ------------
217
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED
218
    // ------------
219
    // TODO: check them
220
221
    public function orderFields($order)
222
    {
223
        $this->setSort('fields', (array) $order);
0 ignored issues
show
Bug introduced by
It seems like setSort() 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...
224
    }
225
226
227
}
228