Completed
Push — master ( b2b7ae...6094fe )
by Arjay
08:43 queued 06:45
created

QueryBuilderEngine::compileRelationSearch()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 95
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 43
nc 10
nop 4
dl 0
loc 95
rs 8.2079
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Yajra\Datatables\Engines;
4
5
use Closure;
6
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
8
use Illuminate\Database\Eloquent\Relations\MorphToMany;
9
use Illuminate\Database\Query\Builder;
10
use Illuminate\Support\Facades\Config;
11
use Illuminate\Support\Str;
12
use Yajra\Datatables\Helper;
13
use Yajra\Datatables\Request;
14
15
/**
16
 * Class QueryBuilderEngine.
17
 *
18
 * @package Yajra\Datatables\Engines
19
 * @author  Arjay Angeles <[email protected]>
20
 */
21
class QueryBuilderEngine extends BaseEngine
22
{
23
    /**
24
     * @param \Illuminate\Database\Query\Builder $builder
25
     * @param \Yajra\Datatables\Request $request
26
     */
27
    public function __construct(Builder $builder, Request $request)
28
    {
29
        $this->query = $builder;
30
        $this->init($request, $builder);
31
    }
32
33
    /**
34
     * Initialize attributes.
35
     *
36
     * @param  \Yajra\Datatables\Request $request
37
     * @param  \Illuminate\Database\Query\Builder $builder
38
     * @param  string $type
39
     */
40
    protected function init($request, $builder, $type = 'builder')
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
41
    {
42
        $this->request    = $request;
43
        $this->query_type = $type;
44
        $this->columns    = $builder->columns;
45
        $this->connection = $builder->getConnection();
46
        $this->prefix     = $this->connection->getTablePrefix();
47
        $this->database   = $this->connection->getDriverName();
48
        if ($this->isDebugging()) {
49
            $this->connection->enableQueryLog();
50
        }
51
    }
52
53
    /**
54
     * Set auto filter off and run your own filter.
55
     * Overrides global search
56
     *
57
     * @param \Closure $callback
58
     * @param bool $globalSearch
59
     * @return $this
60
     */
61
    public function filter(Closure $callback, $globalSearch = false)
62
    {
63
        $this->overrideGlobalSearch($callback, $this->query, $globalSearch);
64
65
        return $this;
66
    }
67
68
    /**
69
     * Organizes works
70
     *
71
     * @param bool $mDataSupport
72
     * @param bool $orderFirst
73
     * @return \Illuminate\Http\JsonResponse
74
     */
75
    public function make($mDataSupport = false, $orderFirst = false)
76
    {
77
        return parent::make($mDataSupport, $orderFirst);
78
    }
79
80
    /**
81
     * Count total items.
82
     *
83
     * @return integer
84
     */
85
    public function totalCount()
86
    {
87
        return $this->totalRecords ? $this->totalRecords : $this->count();
88
    }
89
90
    /**
91
     * Counts current query.
92
     *
93
     * @return int
94
     */
95
    public function count()
96
    {
97
        $myQuery = clone $this->query;
98
        // if its a normal query ( no union, having and distinct word )
99
        // replace the select with static text to improve performance
100
        if (! Str::contains(Str::lower($myQuery->toSql()), ['union', 'having', 'distinct', 'order by', 'group by'])) {
0 ignored issues
show
Bug introduced by
The method toSql does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
101
            $row_count = $this->wrap('row_count');
102
            $myQuery->select($this->connection->raw("'1' as {$row_count}"));
0 ignored issues
show
Bug introduced by
The method select does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
103
        }
104
105
        // check for select soft deleted records
106
        if (! $this->withTrashed && $this->modelUseSoftDeletes()) {
107
            $myQuery->whereNull($myQuery->getModel()->getTable() . '.deleted_at');
0 ignored issues
show
Bug introduced by
The method getModel does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Query\Builder.

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...
Bug introduced by
The method whereNull does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
108
        }
109
110
        return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table'))
111
                                ->setBindings($myQuery->getBindings())->count();
0 ignored issues
show
Bug introduced by
The method getBindings does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
112
    }
113
114
    /**
115
     * Wrap column with DB grammar.
116
     *
117
     * @param string $column
118
     * @return string
119
     */
120
    protected function wrap($column)
121
    {
122
        return $this->connection->getQueryGrammar()->wrap($column);
123
    }
124
125
    /**
126
     * Check if model use SoftDeletes trait
127
     *
128
     * @return boolean
129
     */
130
    private function modelUseSoftDeletes()
131
    {
132
        if ($this->query_type == 'eloquent') {
133
            return in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this->query->getModel()));
0 ignored issues
show
Bug introduced by
The method getModel does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Query\Builder.

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...
134
        }
135
136
        return false;
137
    }
138
139
    /**
140
     * Perform global search.
141
     *
142
     * @return void
143
     */
144
    public function filtering()
145
    {
146
        $this->query->where(
147
            function ($query) {
148
                $globalKeyword = $this->request->keyword();
149
                $queryBuilder  = $this->getQueryBuilder($query);
150
151
                foreach ($this->request->searchableColumnIndex() as $index) {
152
                    $columnName = $this->getColumnName($index);
153
                    if ($this->isBlacklisted($columnName)) {
154
                        continue;
155
                    }
156
157
                    // check if custom column filtering is applied
158
                    if (isset($this->columnDef['filter'][$columnName])) {
159
                        $columnDef = $this->columnDef['filter'][$columnName];
160
                        // check if global search should be applied for the specific column
161
                        $applyGlobalSearch = count($columnDef['parameters']) == 0 || end($columnDef['parameters']) !== false;
162
                        if (! $applyGlobalSearch) {
163
                            continue;
164
                        }
165
166 View Code Duplication
                        if ($columnDef['method'] instanceof Closure) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167
                            $whereQuery = $queryBuilder->newQuery();
168
                            call_user_func_array($columnDef['method'], [$whereQuery, $globalKeyword]);
169
                            $queryBuilder->addNestedWhereQuery($whereQuery, 'or');
170
                        } else {
171
                            $this->compileColumnQuery(
172
                                $queryBuilder,
173
                                Helper::getOrMethod($columnDef['method']),
174
                                $columnDef['parameters'],
175
                                $columnName,
176
                                $globalKeyword
177
                            );
178
                        }
179 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
                        if (count(explode('.', $columnName)) > 1) {
181
                            $eagerLoads     = $this->getEagerLoads();
182
                            $parts          = explode('.', $columnName);
183
                            $relationColumn = array_pop($parts);
184
                            $relation       = implode('.', $parts);
185
                            if (in_array($relation, $eagerLoads)) {
186
                                $this->compileRelationSearch(
187
                                    $queryBuilder,
188
                                    $relation,
189
                                    $relationColumn,
190
                                    $globalKeyword
191
                                );
192
                            } else {
193
                                $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword);
194
                            }
195
                        } else {
196
                            $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword);
197
                        }
198
                    }
199
200
                    $this->isFilterApplied = true;
201
                }
202
            }
203
        );
204
    }
205
206
    /**
207
     * Perform filter column on selected field.
208
     *
209
     * @param mixed $query
210
     * @param string|Closure $method
211
     * @param mixed $parameters
212
     * @param string $column
213
     * @param string $keyword
214
     */
215
    protected function compileColumnQuery($query, $method, $parameters, $column, $keyword)
216
    {
217
        if (method_exists($query, $method)
218
            && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters()
219
        ) {
220
            if (Str::contains(Str::lower($method), 'raw')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 215 can also be of type object<Closure>; however, Illuminate\Support\Str::lower() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
221
                || Str::contains(Str::lower($method), 'exists')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 215 can also be of type object<Closure>; however, Illuminate\Support\Str::lower() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
222
            ) {
223
                call_user_func_array(
224
                    [$query, $method],
225
                    $this->parameterize($parameters, $keyword)
226
                );
227
            } else {
228
                call_user_func_array(
229
                    [$query, $method],
230
                    $this->parameterize($column, $parameters, $keyword)
231
                );
232
            }
233
        }
234
    }
235
236
    /**
237
     * Build Query Builder Parameters.
238
     *
239
     * @return array
240
     */
241
    protected function parameterize()
242
    {
243
        $args       = func_get_args();
244
        $keyword    = count($args) > 2 ? $args[2] : $args[1];
245
        $parameters = Helper::buildParameters($args);
246
        $parameters = Helper::replacePatternWithKeyword($parameters, $keyword, '$1');
247
248
        return $parameters;
249
    }
250
251
    /**
252
     * Get eager loads keys if eloquent.
253
     *
254
     * @return array
255
     */
256
    protected function getEagerLoads()
257
    {
258
        if ($this->query_type == 'eloquent') {
259
            return array_keys($this->query->getEagerLoads());
0 ignored issues
show
Bug introduced by
The method getEagerLoads does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Query\Builder.

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...
260
        }
261
262
        return [];
263
    }
264
265
    /**
266
     * Add relation query on global search.
267
     *
268
     * @param mixed $query
269
     * @param string $relation
270
     * @param string $column
271
     * @param string $keyword
272
     */
273
    protected function compileRelationSearch($query, $relation, $column, $keyword)
274
    {
275
        $myQuery      = clone $this->query;
276
277
        /**
278
         * For compile nested relation, we need store all nested relation as array
279
         * and reverse order to apply where query.
280
         *
281
         * With this method we can create nested sub query with properly relation.
282
         */
283
284
        /**
285
         * Store all relation data that require in next step
286
         */
287
        $relationChunk = [];
288
289
        /**
290
         * Store last eloquent query builder for get next relation.
291
         */
292
        $lastQuery = $query;
293
294
        $relations = explode('.', $relation);
295
        $lastRelation = end($relations);
296
        foreach ($relations as $relation) {
297
            $relationType = $myQuery->getModel()->{$relation}();
298
            $myQuery->orWhereHas($relation, function ($builder) use (
299
                $column,
300
                $keyword,
301
                $query,
302
                $relationType,
303
                $relation,
304
                $lastRelation,
305
                &$relationChunk,
306
                &$lastQuery
307
            ) {
308
                $builder->select($this->connection->raw('count(1)'));
309
310
                // We will perform search on last relation only.
311
                if ($relation == $lastRelation) {
312
                    $this->compileQuerySearch($builder, $column, $keyword, '');
313
                }
314
315
                // Put require object to next step!!
316
                $relationChunk[$relation] = [
317
                    'builder' => $builder,
318
                    'relationType' => $relationType,
319
                    'query' => $lastQuery
320
                ];
321
322
                // This is trick make sub query.
323
                $lastQuery = $builder;
324
            });
325
326
            // This is trick to make nested relation by pass previous relation to be next query eloquent builder
327
            $myQuery = $relationType;
328
        }
329
330
        /**
331
         * Reverse them all
332
         */
333
        $relationChunk = array_reverse($relationChunk, true);
334
335
        /**
336
         * Create valuable for use in check last relation
337
         */
338
        end($relationChunk);
339
        $lastRelation = key($relationChunk);
340
        reset($relationChunk);
341
342
        /**
343
         * Walking ...
344
         */
345
        foreach ($relationChunk as $relation => $chunk) {
346
            // Prepare variables
347
            $builder = $chunk['builder'];
348
            $relationType = $chunk['relationType'];
349
            $query = $chunk['query'];
350
            $builder = "({$builder->toSql()}) >= 1";
351
352
            // Check if it last relation we will use orWhereRaw
353
            if ($lastRelation == $relation) {
354
                $relationMethod = "orWhereRaw";
355
            } else {
356
                // For case parent relation of nested relation.
357
                // We must use and for properly query and get correct result
358
                $relationMethod = "whereRaw";
359
            }
360
361
            if ($relationType instanceof MorphToMany) {
362
                $query->{$relationMethod}($builder, [$relationType->getMorphClass(), $this->prepareKeyword($keyword)]);
363
            } else {
364
                $query->{$relationMethod}($builder, [$this->prepareKeyword($keyword)]);
365
            }
366
        }
367
    }
368
369
    /**
370
     * Compile query builder where clause depending on configurations.
371
     *
372
     * @param mixed $query
373
     * @param string $column
374
     * @param string $keyword
375
     * @param string $relation
376
     */
377
    protected function compileQuerySearch($query, $column, $keyword, $relation = 'or')
378
    {
379
        $column = $this->castColumn($column);
380
        $sql    = $column . ' LIKE ?';
381
382
        if ($this->isCaseInsensitive()) {
383
            $sql = 'LOWER(' . $column . ') LIKE ?';
384
        }
385
386
        $query->{$relation . 'WhereRaw'}($sql, [$this->prepareKeyword($keyword)]);
387
    }
388
389
    /**
390
     * Wrap a column and cast in pgsql.
391
     *
392
     * @param  string $column
393
     * @return string
394
     */
395
    public function castColumn($column)
396
    {
397
        $column = $this->wrap($column);
398
        if ($this->database === 'pgsql') {
399
            $column = 'CAST(' . $column . ' as TEXT)';
400
        } elseif ($this->database === 'firebird') {
401
            $column = 'CAST(' . $column . ' as VARCHAR(255))';
402
        }
403
404
        return $column;
405
    }
406
407
    /**
408
     * Prepare search keyword based on configurations.
409
     *
410
     * @param string $keyword
411
     * @return string
412
     */
413
    protected function prepareKeyword($keyword)
414
    {
415
        if ($this->isCaseInsensitive()) {
416
            $keyword = Str::lower($keyword);
417
        }
418
419
        if ($this->isWildcard()) {
420
            $keyword = $this->wildcardLikeString($keyword);
421
        }
422
423
        if ($this->isSmartSearch()) {
424
            $keyword = "%$keyword%";
425
        }
426
427
        return $keyword;
428
    }
429
430
    /**
431
     * Perform column search.
432
     *
433
     * @return void
434
     */
435
    public function columnSearch()
436
    {
437
        $columns = $this->request->get('columns', []);
438
439
        foreach ($columns as $index => $column) {
440
            if (! $this->request->isColumnSearchable($index)) {
441
                continue;
442
            }
443
444
            $column = $this->getColumnName($index);
445
446
            if (isset($this->columnDef['filter'][$column])) {
447
                $columnDef = $this->columnDef['filter'][$column];
448
                // get a raw keyword (without wildcards)
449
                $keyword = $this->getSearchKeyword($index, true);
450
                $builder = $this->getQueryBuilder();
451
452 View Code Duplication
                if ($columnDef['method'] instanceof Closure) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
453
                    $whereQuery = $builder->newQuery();
454
                    call_user_func_array($columnDef['method'], [$whereQuery, $keyword]);
455
                    $builder->addNestedWhereQuery($whereQuery);
456
                } else {
457
                    $this->compileColumnQuery(
458
                        $builder,
459
                        $columnDef['method'],
460
                        $columnDef['parameters'],
461
                        $column,
462
                        $keyword
463
                    );
464
                }
465 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
466
                if (count(explode('.', $column)) > 1) {
467
                    $eagerLoads     = $this->getEagerLoads();
468
                    $parts          = explode('.', $column);
469
                    $relationColumn = array_pop($parts);
470
                    $relation       = implode('.', $parts);
471
                    if (in_array($relation, $eagerLoads)) {
472
                        $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
473
                    }
474
                }
475
476
                $keyword = $this->getSearchKeyword($index);
477
                $this->compileColumnSearch($index, $column, $keyword);
478
            }
479
480
            $this->isFilterApplied = true;
481
        }
482
    }
483
484
    /**
485
     * Get proper keyword to use for search.
486
     *
487
     * @param int $i
488
     * @param bool $raw
489
     * @return string
490
     */
491
    private function getSearchKeyword($i, $raw = false)
492
    {
493
        $keyword = $this->request->columnKeyword($i);
494
        if ($raw || $this->request->isRegex($i)) {
495
            return $keyword;
496
        }
497
498
        return $this->setupKeyword($keyword);
499
    }
500
501
    /**
502
     * Join eager loaded relation and get the related column name.
503
     *
504
     * @param string $relation
505
     * @param string $relationColumn
506
     * @return string
507
     */
508
    protected function joinEagerLoadedColumn($relation, $relationColumn)
509
    {
510
        $joins = [];
511
        foreach ((array) $this->getQueryBuilder()->joins as $key => $join) {
512
            $joins[] = $join->table;
513
        }
514
515
        $model = $this->query->getRelation($relation);
0 ignored issues
show
Bug introduced by
The method getRelation does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Query\Builder.

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...
516
        if ($model instanceof BelongsToMany) {
517
            $pivot   = $model->getTable();
518
            $pivotPK = $model->getForeignKey();
519
            $pivotFK = $model->getQualifiedParentKeyName();
520
521
            if (! in_array($pivot, $joins)) {
522
                $this->getQueryBuilder()->leftJoin($pivot, $pivotPK, '=', $pivotFK);
523
            }
524
525
            $related = $model->getRelated();
526
            $table   = $related->getTable();
527
            $tablePK = $related->getForeignKey();
528
            $tableFK = $related->getQualifiedKeyName();
529
530
            if (! in_array($table, $joins)) {
531
                $this->getQueryBuilder()->leftJoin($table, $pivot . '.' . $tablePK, '=', $tableFK);
532
            }
533
        } else {
534
            $table = $model->getRelated()->getTable();
535
            if ($model instanceof HasOneOrMany) {
536
                $foreign = $model->getForeignKey();
537
                $other   = $model->getQualifiedParentKeyName();
538
            } else {
539
                $foreign = $model->getQualifiedForeignKey();
540
                $other   = $model->getQualifiedOtherKeyName();
541
            }
542
543
            if (! in_array($table, $joins)) {
544
                $this->getQueryBuilder()->leftJoin($table, $foreign, '=', $other);
545
            }
546
        }
547
548
        $column = $table . '.' . $relationColumn;
549
550
        return $column;
551
    }
552
553
    /**
554
     * Compile queries for column search.
555
     *
556
     * @param int $i
557
     * @param mixed $column
558
     * @param string $keyword
559
     */
560
    protected function compileColumnSearch($i, $column, $keyword)
561
    {
562
        if ($this->request->isRegex($i)) {
563
            $column = strstr($column, '(') ? $this->connection->raw($column) : $column;
564
            $this->regexColumnSearch($column, $keyword);
565
        } else {
566
            $this->compileQuerySearch($this->query, $column, $keyword, '');
567
        }
568
    }
569
570
    /**
571
     * Compile regex query column search.
572
     *
573
     * @param mixed $column
574
     * @param string $keyword
575
     */
576
    protected function regexColumnSearch($column, $keyword)
577
    {
578
        if ($this->isOracleSql()) {
579
            $sql = ! $this->isCaseInsensitive() ? 'REGEXP_LIKE( ' . $column . ' , ? )' : 'REGEXP_LIKE( LOWER(' . $column . ') , ?, \'i\' )';
580
            $this->query->whereRaw($sql, [$keyword]);
0 ignored issues
show
Bug introduced by
The method whereRaw does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
581
        } else {
582
            $sql = ! $this->isCaseInsensitive() ? $column . ' REGEXP ?' : 'LOWER(' . $column . ') REGEXP ?';
583
            $this->query->whereRaw($sql, [Str::lower($keyword)]);
584
        }
585
    }
586
587
    /**
588
     * Perform sorting of columns.
589
     *
590
     * @return void
591
     */
592
    public function ordering()
593
    {
594
        if ($this->orderCallback) {
595
            call_user_func($this->orderCallback, $this->getQueryBuilder());
596
597
            return;
598
        }
599
600
        foreach ($this->request->orderableColumns() as $orderable) {
601
            $column = $this->getColumnName($orderable['column'], true);
602
603
            if ($this->isBlacklisted($column)) {
604
                continue;
605
            }
606
607
            if (isset($this->columnDef['order'][$column])) {
608
                $method     = $this->columnDef['order'][$column]['method'];
609
                $parameters = $this->columnDef['order'][$column]['parameters'];
610
                $this->compileColumnQuery(
611
                    $this->getQueryBuilder(),
612
                    $method,
613
                    $parameters,
614
                    $column,
615
                    $orderable['direction']
616
                );
617
            } else {
618
                $valid = 1;
619
                if (count(explode('.', $column)) > 1) {
620
                    $eagerLoads     = $this->getEagerLoads();
621
                    $parts          = explode('.', $column);
622
                    $relationColumn = array_pop($parts);
623
                    $relation       = implode('.', $parts);
624
625
                    if (in_array($relation, $eagerLoads)) {
626
                        $relationship = $this->query->getRelation($relation);
0 ignored issues
show
Bug introduced by
The method getRelation does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Query\Builder.

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...
627
                        if (! ($relationship instanceof MorphToMany)) {
628
                            $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
629
                        } else {
630
                            $valid = 0;
631
                        }
632
                    }
633
                }
634
635
                if ($valid == 1) {
636
                    if ($this->nullsLast) {
637
                        $this->getQueryBuilder()->orderByRaw($this->getNullsLastSql($column, $orderable['direction']));
638
                    } else {
639
                        $this->getQueryBuilder()->orderBy($column, $orderable['direction']);
640
                    }
641
                }
642
            }
643
        }
644
    }
645
646
    /**
647
     * Get NULLS LAST SQL.
648
     *
649
     * @param  string $column
650
     * @param  string $direction
651
     * @return string
652
     */
653
    protected function getNullsLastSql($column, $direction)
654
    {
655
        $sql = Config::get('datatables.nulls_last_sql', '%s %s NULLS LAST');
656
657
        return sprintf($sql, $column, $direction);
658
    }
659
660
    /**
661
     * Perform pagination
662
     *
663
     * @return void
664
     */
665
    public function paging()
666
    {
667
        $this->query->skip($this->request['start'])
0 ignored issues
show
Bug introduced by
The method skip does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloquent\Builder.

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...
668
                    ->take((int) $this->request['length'] > 0 ? $this->request['length'] : 10);
669
    }
670
671
    /**
672
     * Get results
673
     *
674
     * @return array|static[]
675
     */
676
    public function results()
677
    {
678
        return $this->query->get();
679
    }
680
}
681