Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Push — master ( 0be2ba...247314 )
by Cristian
04:16
created

Columns::remove()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 3
cp 0
crap 2
rs 9.4285
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
        // make sure the column has a type
80 21
        if (! array_key_exists('type', $column_with_details)) {
81 18
            $column_with_details['type'] = 'text';
82
        }
83
84
        // make sure the column has a key
85 21
        if (! array_key_exists('key', $column_with_details)) {
86 21
            $column_with_details['key'] = $column_with_details['name'];
87
        }
88
89
        // check if the column exists in the DB table
90 21
        if ($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...
91 3
            $column_with_details['tableColumn'] = true;
92
        } else {
93 18
            $column_with_details['tableColumn'] = false;
94 18
            $column_with_details['orderable'] = false;
95 18
            $column_with_details['searchLogic'] = false;
96
        }
97
98 21
        array_filter($this->columns[$column_with_details['key']] = $column_with_details);
99
100
        // if this is a relation type field and no corresponding model was specified, get it from the relation method
101
        // defined in the main model
102 21
        if (isset($column_with_details['entity']) && ! isset($column_with_details['model'])) {
103 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...
104
        }
105
106 21
        return $this;
107
    }
108
109
    /**
110
     * Add multiple columns at the end of the CRUD object's "columns" array.
111
     *
112
     * @param [array of columns]
113
     */
114 16
    public function addColumns($columns)
115
    {
116 16
        if (count($columns)) {
117 16
            foreach ($columns as $key => $column) {
118 15
                $this->addColumn($column);
119
            }
120
        }
121 15
    }
122
123
    /**
124
     * Move the most recently added column after the given target column.
125
     *
126
     * @param string|array $targetColumn The target column name or array.
127
     */
128 2
    public function afterColumn($targetColumn)
129
    {
130 2
        $this->moveColumn($targetColumn, false);
131 2
    }
132
133
    /**
134
     * Move the most recently added column before the given target column.
135
     *
136
     * @param string|array $targetColumn The target column name or array.
137
     */
138 2
    public function beforeColumn($targetColumn)
139
    {
140 2
        $this->moveColumn($targetColumn);
141 2
    }
142
143
    /**
144
     * Move the most recently added column before or after the given target column. Default is before.
145
     *
146
     * @param string|array $targetColumn The target column name or array.
147
     * @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...
148
     */
149 4
    private function moveColumn($targetColumn, $before = true)
150
    {
151
        // TODO: this and the moveField method from the Fields trait should be refactored into a single method and moved
152
        //       into a common class
153 4
        $targetColumnName = is_array($targetColumn) ? $targetColumn['name'] : $targetColumn;
154
155 4
        if (array_key_exists($targetColumnName, $this->columns)) {
156 2
            $targetColumnPosition = $before ? array_search($targetColumnName, array_keys($this->columns)) :
157 2
                array_search($targetColumnName, array_keys($this->columns)) + 1;
158
159 2
            $element = array_pop($this->columns);
160 2
            $beginningPart = array_slice($this->columns, 0, $targetColumnPosition, true);
161 2
            $endingArrayPart = array_slice($this->columns, $targetColumnPosition, null, true);
162
163 2
            $this->columns = array_merge($beginningPart, [$element['name'] => $element], $endingArrayPart);
164
        }
165 4
    }
166
167
    /**
168
     * Add the default column type to the given Column, inferring the type from the database column type.
169
     *
170
     * @param [column array]
171
     */
172
    public function addDefaultTypeToColumn($column)
173
    {
174
        if (array_key_exists('name', (array) $column)) {
175
            $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...
176
177
            return array_merge(['type' => $default_type], $column);
178
        }
179
180
        return false;
181
    }
182
183
    /**
184
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
185
     * So we add the field Name as a label - it's better than nothing.
186
     *
187
     * @param [field or column]
188
     */
189 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...
190
    {
191 21
        if (! array_key_exists('label', (array) $array) && array_key_exists('name', (array) $array)) {
192 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...
193
194 7
            return $array;
195
        }
196
197 14
        return $array;
198
    }
199
200
    /**
201
     * Remove a column from the CRUD panel by name.
202
     *
203
     * @param string $column The column name.
204
     */
205 4
    public function removeColumn($column)
206
    {
207 4
        array_forget($this->columns, $column);
208 4
    }
209
210
    /**
211
     * Remove multiple columns from the CRUD panel by name.
212
     *
213
     * @param array $columns Array of column names.
214
     */
215 2
    public function removeColumns($columns)
216
    {
217 2
        if (! empty($columns)) {
218 2
            foreach ($columns as $columnName) {
219 2
                $this->removeColumn($columnName);
220
            }
221
        }
222 2
    }
223
224
    /**
225
     * Remove an entry from an array.
226
     *
227
     * @param string $entity
228
     * @param array $fields
229
     * @return array values
230
     *
231
     * @deprecated This method is no longer used by internal code and is not recommended as it does not preserve the
232
     *             target array keys.
233
     * @see Columns::removeColumn() to remove a column from the CRUD panel by name.
234
     * @see Columns::removeColumns() to remove multiple columns from the CRUD panel by name.
235
     */
236
    public function remove($entity, $fields)
237
    {
238
        return array_values(array_filter($this->{$entity}, function ($field) use ($fields) {
239
            return ! in_array($field['name'], (array) $fields);
240
        }));
241
    }
242
243
    /**
244
     * Change attributes for multiple columns.
245
     *
246
     * @param [columns arrays]
247
     * @param [attributes and values array]
248
     */
249
    public function setColumnsDetails($columns, $attributes)
250
    {
251
        $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...
252
    }
253
254
    /**
255
     * Change attributes for a certain column.
256
     *
257
     * @param [string] Column name.
258
     * @param [attributes and values array]
259
     */
260
    public function setColumnDetails($column, $attributes)
261
    {
262
        $this->setColumnsDetails([$column], $attributes);
263
    }
264
265
    /**
266
     * Set label for a specific column.
267
     *
268
     * @param string $column
269
     * @param string $label
270
     */
271
    public function setColumnLabel($column, $label)
272
    {
273
        $this->setColumnDetails($column, ['label' => $label]);
274
    }
275
276
    /**
277
     * Get the relationships used in the CRUD columns.
278
     * @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...
279
     */
280 3
    public function getColumnsRelationships()
281
    {
282 3
        $columns = $this->getColumns();
283
284 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...
285 2
            return $value == null;
286 3
        })->toArray();
287
    }
288
289
    /**
290
     * Order the CRUD columns. If certain columns are missing from the given order array, they will be pushed to the
291
     * new columns array in the original order.
292
     *
293
     * @param array $order An array of column names in the desired order.
294
     */
295 5
    public function orderColumns($order)
296
    {
297 5
        $orderedColumns = [];
298 5
        foreach ($order as $columnName) {
299 4
            if (array_key_exists($columnName, $this->columns)) {
300 4
                $orderedColumns[$columnName] = $this->columns[$columnName];
301
            }
302
        }
303
304 5
        if (empty($orderedColumns)) {
305 2
            return;
306
        }
307
308 3
        $remaining = array_diff_key($this->columns, $orderedColumns);
309 3
        $this->columns = array_merge($orderedColumns, $remaining);
310 3
    }
311
312
    /**
313
     * Set the order of the CRUD columns.
314
     *
315
     * @param array $columns Column order.
316
     *
317
     * @deprecated This method was not and will not be implemented since it's a duplicate of the orderColumns method.
318
     * @see Columns::orderColumns() to order the CRUD columns.
319
     */
320
    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...
321
    {
322
        // not implemented
323
    }
324
325
    /**
326
     * Set the order of the CRUD columns.
327
     *
328
     * @param array $columns Column order.
329
     *
330
     * @deprecated This method was not and will not be implemented since it's a duplicate of the orderColumns method.
331
     * @see Columns::orderColumns() to order the CRUD columns.
332
     */
333
    public function setColumnsOrder($columns)
334
    {
335
        $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...
336
    }
337
338
    /**
339
     * Get a column by the id, from the associative array.
340
     * @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...
341
     * @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...
342
     */
343
    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...
344
    {
345
        $result = array_slice($this->getColumns(), $column_number, 1);
346
347
        return reset($result);
348
    }
349
    
350 21
    protected function hasColumn($table, $name)
351
	{
352 21
		static $cache = [];
353
		
354 21
		if(isset($cache[$table])){
355 19
			$columns = $cache[$table];
356
		}else{
357 3
			$columns = $cache[$table] = \Schema::getColumnListing($table);
358
		}
359
360 21
		return in_array($name, $columns);
361
	}
362
363
}
364