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 (#1522)
by Owen
08:34
created

Search::applySearchTerm()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 1
nop 1
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
ccs 0
cts 6
cp 0
crap 12
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
15
    /**
16
     * Add conditions to the CRUD query for a particular search term.
17
     *
18
     * @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...
19
     */
20
    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...
21
    {
22
        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...
23
            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...
24
                if (! isset($column['type'])) {
25
                    abort(400, 'Missing column type when trying to apply search term.');
26
                }
27
28
                $this->applySearchLogicForColumn($query, $column, $searchTerm);
29
            }
30
        });
31
    }
32
33
    /**
34
     * Apply the search logic for each CRUD column.
35
     */
36
    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...
37
    {
38
        // if there's a particular search logic defined, apply that one
39
        if (isset($column['searchLogic'])) {
40
            $searchLogic = $column['searchLogic'];
41
42
            if (is_callable($searchLogic)) {
43
                return $searchLogic($query, $column, $searchTerm);
44
            }
45
46
            if ($searchLogic == false) {
47
                return;
48
            }
49
        }
50
51
        // sensible fallback search logic, if none was explicitly given
52
        if ($column['tableColumn']) {
53
            $columnType = isset($column['search_as']) ? $column['search_as'] : $column['type'];
54
55
            switch ($columnType) {
56
                case 'email':
57
                case 'date':
58
                case 'datetime':
59
                case 'text':
60
                    $query->orWhere($column['name'], 'like', '%'.$searchTerm.'%');
61
                    break;
62
63
                case 'select':
64
                case 'select_multiple':
65
                    $query->orWhereHas($column['entity'], function ($q) use ($column, $searchTerm) {
66
                        $q->where($column['attribute'], 'like', '%'.$searchTerm.'%');
67
                    });
68
                    break;
69
70
                default:
71
                    return;
72
                    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...
73
            }
74
        }
75
    }
76
77
    /**
78
     * Tell the list view to use AJAX for loading multiple rows.
79
     *
80 1
     * @deprecated 3.3.0 All tables are AjaxTables starting with 3.3.0.
81
     */
82 1
    public function enableAjaxTable()
83 1
    {
84
        $this->ajax_table = true;
85
    }
86
87
    /**
88
     * Check if ajax is enabled for the table view.
89
     *
90
     * @deprecated 3.3.0 Since all tables use ajax, this will soon be removed.
91 2
     * @return bool
92
     */
93 2
    public function ajaxTable()
94
    {
95
        return $this->ajax_table;
96
    }
97
98
    /**
99
     * Get the HTML of the cells in a table row, for a certain DB entry.
100
     * @param  Entity $entry A db entry of the current entity;
101
     * @param  int The number shown to the user as row number (index);
102
     * @return array         Array of HTML cell contents.
103
     */
104
    public function getRowViews($entry, $rowNumber = false)
105
    {
106
        $row_items = [];
107
108
        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...
109
            $row_items[] = $this->getCellView($column, $entry, $rowNumber);
110
        }
111
112
        // add the buttons as the last column
113
        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...
114
            $row_items[] = \View::make('crud::inc.button_stack', ['stack' => 'line'])
115
                                ->with('crud', $this)
116
                                ->with('entry', $entry)
117
                                ->with('row_number', $rowNumber)
118
                                ->render();
119
        }
120
121
        // add the details_row button to the first column
122
        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...
123
            $details_row_button = \View::make('crud::columns.details_row_button')
124
                                           ->with('crud', $this)
125
                                           ->with('entry', $entry)
126
                                           ->with('row_number', $rowNumber)
127
                                           ->render();
128
            $row_items[0] = $details_row_button.$row_items[0];
129
        }
130
131
        return $row_items;
132
    }
133
134
    /**
135
     * Get the HTML of a cell, using the column types.
136
     * @param  array $column
137
     * @param  Entity $entry A db entry of the current entity;
138
     * @param  int The number shown to the user as row number (index);
139
     * @return HTML
140
     */
141
    public function getCellView($column, $entry, $rowNumber = false)
142
    {
143
        return $this->renderCellView($this->getCellViewName($column), $column, $entry, $rowNumber);
144
    }
145
146
    /**
147
     * Get the name of the view to load for the cell.
148
     * @param $column
149
     * @return string
150
     */
151
    private function getCellViewName($column)
152
    {
153
        // return custom column if view_namespace attribute is set
154
        if (isset($column['view_namespace']) && isset($column['type'])) {
155
            return $column['view_namespace'].'.'.$column['type'];
156
        }
157
158
        if (isset($column['type'])) {
159
            // if the column has been overwritten return that one
160
            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...
161
                return 'vendor.backpack.crud.columns.'.$column['type'];
162
            }
163
164
            // return the column from the package
165
            return 'crud::columns.'.$column['type'];
166
        }
167
168
        // fallback to text column
169
        return 'crud::columns.text';
170
    }
171
172
    /**
173
     * Render the given view.
174
     * @param $view
175
     * @param $column
176
     * @param $entry
177
     * @param  int The number shown to the user as row number (index);
178
     * @return mixed
179
     */
180
    private function renderCellView($view, $column, $entry, $rowNumber = false)
181
    {
182
        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...
183
            $view = 'crud::columns.text'; // fallback to text column
184
        }
185
186
        return \View::make($view)
187
            ->with('crud', $this)
188
            ->with('column', $column)
189
            ->with('entry', $entry)
190
            ->with('rowNumber', $rowNumber)
191
            ->render();
192
    }
193
194
    /**
195
     * Created the array to be fed to the data table.
196
     *
197
     * @param $entries Eloquent results.
198
     * @return array
199
     */
200
    public function getEntriesAsJsonForDatatables($entries, $totalRows, $filteredRows, $startIndex = false)
201
    {
202
        $rows = [];
203
204
        foreach ($entries as $row) {
205
            $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...
206
        }
207
208
        return [
209
            '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...
210
            'recordsTotal'    => $totalRows,
211
            'recordsFiltered' => $filteredRows,
212
            'data'            => $rows,
213
        ];
214
    }
215
}
216