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 (#1389)
by Thomas
10:09 queued 04:28
created

CrudFilter   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 68
rs 10
wmc 12
lcom 2
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 3
B checkOptionsIntegrity() 0 15 5
A isActive() 0 8 2
A setView() 0 8 2
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
trait Filters
6
{
7
    public $filters = [];
8
9
    public function filtersEnabled()
10
    {
11
        return ! is_array($this->filters);
12
    }
13
14
    public function filtersDisabled()
15
    {
16
        return is_array($this->filters);
17
    }
18
19
    public function enableFilters()
20
    {
21
        if ($this->filtersDisabled()) {
22
            $this->filters = new FiltersCollection;
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Backpack\CRUD\PanelTraits\FiltersCollection() of type object<Backpack\CRUD\Pan...aits\FiltersCollection> is incompatible with the declared type array of property $filters.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
23
        }
24
    }
25
26
    public function disableFilters()
27
    {
28
        $this->filters = [];
29
    }
30
31
    public function clearFilters()
32
    {
33
        $this->filters = new FiltersCollection;
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Backpack\CRUD\PanelTraits\FiltersCollection() of type object<Backpack\CRUD\Pan...aits\FiltersCollection> is incompatible with the declared type array of property $filters.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
34
    }
35
36
    /**
37
     * Add a filter to the CRUD table view.
38
     *
39
     * @param array         $options        Name, type, label, etc.
40
     * @param array/closure $values         The HTML for the filter.
0 ignored issues
show
Documentation introduced by
The doc-type array/closure could not be parsed: Unknown type name "array/closure" 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...
41
     * @param closure       $filter_logic   Query modification (filtering) logic when filter is active.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $filter_logic not be false|closure?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
42
     * @param closure       $fallback_logic  Query modification (filtering) logic when filter is not active.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $fallback_logic not be false|closure?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
43
     */
44
    public function addFilter($options, $values = false, $filter_logic = false, $fallback_logic = false)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $filter_logic 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...
Coding Style Naming introduced by
The parameter $fallback_logic 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...
45
    {
46
        // if a closure was passed as "values"
47
        if (is_callable($values)) {
48
            // get its results
49
            $values = $values();
50
        }
51
52
        // enable the filters functionality
53
        $this->enableFilters();
54
55
        // check if another filter with the same name exists
56
        if (! isset($options['name'])) {
57
            abort(500, 'All your filters need names.');
58
        }
59
        if ($this->filters->contains('name', $options['name'])) {
60
            abort(500, "Sorry, you can't have two filters with the same name.");
61
        }
62
63
        // add a new filter to the interface
64
        $filter = new CrudFilter($options, $values, $filter_logic);
65
        $this->filters->push($filter);
66
67
        // if a closure was passed as "filter_logic"
68
        if ($this->doingListOperation()) {
69
            if ($this->request->has($options['name'])) {
70
                if (is_callable($filter_logic)) {
71
                    // apply it
72
                    $filter_logic($this->request->input($options['name']));
0 ignored issues
show
Bug introduced by
The property request 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...
73
                } else {
74
                    $this->addDefaultFilterLogic($filter->name, $filter_logic);
75
                }
76
            } else {
77
                //if the filter is not active, but fallback logic was supplied
78
                if (is_callable($fallback_logic)) {
79
                    // apply the fallback logic
80
                    $fallback_logic();
81
                }
82
            }
83
        }
84
    }
85
86
    public function addDefaultFilterLogic($name, $operator)
87
    {
88
        $input = \Request::all();
89
90
        // if this filter is active (the URL has it as a GET parameter)
91
        switch ($operator) {
92
            // if no operator was passed, just use the equals operator
93
            case false:
94
                $this->addClause('where', $name, $input[$name]);
0 ignored issues
show
Bug introduced by
It seems like addClause() 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...
95
                break;
96
97
            case 'scope':
98
                $this->addClause($operator);
0 ignored issues
show
Bug introduced by
It seems like addClause() 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...
99
                break;
100
101
            // TODO:
102
            // whereBetween
103
            // whereNotBetween
104
            // whereIn
105
            // whereNotIn
106
            // whereNull
107
            // whereNotNull
108
            // whereDate
109
            // whereMonth
110
            // whereDay
111
            // whereYear
112
            // whereColumn
113
            // like
114
115
            // sql comparison operators
116
            case '=':
117
            case '<=>':
118
            case '<>':
119
            case '!=':
120
            case '>':
121
            case '>=':
122
            case '<':
123
            case '<=':
124
                $this->addClause('where', $name, $operator, $input[$name]);
0 ignored issues
show
Bug introduced by
It seems like addClause() 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...
125
                break;
126
127
            default:
128
                abort(500, 'Unknown filter operator.');
129
                break;
130
        }
131
    }
132
133
    public function filters()
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...
134
    {
135
        return $this->filters;
136
    }
137
138
    public function removeFilter($name)
139
    {
140
        $this->filters = $this->filters->reject(function ($filter) use ($name) {
141
            return $filter->name == $name;
142
        });
143
    }
144
145
    public function removeAllFilters()
146
    {
147
        $this->filters = collect([]);
0 ignored issues
show
Documentation Bug introduced by
It seems like collect(array()) of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $filters.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
148
    }
149
150
    /**
151
     * Determine if the current CRUD action is a list operation (using standard or ajax DataTables).
152
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
153
     */
154
    public function doingListOperation()
155
    {
156
        $route = $this->route;
0 ignored issues
show
Bug introduced by
The property route 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...
Unused Code introduced by
$route is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
157
158
        switch ($this->request->url()) {
159
            case url($this->route):
160
                if ($this->request->getMethod() == 'POST' ||
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($this->request-...etMethod() == 'PATCH');.
Loading history...
161
                    $this->request->getMethod() == 'PATCH') {
162
                    return false;
163
                }
164
165
                return true;
166
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
167
168
            case url($this->route.'/search'):
169
                return true;
170
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
171
172
            default:
173
                return false;
174
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
175
        }
176
    }
177
}
178
179
class FiltersCollection extends \Illuminate\Support\Collection
0 ignored issues
show
Coding Style Compatibility introduced by
Each trait must be in a file by itself

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
180
{
181
    public function removeFilter($name)
0 ignored issues
show
Unused Code introduced by
The parameter $name 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...
182
    {
183
    }
184
185
    // public function count()
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
186
    // {
187
    //     dd($this);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
188
    // }
189
}
190
191
class CrudFilter
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
192
{
193
    public $name; // the name of the filtered variable (db column name)
194
    public $type = 'select'; // the name of the filter view that will be loaded
195
    public $label;
196
    public $placeholder;
197
    public $values;
198
    public $options;
199
    public $currentValue;
200
    public $view;
201
202
    public function __construct($options, $values, $filter_logic)
0 ignored issues
show
Unused Code introduced by
The parameter $filter_logic 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...
Coding Style Naming introduced by
The parameter $filter_logic 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...
203
    {
204
        $this->checkOptionsIntegrity($options);
205
206
        $this->name = $options['name'];
207
        $this->type = $options['type'];
208
        $this->label = $options['label'];
209
210
        if (! isset($options['placeholder'])) {
211
            $this->placeholder = '';
212
        } else {
213
            $this->placeholder = $options['placeholder'];
214
        }
215
216
        $this->values = $values;
217
        $this->options = $options;
218
        $this->setView();
219
220
        if (\Request::has($this->name)) {
221
            $this->currentValue = \Request::input($this->name);
222
        }
223
    }
224
225
    public function setView()
226
    {
227
        if (isset($this->options['view_namespace'])) {
228
            $this->view = $this->options['view_namespace'] . '.' . $this->type;
229
        } else {
230
            $this->view = 'crud::filters.' . $this->type;
231
        }
232
    }
233
234
    public function checkOptionsIntegrity($options)
235
    {
236
        if (! isset($options['name'])) {
237
            abort(500, 'Please make sure all your filters have names.');
238
        }
239
        if (! isset($options['type'])) {
240
            abort(500, 'Please make sure all your filters have types.');
241
        }
242
        if (! \View::exists('crud::filters.'.$options['type'])) {
243
            abort(500, 'No filter view named "'.$options['type'].'.blade.php" was found.');
244
        }
245
        if (! isset($options['label'])) {
246
            abort(500, 'Please make sure all your filters have labels.');
247
        }
248
    }
249
250
    public function isActive()
251
    {
252
        if (\Request::has($this->name)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return \Request::has($this->name);.
Loading history...
253
            return true;
254
        }
255
256
        return false;
257
    }
258
}
259