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 (#1505)
by Oliver
05:09
created

Search   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 258
Duplicated Lines 0 %

Coupling/Cohesion

Components 4
Dependencies 0

Test Coverage

Coverage 6.25%

Importance

Changes 0
Metric Value
dl 0
loc 258
ccs 5
cts 80
cp 0.0625
rs 9.36
c 0
b 0
f 0
wmc 38
lcom 4
cbo 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A applySearchTerm() 0 12 3
C applySearchLogicForColumn() 0 47 12
A enableAjaxTable() 0 4 1
A ajaxTable() 0 4 1
A setResponsiveTable() 0 4 1
A getCellView() 0 4 1
A getCellViewName() 0 20 5
A getResponsiveTable() 0 8 2
A enableResponsiveTable() 0 4 1
A disableResponsiveTable() 0 4 1
A getRowViews() 0 29 4
A renderCellView() 0 13 2
A getEntriesAsJsonForDatatables() 0 15 4
1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
trait Search
6
{
7
    /*
8
    |--------------------------------------------------------------------------
9
    |                                   SEARCH
10
    |--------------------------------------------------------------------------
11
    */
12
13
    public $ajax_table = true;
14
    public $responsive_table;
15
16
    /**
17
     * Add conditions to the CRUD query for a particular search term.
18
     *
19
     * @param  [string] $searchTerm Whatever string the user types in the search bar.
0 ignored issues
show
Documentation introduced by
The doc-type [string] 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...
20
     */
21
    public function applySearchTerm($searchTerm)
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...
22
    {
23
        return $this->query->where(function ($query) use ($searchTerm) {
0 ignored issues
show
Bug introduced by
The property query 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...
24
            foreach ($this->getColumns() as $column) {
0 ignored issues
show
Bug introduced by
It seems like getColumns() 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...
25
                if (! isset($column['type'])) {
26
                    abort(400, 'Missing column type when trying to apply search term.');
27
                }
28
29
                $this->applySearchLogicForColumn($query, $column, $searchTerm);
30
            }
31
        });
32
    }
33
34
    /**
35
     * Apply the search logic for each CRUD column.
36
     */
37
    public function applySearchLogicForColumn($query, $column, $searchTerm)
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...
38
    {
39
        $columnType = $column['type'];
40
41
        // if there's a particular search logic defined, apply that one
42
        if (isset($column['searchLogic'])) {
43
            $searchLogic = $column['searchLogic'];
44
45
            // if a closure was passed, execute it
46
            if (is_callable($searchLogic)) {
47
                return $searchLogic($query, $column, $searchTerm);
48
            }
49
50
            // if a string was passed, search like it was that column type
51
            if (is_string($searchLogic)) {
52
                $columnType = $searchLogic;
53
            }
54
55
            // if false was passed, don't search this column
56
            if ($searchLogic == false) {
57
                return;
58
            }
59
        }
60
61
        // sensible fallback search logic, if none was explicitly given
62
        if ($column['tableColumn']) {
63
            switch ($columnType) {
64
                case 'email':
65
                case 'date':
66
                case 'datetime':
67
                case 'text':
68
                    $query->orWhere($column['name'], 'like', '%'.$searchTerm.'%');
69
                    break;
70
71
                case 'select':
72
                case 'select_multiple':
73
                    $query->orWhereHas($column['entity'], function ($q) use ($column, $searchTerm) {
74
                        $q->where($column['attribute'], 'like', '%'.$searchTerm.'%');
75
                    });
76
                    break;
77
78
                default:
79
                    return;
80 1
                    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...
81
            }
82 1
        }
83 1
    }
84
85
    /**
86
     * Tell the list view to use AJAX for loading multiple rows.
87
     *
88
     * @deprecated 3.3.0 All tables are AjaxTables starting with 3.3.0.
89
     */
90
    public function enableAjaxTable()
91 2
    {
92
        $this->ajax_table = true;
93 2
    }
94
95
    /**
96
     * Check if ajax is enabled for the table view.
97
     *
98
     * @deprecated 3.3.0 Since all tables use ajax, this will soon be removed.
99
     * @return bool
100
     */
101
    public function ajaxTable()
102
    {
103
        return $this->ajax_table;
104
    }
105
106
    /**
107
     * Tell the list view to NOT show a reponsive DataTable.
108
     * @param  bool $value
109
     */
110
    public function setResponsiveTable($value = true)
111
    {
112
        $this->responsive_table = $value;
113
    }
114
115
    /**
116
     * Check if responsiveness is enabled for the table view.
117
     *
118
     * @return bool
119
     */
120
    public function getResponsiveTable()
121
    {
122
        if ($this->responsive_table !== null) {
123
            return $this->responsive_table;
124
        }
125
126
        return config('backpack.crud.responsive_table');
127
    }
128
129
    /**
130
     * Remember to show a responsive table.
131
     */
132
    public function enableResponsiveTable()
133
    {
134
        $this->setResponsiveTable(true);
135
    }
136
137
    /**
138
     * Remember to show a table with horizontal scrolling.
139
     */
140
    public function disableResponsiveTable()
141
    {
142
        $this->setResponsiveTable(false);
143
    }
144
145
    /**
146
     * Get the HTML of the cells in a table row, for a certain DB entry.
147
     * @param  Entity $entry A db entry of the current entity;
148
     * @param  int The number shown to the user as row number (index);
149
     * @return array         Array of HTML cell contents.
150
     */
151
    public function getRowViews($entry, $rowNumber = false)
152
    {
153
        $row_items = [];
154
155
        foreach ($this->columns as $key => $column) {
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...
156
            $row_items[] = $this->getCellView($column, $entry, $rowNumber);
157
        }
158
159
        // add the buttons as the last column
160
        if ($this->buttons->where('stack', 'line')->count()) {
0 ignored issues
show
Bug introduced by
The property buttons 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...
161
            $row_items[] = \View::make('crud::inc.button_stack', ['stack' => 'line'])
162
                                ->with('crud', $this)
163
                                ->with('entry', $entry)
164
                                ->with('row_number', $rowNumber)
165
                                ->render();
166
        }
167
168
        // add the details_row button to the first column
169
        if ($this->details_row) {
0 ignored issues
show
Bug introduced by
The property details_row 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...
170
            $details_row_button = \View::make('crud::columns.details_row_button')
171
                                           ->with('crud', $this)
172
                                           ->with('entry', $entry)
173
                                           ->with('row_number', $rowNumber)
174
                                           ->render();
175
            $row_items[0] = $details_row_button.$row_items[0];
176
        }
177
178
        return $row_items;
179
    }
180
181
    /**
182
     * Get the HTML of a cell, using the column types.
183
     * @param  array $column
184
     * @param  Entity $entry A db entry of the current entity;
185
     * @param  int The number shown to the user as row number (index);
186
     * @return HTML
187
     */
188
    public function getCellView($column, $entry, $rowNumber = false)
189
    {
190
        return $this->renderCellView($this->getCellViewName($column), $column, $entry, $rowNumber);
191
    }
192
193
    /**
194
     * Get the name of the view to load for the cell.
195
     * @param $column
196
     * @return string
197
     */
198
    private function getCellViewName($column)
199
    {
200
        // return custom column if view_namespace attribute is set
201
        if (isset($column['view_namespace']) && isset($column['type'])) {
202
            return $column['view_namespace'].'.'.$column['type'];
203
        }
204
205
        if (isset($column['type'])) {
206
            // if the column has been overwritten return that one
207
            if (view()->exists('vendor.backpack.crud.columns.'.$column['type'])) {
0 ignored issues
show
Bug introduced by
The method exists does only exist in Illuminate\Contracts\View\Factory, but not in Illuminate\View\View.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
208
                return 'vendor.backpack.crud.columns.'.$column['type'];
209
            }
210
211
            // return the column from the package
212
            return 'crud::columns.'.$column['type'];
213
        }
214
215
        // fallback to text column
216
        return 'crud::columns.text';
217
    }
218
219
    /**
220
     * Render the given view.
221
     * @param $view
222
     * @param $column
223
     * @param $entry
224
     * @param  int The number shown to the user as row number (index);
225
     * @return mixed
226
     */
227
    private function renderCellView($view, $column, $entry, $rowNumber = false)
228
    {
229
        if (! view()->exists($view)) {
0 ignored issues
show
Bug introduced by
The method exists does only exist in Illuminate\Contracts\View\Factory, but not in Illuminate\View\View.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
230
            $view = 'crud::columns.text'; // fallback to text column
231
        }
232
233
        return \View::make($view)
234
            ->with('crud', $this)
235
            ->with('column', $column)
236
            ->with('entry', $entry)
237
            ->with('rowNumber', $rowNumber)
238
            ->render();
239
    }
240
241
    /**
242
     * Created the array to be fed to the data table.
243
     *
244
     * @param $entries Eloquent results.
245
     * @return array
246
     */
247
    public function getEntriesAsJsonForDatatables($entries, $totalRows, $filteredRows, $startIndex = false)
248
    {
249
        $rows = [];
250
251
        foreach ($entries as $row) {
252
            $rows[] = $this->getRowViews($row, $startIndex === false ? false : ++$startIndex);
0 ignored issues
show
Documentation introduced by
$startIndex === false ? false : ++$startIndex is of type integer|double, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
253
        }
254
255
        return [
256
            'draw'            => (isset($this->request['draw']) ? (int) $this->request['draw'] : 0),
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...
257
            'recordsTotal'    => $totalRows,
258
            'recordsFiltered' => $filteredRows,
259
            'data'            => $rows,
260
        ];
261
    }
262
}
263