GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — new (#876)
by
unknown
13:54
created

DisplayDatatablesAsync::applySearch()   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 16
nc 2
nop 2
dl 0
loc 27
rs 5.3846
c 0
b 0
f 0
1
<?php
2
3
namespace SleepingOwl\Admin\Display;
4
5
use Request;
6
use Illuminate\Routing\Router;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Builder;
9
use SleepingOwl\Admin\Display\Column\Link;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, SleepingOwl\Admin\Display\Link. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
use SleepingOwl\Admin\Display\Column\Text;
11
use SleepingOwl\Admin\Display\Column\Email;
12
use SleepingOwl\Admin\Display\Column\Control;
13
use SleepingOwl\Admin\Contracts\WithRoutesInterface;
14
use SleepingOwl\Admin\Contracts\Display\ColumnInterface;
15
use SleepingOwl\Admin\Contracts\Display\ColumnMetaInterface;
16
17
class DisplayDatatablesAsync extends DisplayDatatables implements WithRoutesInterface
18
{
19
    /**
20
     * Register display routes.
21
     *
22
     * @param Router $router
23
     *
24
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
25
     */
26
    public static function registerRoutes(Router $router)
27
    {
28
        $routeName = 'admin.display.async';
29
        if (! $router->has($routeName)) {
30
            $router->get('{adminModel}/async/{adminDisplayName?}', [
31
                'as'   => $routeName,
32
                'uses' => 'SleepingOwl\Admin\Http\Controllers\DisplayController@async',
0 ignored issues
show
Bug introduced by
The controller App\Http\Controllers\Sle...llers\DisplayController does not seem to exist.

If there is a route defined but the controller class cannot be found there are two options: 1. the controller class needs to be implemented or 2. the route is outdated and can be removed.

If ?FooController? was found and ?BarController? is missing for the following example, either the controller should be implemented or the route should be removed:

$app->group(['as' => 'foo', 'prefix' => 'foo', 'namespace' => 'Foo'], function($app) {
    $app->group(['as' => 'foo', 'prefix' => 'foo'], function($app) {
        $app->get('/all/{from}/{to}', ['as' => 'all', 'uses' => 'FooController@getFoo']);
        $app->get('/all/{from}/{to}', ['as' => 'all', 'uses' => 'BarController@getBar']);
    });
});
Loading history...
33
            ]);
34
        }
35
36
        $routeName = 'admin.display.async.inlineEdit';
37
        if (! $router->has($routeName)) {
38
            $router->post('{adminModel}/async/{adminDisplayName?}', [
39
                'as'   => $routeName,
40
                'uses' => 'SleepingOwl\Admin\Http\Controllers\AdminController@inlineEdit',
0 ignored issues
show
Bug introduced by
The controller App\Http\Controllers\Sle...rollers\AdminController does not seem to exist.

If there is a route defined but the controller class cannot be found there are two options: 1. the controller class needs to be implemented or 2. the route is outdated and can be removed.

If ?FooController? was found and ?BarController? is missing for the following example, either the controller should be implemented or the route should be removed:

$app->group(['as' => 'foo', 'prefix' => 'foo', 'namespace' => 'Foo'], function($app) {
    $app->group(['as' => 'foo', 'prefix' => 'foo'], function($app) {
        $app->get('/all/{from}/{to}', ['as' => 'all', 'uses' => 'FooController@getFoo']);
        $app->get('/all/{from}/{to}', ['as' => 'all', 'uses' => 'BarController@getBar']);
    });
});
Loading history...
41
            ]);
42
        }
43
    }
44
45
    protected $payload;
46
    /**
47
     * @var string
48
     */
49
    protected $name;
50
51
    /**
52
     * @param string|null $name
53
     */
54
    protected $distinct;
55
56
    /**
57
     * @var
58
     */
59
    protected $displaySearch = false;
60
61
    /**
62
     * @var
63
     */
64
    protected $displayLength = false;
65
66
    /**
67
     * DisplayDatatablesAsync constructor.
68
     *
69
     * @param string|null $name
70
     * @param string|null $distinct
71
     */
72
    public function __construct($name = null, $distinct = null)
73
    {
74
        parent::__construct();
75
76
        $this->setName($name);
77
        $this->setDistinct($distinct);
78
79
        $this->getColumns()->setView('display.extensions.columns_async');
80
    }
81
82
    /**
83
     * Initialize display.
84
     */
85
    public function initialize()
86
    {
87
        parent::initialize();
88
89
        $attributes = Request::all();
90
        array_unshift($attributes, $this->getName());
91
        array_unshift($attributes, $this->getModelConfiguration()->getAlias());
92
93
        $this->setHtmlAttribute('style', 'width:100%');
94
        $this->setHtmlAttribute('data-url', route('admin.display.async', $attributes));
95
        $this->setHtmlAttribute('data-payload', json_encode($this->payload));
96
97
        if ($this->getDisplaySearch()) {
98
            $this->setHtmlAttribute('data-display-search', 1);
99
        }
100
101
        if ($this->getDisplayLength()) {
102
            $this->setHtmlAttribute('data-display-dtlength', 1);
103
        }
104
    }
105
106
    /**
107
     * @param bool $length
108
     * @return $this
109
     */
110
    public function setDisplayLength($length)
111
    {
112
        $this->displayLength = $length;
113
114
        return $this;
115
    }
116
117
    /**
118
     * @return bool
119
     */
120
    public function getDisplayLength()
121
    {
122
        return $this->displayLength;
123
    }
124
125
    /**
126
     * @param $search
127
     * @return $this
128
     */
129
    public function setDisplaySearch($search)
130
    {
131
        $this->displaySearch = $search;
132
133
        return $this;
134
    }
135
136
    /**
137
     * @return bool
138
     */
139
    public function getDisplaySearch()
140
    {
141
        return $this->displaySearch;
142
    }
143
144
    /**
145
     * @return string
146
     */
147
    public function getName()
148
    {
149
        return $this->name;
150
    }
151
152
    /**
153
     * @param string $name
154
     *
155
     * @return $this
156
     */
157
    public function setName($name)
158
    {
159
        $this->name = $name;
160
161
        return $this;
162
    }
163
164
    /**
165
     * @return mixed
166
     */
167
    public function getDistinct()
168
    {
169
        return $this->distinct;
170
    }
171
172
    /**
173
     * @param mixed $distinct
174
     *
175
     * @return $this
176
     */
177
    public function setDistinct($distinct)
178
    {
179
        $this->distinct = $distinct;
180
181
        return $this;
182
    }
183
184
    /**
185
     * Render async request.
186
     *
187
     * @param \Illuminate\Http\Request $request
188
     *
189
     * @return array
190
     */
191
    public function renderAsync(\Illuminate\Http\Request $request)
192
    {
193
        $query = $this->getRepository()->getQuery();
194
        $totalCount = $query->count();
195
        $filteredCount = 0;
196
197
        if (! is_null($this->distinct)) {
198
            $filteredCount = $query->distinct()->count($this->getDistinct());
199
        }
200
201
        $this->modifyQuery($query);
202
        $this->applySearch($query, $request);
203
204
        if (is_null($this->distinct)) {
205
            $countQuery = clone $query;
206
            $countQuery->getQuery()->orders = null;
207
            $filteredCount = $countQuery->count();
208
        }
209
210
        $this->applyOffset($query, $request);
211
        $collection = $query->get();
212
213
        return $this->prepareDatatablesStructure($request, $collection, $totalCount, $filteredCount);
0 ignored issues
show
Bug introduced by
It seems like $totalCount can also be of type Illuminate\Database\Eloquent\Builder; however, parameter $totalCount of SleepingOwl\Admin\Displa...reDatatablesStructure() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

213
        return $this->prepareDatatablesStructure($request, $collection, /** @scrutinizer ignore-type */ $totalCount, $filteredCount);
Loading history...
214
    }
215
216
    /**
217
     * Apply offset and limit to the query.
218
     *
219
     * @param $query
220
     * @param \Illuminate\Http\Request $request
221
     */
222
    protected function applyOffset($query, \Illuminate\Http\Request $request)
223
    {
224
        $offset = $request->input('start', 0);
225
        $limit = $request->input('length', 10);
226
227
        if ($limit == -1) {
228
            return;
229
        }
230
231
        $query->offset((int) $offset)->limit((int) $limit);
232
    }
233
234
    /**
235
     * Apply search to the query.
236
     *
237
     * @param Builder $query
238
     * @param \Illuminate\Http\Request $request
239
     */
240
    protected function applySearch(Builder $query, \Illuminate\Http\Request $request)
241
    {
242
        $search = $request->input('search.value');
243
        if (empty($search)) {
244
            return;
245
        }
246
247
        $query->where(function (Builder $query) use ($search) {
248
            $columns = $this->getColumns()->all();
249
250
            foreach ($columns as $column) {
251
                if ($column->isSearchable()) {
252
                    if ($column instanceof ColumnInterface) {
253
                        if (($metaInstance = $column->getMetaData()) instanceof ColumnMetaInterface) {
0 ignored issues
show
Bug introduced by
The method getMetaData() does not exist on SleepingOwl\Admin\Contra...Display\ColumnInterface. It seems like you code against a sub-type of said class. However, the method does not exist in SleepingOwl\Admin\Contra...ColumnEditableInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

253
                        if (($metaInstance = $column->/** @scrutinizer ignore-call */ getMetaData()) instanceof ColumnMetaInterface) {
Loading history...
254
                            if (method_exists($metaInstance, 'onSearch')) {
255
                                $metaInstance->onSearch($column, $query, $search);
256
                                continue;
257
                            }
258
                        }
259
260
                        if (is_callable($callback = $column->getSearchCallback())) {
0 ignored issues
show
Bug introduced by
The method getSearchCallback() does not exist on SleepingOwl\Admin\Contra...Display\ColumnInterface. It seems like you code against a sub-type of said class. However, the method does not exist in SleepingOwl\Admin\Contra...ColumnEditableInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

260
                        if (is_callable($callback = $column->/** @scrutinizer ignore-call */ getSearchCallback())) {
Loading history...
261
                            $callback($column, $query, $search);
262
                            continue;
263
                        }
264
                    }
265
266
                    $query->orWhere($column->getName(), 'like', '%'.$search.'%');
267
                }
268
            }
269
        });
270
    }
271
272
    /**
273
     * Convert collection to the datatables structure.
274
     *
275
     * @param \Illuminate\Http\Request $request
276
     * @param array|Collection $collection
277
     * @param int $totalCount
278
     * @param int $filteredCount
279
     *
280
     * @return array
281
     */
282
    protected function prepareDatatablesStructure(
283
        \Illuminate\Http\Request $request,
284
        Collection $collection,
285
        $totalCount,
286
        $filteredCount
287
    ) {
288
        $columns = $this->getColumns();
289
290
        $result = [];
291
        $result['draw'] = $request->input('draw', 0);
292
        $result['recordsTotal'] = $totalCount;
293
        $result['recordsFiltered'] = $filteredCount;
294
        $result['data'] = [];
295
296
        foreach ($collection as $instance) {
297
            $_row = [];
298
299
            foreach ($columns->all() as $column) {
300
                $column->setModel($instance);
301
302
                if ($column instanceof Control) {
303
                    $column->initialize();
304
                }
305
306
                $_row[] = (string) $column;
307
            }
308
309
            $result['data'][] = $_row;
310
        }
311
312
        return $result;
313
    }
314
315
    /**
316
     * @return void
317
     */
318
    public function getCollection()
319
    {
320
    }
321
322
    /**
323
     * @param $payload
324
     */
325
    public function setPayload($payload)
326
    {
327
        $this->payload = $payload;
328
    }
329
330
    /**
331
     * @return mixed
332
     */
333
    public function getPayload()
334
    {
335
        return $this->payload;
336
    }
337
338
    /**
339
     * @return array
340
     */
341
    public function toArray()
342
    {
343
        $params = parent::toArray();
344
        $params['payload'] = $this->payload;
345
346
        return $params;
347
    }
348
}
349