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 (#292)
by Owen
02:33
created

Filters::addFilter()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
c 3
b 0
f 0
nc 24
nop 3
dl 0
loc 31
rs 6.7272
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
use Illuminate\Http\Request;
6
7
trait Filters
8
{
9
    // ------------
10
    // FILTERS
11
    // ------------
12
13
    public $filters = [];
14
15
    public function __construct()
16
    {
17
        $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...
18
    }
19
20
    /**
21
     * Add a filter to the CRUD table view.
22
     *
23
     * @param array         $options        Name, type, label, etc.
24
     * @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...
25
     * @param closure       $filter_logic   Query modification (filtering) logic.
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...
26
     */
27
    public function addFilter($options, $values = false, $filter_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...
28
    {
29
        // if a closure was passed as "values"
30
        if (is_callable($values)) {
31
            // get its results
32
            $values = $values();
33
        }
34
35
        // check if another filter with the same name exists
36
        if (! isset($options['name'])) {
37
            abort(500, 'All your filters need names.');
38
        }
39
        if ($this->filters->contains('name', $options['name'])) {
40
            abort(500, "Sorry, you can't have two filters with the same name.");
41
        }
42
43
        // add a new filter to the interface
44
        $filter = new CrudFilter($options, $values, $filter_logic);
45
        $this->filters->push($filter);
46
47
        // if a closure was passed as "filter_logic"
48
        if ($this->doingListOperation() &&
49
            $this->request->has($options['name'])) {
50
            if (is_callable($filter_logic)) {
51
                // apply it
52
                $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...
53
            } else {
54
                $this->addDefaultFilterLogic($filter->name, $filter_logic);
55
            }
56
        }
57
    }
58
59
    public function addDefaultFilterLogic($name, $operator)
60
    {
61
        $input = \Request::all();
62
63
        // if this filter is active (the URL has it as a GET parameter)
64
        switch ($operator) {
65
            // if no operator was passed, just use the equals operator
66
            case false:
67
                $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...
68
                break;
69
70
            case 'scope':
71
                $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...
72
                break;
73
74
            // TODO:
75
            // whereBetween
76
            // whereNotBetween
77
            // whereIn
78
            // whereNotIn
79
            // whereNull
80
            // whereNotNull
81
            // whereDate
82
            // whereMonth
83
            // whereDay
84
            // whereYear
85
            // whereColumn
86
            // like
87
88
            // sql comparison operators
89
            case '=':
90
            case '<=>':
91
            case '<>':
92
            case '!=':
93
            case '>':
94
            case '>=':
95
            case '<':
96
            case '<=':
97
                $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...
98
                break;
99
100
            default:
101
                abort(500, 'Unknown filter operator.');
102
                break;
103
        }
104
    }
105
106
    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...
107
    {
108
        return $this->filters;
109
    }
110
111
    public function removeFilter($name)
112
    {
113
        $this->filters = $this->filters->reject(function ($filter) use ($name) {
114
            return $filter->name == $name;
115
        });
116
    }
117
118
    public function removeAllFilters()
119
    {
120
        $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...
121
    }
122
123
    /**
124
     * Determine if the current CRUD action is a list operation (using standard or ajax DataTables).
125
     * @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...
126
     */
127
    public function doingListOperation()
128
    {
129
        $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...
130
131
        switch ($this->request->url()) {
132
            case url($this->route):
133
                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...
134
                    $this->request->getMethod() == 'PATCH') {
135
                    return false;
136
                }
137
138
                return true;
139
                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...
140
141
            case url($this->route.'/search'):
142
                return true;
143
                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...
144
145
            default:
146
                return false;
147
                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...
148
        }
149
    }
150
}
151
152
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...
153
{
154
    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...
155
    {
156
    }
157
158
    // 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...
159
    // {
160
    //     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...
161
    // }
162
}
163
164
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...
165
{
166
    public $name; // the name of the filtered variable (db column name)
167
    public $type = 'select'; // the name of the filter view that will be loaded
168
    public $label;
169
    public $placeholder;
170
    public $values;
171
    public $options;
172
    public $currentValue;
173
    public $view;
174
175
    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...
176
    {
177
        $this->checkOptionsIntegrity($options);
178
179
        $this->name = $options['name'];
180
        $this->type = $options['type'];
181
        $this->label = $options['label'];
182
183
        if (! isset($options['placeholder'])) {
184
            $this->placeholder = '';
185
        } else {
186
            $this->placeholder = $options['placeholder'];
187
        }
188
189
        $this->values = $values;
190
        $this->options = $options;
191
        $this->view = 'crud::filters.'.$this->type;
192
193
        if (\Request::has($this->name)) {
194
            $this->currentValue = \Request::input($this->name);
195
        }
196
    }
197
198
    public function checkOptionsIntegrity($options)
199
    {
200
        if (! isset($options['name'])) {
201
            abort(500, 'Please make sure all your filters have names.');
202
        }
203
        if (! isset($options['type'])) {
204
            abort(500, 'Please make sure all your filters have types.');
205
        }
206
        if (! \View::exists('crud::filters.'.$options['type'])) {
207
            abort(500, 'No filter view named "'.$options['type'].'.blade.php" was found.');
208
        }
209
        if (! isset($options['label'])) {
210
            abort(500, 'Please make sure all your filters have labels.');
211
        }
212
    }
213
214
    public function isActive()
215
    {
216
        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...
217
            return true;
218
        }
219
220
        return false;
221
    }
222
}
223