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 ( abee17...d0fdf9 )
by Cristian
04:01
created

Columns::setColumnLabel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
trait Columns
6
{
7
    // ------------
8
    // COLUMNS
9
    // ------------
10
11
    /**
12
     * Get the CRUD columns.
13
     *
14
     * @return array CRUD columns.
15
     */
16 3
    public function getColumns()
17
    {
18 3
        return $this->columns;
0 ignored issues
show
Bug introduced by
The property columns 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...
19
    }
20
21
    /**
22
     * Add a bunch of column names and their details to the CRUD object.
23
     *
24
     * @param [array or multi-dimensional array]
25
     */
26
    public function setColumns($columns)
27
    {
28
        // clear any columns already set
29
        $this->columns = [];
30
31
        // if array, add a column for each of the items
32
        if (is_array($columns) && count($columns)) {
33
            foreach ($columns as $key => $column) {
34
                // if label and other details have been defined in the array
35
                if (is_array($column)) {
36
                    $this->addColumn($column);
37
                } else {
38
                    $this->addColumn([
39
                                    'name'  => $column,
40
                                    'label' => ucfirst($column),
41
                                    'type'  => 'text',
42
                                ]);
43
                }
44
            }
45
        }
46
47
        if (is_string($columns)) {
48
            $this->addColumn([
49
                                'name'  => $columns,
50
                                'label' => ucfirst($columns),
51
                                'type'  => 'text',
52
                                ]);
53
        }
54
55
        // This was the old setColumns() function, and it did not work:
56
        // $this->columns = array_filter(array_map([$this, 'addDefaultTypeToColumn'], $columns));
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
57
    }
58
59
    /**
60
     * Add a column at the end of to the CRUD object's "columns" array.
61
     *
62
     * @param [string or array]
63
     */
64 21
    public function addColumn($column)
65
    {
66
        // if a string was passed, not an array, change it to an array
67 21
        if (! is_array($column)) {
68 6
            $column = ['name' => $column];
69
        }
70
71
        // make sure the column has a label
72 21
        $column_with_details = $this->addDefaultLabel($column);
73
74
        // make sure the column has a name
75 21
        if (! array_key_exists('name', $column_with_details)) {
76
            $column_with_details['name'] = 'anonymous_column_'.str_random(5);
77
        }
78
79
        // check if the column exists in the database table
80 21
        $columnExistsInDb = $this->hasColumn($this->model->getTable(), $column_with_details['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...
81
82
        // make sure the column has a type
83 21
        if (! array_key_exists('type', $column_with_details)) {
84 18
            $column_with_details['type'] = 'text';
85
        }
86
87
        // make sure the column has a key
88 21
        if (! array_key_exists('key', $column_with_details)) {
89 21
            $column_with_details['key'] = $column_with_details['name'];
90
        }
91
92
        // make sure the column has a tableColumn boolean
93 21
        if (! array_key_exists('tableColumn', $column_with_details)) {
94 21
            $column_with_details['tableColumn'] = $columnExistsInDb ? true : false;
95
        }
96
97
        // make sure the column has a orderable boolean
98 21
        if (! array_key_exists('orderable', $column_with_details)) {
99 21
            $column_with_details['orderable'] = $columnExistsInDb ? true : false;
100
        }
101
102
        // make sure the column has a searchLogic
103 21
        if (! array_key_exists('searchLogic', $column_with_details)) {
104 21
            $column_with_details['searchLogic'] = $columnExistsInDb ? true : false;
105
        }
106
107 21
        array_filter($this->columns[$column_with_details['key']] = $column_with_details);
108
109
        // if this is a relation type field and no corresponding model was specified, get it from the relation method
110
        // defined in the main model
111 21
        if (isset($column_with_details['entity']) && ! isset($column_with_details['model'])) {
112 1
            $column_with_details['model'] = $this->getRelationModel($column_with_details['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...
113
        }
114
115 21
        return $this;
116
    }
117
118
    /**
119
     * Add multiple columns at the end of the CRUD object's "columns" array.
120
     *
121
     * @param [array of columns]
122
     */
123 16
    public function addColumns($columns)
124
    {
125 16
        if (count($columns)) {
126 15
            foreach ($columns as $key => $column) {
127 15
                $this->addColumn($column);
128
            }
129
        }
130 15
    }
131
132
    /**
133
     * Move the most recently added column after the given target column.
134
     *
135
     * @param string|array $targetColumn The target column name or array.
136
     */
137 2
    public function afterColumn($targetColumn)
138
    {
139 2
        $this->moveColumn($targetColumn, false);
140 2
    }
141
142
    /**
143
     * Move the most recently added column before the given target column.
144
     *
145
     * @param string|array $targetColumn The target column name or array.
146
     */
147 2
    public function beforeColumn($targetColumn)
148
    {
149 2
        $this->moveColumn($targetColumn);
150 2
    }
151
152
    /**
153
     * Move the most recently added column before or after the given target column. Default is before.
154
     *
155
     * @param string|array $targetColumn The target column name or array.
156
     * @param bool $before If true, the column will be moved before the target column, otherwise it will be moved after it.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 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...
157
     */
158 4
    private function moveColumn($targetColumn, $before = true)
159
    {
160
        // TODO: this and the moveField method from the Fields trait should be refactored into a single method and moved
161
        //       into a common class
162 4
        $targetColumnName = is_array($targetColumn) ? $targetColumn['name'] : $targetColumn;
163
164 4
        if (array_key_exists($targetColumnName, $this->columns)) {
165 2
            $targetColumnPosition = $before ? array_search($targetColumnName, array_keys($this->columns)) :
166 2
                array_search($targetColumnName, array_keys($this->columns)) + 1;
167
168 2
            $element = array_pop($this->columns);
169 2
            $beginningPart = array_slice($this->columns, 0, $targetColumnPosition, true);
170 2
            $endingArrayPart = array_slice($this->columns, $targetColumnPosition, null, true);
171
172 2
            $this->columns = array_merge($beginningPart, [$element['name'] => $element], $endingArrayPart);
173
        }
174 4
    }
175
176
    /**
177
     * Add the default column type to the given Column, inferring the type from the database column type.
178
     *
179
     * @param [column array]
180
     */
181
    public function addDefaultTypeToColumn($column)
182
    {
183
        if (array_key_exists('name', (array) $column)) {
184
            $default_type = $this->getFieldTypeFromDbColumnType($column['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...
185
186
            return array_merge(['type' => $default_type], $column);
187
        }
188
189
        return false;
190
    }
191
192
    /**
193
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
194
     * So we add the field Name as a label - it's better than nothing.
195
     *
196
     * @param [field or column]
197
     */
198 21
    public function addDefaultLabel($array)
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...
199
    {
200 21
        if (! array_key_exists('label', (array) $array) && array_key_exists('name', (array) $array)) {
201 7
            $array = array_merge(['label' => ucfirst($this->makeLabel($array['name']))], $array);
0 ignored issues
show
Bug introduced by
It seems like makeLabel() 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...
202
203 7
            return $array;
204
        }
205
206 14
        return $array;
207
    }
208
209
    /**
210
     * Remove a column from the CRUD panel by name.
211
     *
212
     * @param string $column The column name.
213
     */
214 4
    public function removeColumn($column)
215
    {
216 4
        array_forget($this->columns, $column);
217 4
    }
218
219
    /**
220
     * Remove multiple columns from the CRUD panel by name.
221
     *
222
     * @param array $columns Array of column names.
223
     */
224 2
    public function removeColumns($columns)
225
    {
226 2
        if (! empty($columns)) {
227 2
            foreach ($columns as $columnName) {
228 2
                $this->removeColumn($columnName);
229
            }
230
        }
231 2
    }
232
233
    /**
234
     * Remove an entry from an array.
235
     *
236
     * @param string $entity
237
     * @param array $fields
238
     * @return array values
239
     *
240
     * @deprecated This method is no longer used by internal code and is not recommended as it does not preserve the
241
     *             target array keys.
242
     * @see Columns::removeColumn() to remove a column from the CRUD panel by name.
243
     * @see Columns::removeColumns() to remove multiple columns from the CRUD panel by name.
244
     */
245
    public function remove($entity, $fields)
246
    {
247
        return array_values(array_filter($this->{$entity}, function ($field) use ($fields) {
248
            return ! in_array($field['name'], (array) $fields);
249
        }));
250
    }
251
252
    /**
253
     * Change attributes for multiple columns.
254
     *
255
     * @param [columns arrays]
256
     * @param [attributes and values array]
257
     */
258
    public function setColumnsDetails($columns, $attributes)
259
    {
260
        $this->sync('columns', $columns, $attributes);
0 ignored issues
show
Bug introduced by
It seems like sync() 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...
261
    }
262
263
    /**
264
     * Change attributes for a certain column.
265
     *
266
     * @param [string] Column name.
267
     * @param [attributes and values array]
268
     */
269
    public function setColumnDetails($column, $attributes)
270
    {
271
        $this->setColumnsDetails([$column], $attributes);
272
    }
273
274
    /**
275
     * Set label for a specific column.
276
     *
277
     * @param string $column
278
     * @param string $label
279
     */
280
    public function setColumnLabel($column, $label)
281
    {
282
        $this->setColumnDetails($column, ['label' => $label]);
283
    }
284
285
    /**
286
     * Get the relationships used in the CRUD columns.
287
     * @return [array] Relationship names
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
288
     */
289 3
    public function getColumnsRelationships()
290
    {
291 3
        $columns = $this->getColumns();
292
293 3
        return collect($columns)->pluck('entity')->reject(function ($value, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
294 2
            return $value == null;
295 3
        })->toArray();
296
    }
297
298
    /**
299
     * Order the CRUD columns. If certain columns are missing from the given order array, they will be pushed to the
300
     * new columns array in the original order.
301
     *
302
     * @param array $order An array of column names in the desired order.
303
     */
304 5
    public function orderColumns($order)
305
    {
306 5
        $orderedColumns = [];
307 5
        foreach ($order as $columnName) {
308 4
            if (array_key_exists($columnName, $this->columns)) {
309 4
                $orderedColumns[$columnName] = $this->columns[$columnName];
310
            }
311
        }
312
313 5
        if (empty($orderedColumns)) {
314 2
            return;
315
        }
316
317 3
        $remaining = array_diff_key($this->columns, $orderedColumns);
318 3
        $this->columns = array_merge($orderedColumns, $remaining);
319 3
    }
320
321
    /**
322
     * Set the order of the CRUD columns.
323
     *
324
     * @param array $columns Column order.
325
     *
326
     * @deprecated This method was not and will not be implemented since it's a duplicate of the orderColumns method.
327
     * @see Columns::orderColumns() to order the CRUD columns.
328
     */
329
    public function setColumnOrder($columns)
0 ignored issues
show
Unused Code introduced by
The parameter $columns 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...
330
    {
331
        // not implemented
332
    }
333
334
    /**
335
     * Set the order of the CRUD columns.
336
     *
337
     * @param array $columns Column order.
338
     *
339
     * @deprecated This method was not and will not be implemented since it's a duplicate of the orderColumns method.
340
     * @see Columns::orderColumns() to order the CRUD columns.
341
     */
342
    public function setColumnsOrder($columns)
343
    {
344
        $this->setColumnOrder($columns);
0 ignored issues
show
Deprecated Code introduced by
The method Backpack\CRUD\PanelTrait...lumns::setColumnOrder() has been deprecated with message: This method was not and will not be implemented since it's a duplicate of the orderColumns 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...
345
    }
346
347
    /**
348
     * Get a column by the id, from the associative array.
349
     * @param  [integer] $column_number Placement inside the columns array.
0 ignored issues
show
Documentation introduced by
The doc-type [integer] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
350
     * @return [array] Column details.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
351
     */
352
    public function findColumnById($column_number)
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...
Coding Style Naming introduced by
The parameter $column_number 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...
353
    {
354
        $result = array_slice($this->getColumns(), $column_number, 1);
355
356
        return reset($result);
357
    }
358
359 21
    protected function hasColumn($table, $name)
360
    {
361 21
        static $cache = [];
362
363 21
        if (isset($cache[$table])) {
364 19
            $columns = $cache[$table];
365
        } else {
366 3
            $columns = $cache[$table] = $this->getSchema()->getColumnListing($table);
0 ignored issues
show
Bug introduced by
It seems like getSchema() 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...
367
        }
368
369 21
        return in_array($name, $columns);
370
    }
371
}
372