Completed
Push — master ( e46d32...01f863 )
by Arjay
03:35
created

QueryBuilderEngine::wrap()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
rs 10
1
<?php
2
3
namespace Yajra\Datatables\Engines;
4
5
use Closure;
6
use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
8
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
9
use Illuminate\Database\Eloquent\Relations\MorphToMany;
10
use Illuminate\Database\Query\Builder;
11
use Illuminate\Database\Query\Expression;
12
use Illuminate\Support\Facades\Config;
13
use Illuminate\Support\Str;
14
use Yajra\Datatables\Helper;
15
use Yajra\Datatables\Request;
16
17
/**
18
 * Class QueryBuilderEngine.
19
 *
20
 * @package Yajra\Datatables\Engines
21
 * @author  Arjay Angeles <[email protected]>
22
 */
23
class QueryBuilderEngine extends BaseEngine
24
{
25
    /**
26
     * @param \Illuminate\Database\Query\Builder $builder
27
     * @param \Yajra\Datatables\Request $request
28
     */
29
    public function __construct(Builder $builder, Request $request)
30
    {
31
        $this->query = $builder;
32
        $this->init($request, $builder);
33
    }
34
35
    /**
36
     * Initialize attributes.
37
     *
38
     * @param  \Yajra\Datatables\Request $request
39
     * @param  \Illuminate\Database\Query\Builder $builder
40
     * @param  string $type
41
     */
42
    protected function init($request, $builder, $type = 'builder')
43
    {
44
        $this->request    = $request;
45
        $this->query_type = $type;
46
        $this->columns    = $builder->columns;
47
        $this->connection = $builder->getConnection();
48
        $this->prefix     = $this->connection->getTablePrefix();
49
        $this->database   = $this->connection->getDriverName();
50
        if ($this->isDebugging()) {
51
            $this->connection->enableQueryLog();
52
        }
53
    }
54
55
    /**
56
     * Set auto filter off and run your own filter.
57
     * Overrides global search
58
     *
59
     * @param \Closure $callback
60
     * @param bool $globalSearch
61
     * @return $this
62
     */
63
    public function filter(Closure $callback, $globalSearch = false)
64
    {
65
        $this->overrideGlobalSearch($callback, $this->query, $globalSearch);
66
67
        return $this;
68
    }
69
70
    /**
71
     * Organizes works
72
     *
73
     * @param bool $mDataSupport
74
     * @param bool $orderFirst
75
     * @return \Illuminate\Http\JsonResponse
76
     */
77
    public function make($mDataSupport = false, $orderFirst = false)
78
    {
79
        return parent::make($mDataSupport, $orderFirst);
80
    }
81
82
    /**
83
     * Count total items.
84
     *
85
     * @return integer
86
     */
87
    public function totalCount()
88
    {
89
        return $this->totalRecords ? $this->totalRecords : $this->count();
90
    }
91
92
    /**
93
     * Counts current query.
94
     *
95
     * @return int
96
     */
97
    public function count()
98
    {
99
        $myQuery = clone $this->query;
100
        // if its a normal query ( no union, having and distinct word )
101
        // replace the select with static text to improve performance
102 View Code Duplication
        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...
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...
103
            $row_count = $this->wrap('row_count');
104
            $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...
105
        }
106
107
        return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table'))
108
                                ->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...
109
    }
110
111
    /**
112
     * Wrap column with DB grammar.
113
     *
114
     * @param string $column
115
     * @return string
116
     */
117
    protected function wrap($column)
118
    {
119
        return $this->connection->getQueryGrammar()->wrap($column);
120
    }
121
122
    /**
123
     * Perform global search.
124
     *
125
     * @return void
126
     */
127
    public function filtering()
128
    {
129
        $this->query->where(
130
            function ($query) {
131
                $globalKeyword = $this->request->keyword();
132
                $queryBuilder  = $this->getQueryBuilder($query);
133
134
                foreach ($this->request->searchableColumnIndex() as $index) {
135
                    $columnName = $this->getColumnName($index);
136
                    if ($this->isBlacklisted($columnName)) {
137
                        continue;
138
                    }
139
140
                    // check if custom column filtering is applied
141
                    if (isset($this->columnDef['filter'][$columnName])) {
142
                        $columnDef = $this->columnDef['filter'][$columnName];
143
                        // check if global search should be applied for the specific column
144
                        $applyGlobalSearch = count($columnDef['parameters']) == 0 || end($columnDef['parameters']) !== false;
145
                        if (! $applyGlobalSearch) {
146
                            continue;
147
                        }
148
149 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...
150
                            $whereQuery = $queryBuilder->newQuery();
151
                            call_user_func_array($columnDef['method'], [$whereQuery, $globalKeyword]);
152
                            $queryBuilder->addNestedWhereQuery($whereQuery, 'or');
153
                        } else {
154
                            $this->compileColumnQuery(
155
                                $queryBuilder,
156
                                Helper::getOrMethod($columnDef['method']),
157
                                $columnDef['parameters'],
158
                                $columnName,
159
                                $globalKeyword
0 ignored issues
show
Bug introduced by
It seems like $globalKeyword defined by $this->request->keyword() on line 131 can also be of type array; however, Yajra\Datatables\Engines...e::compileColumnQuery() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
160
                            );
161
                        }
162 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...
163
                        if (count(explode('.', $columnName)) > 1) {
164
                            $eagerLoads     = $this->getEagerLoads();
165
                            $parts          = explode('.', $columnName);
166
                            $relationColumn = array_pop($parts);
167
                            $relation       = implode('.', $parts);
168
                            if (in_array($relation, $eagerLoads)) {
169
                                $this->compileRelationSearch(
170
                                    $queryBuilder,
171
                                    $relation,
172
                                    $relationColumn,
173
                                    $globalKeyword
0 ignored issues
show
Bug introduced by
It seems like $globalKeyword defined by $this->request->keyword() on line 131 can also be of type array; however, Yajra\Datatables\Engines...compileRelationSearch() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
174
                                );
175
                            } else {
176
                                $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword);
0 ignored issues
show
Bug introduced by
It seems like $globalKeyword defined by $this->request->keyword() on line 131 can also be of type array; however, Yajra\Datatables\Engines...e::compileQuerySearch() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
177
                            }
178
                        } else {
179
                            $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword);
0 ignored issues
show
Bug introduced by
It seems like $globalKeyword defined by $this->request->keyword() on line 131 can also be of type array; however, Yajra\Datatables\Engines...e::compileQuerySearch() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
180
                        }
181
                    }
182
183
                    $this->isFilterApplied = true;
184
                }
185
            }
186
        );
187
    }
188
189
    /**
190
     * Perform filter column on selected field.
191
     *
192
     * @param mixed $query
193
     * @param string|Closure $method
194
     * @param mixed $parameters
195
     * @param string $column
196
     * @param string $keyword
197
     */
198
    protected function compileColumnQuery($query, $method, $parameters, $column, $keyword)
199
    {
200
        if (method_exists($query, $method)
201
            && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters()
202
        ) {
203
            if (Str::contains(Str::lower($method), 'raw')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 198 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...
204
                || Str::contains(Str::lower($method), 'exists')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 198 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...
205
            ) {
206
                call_user_func_array(
207
                    [$query, $method],
208
                    $this->parameterize($parameters, $keyword)
209
                );
210
            } else {
211
                call_user_func_array(
212
                    [$query, $method],
213
                    $this->parameterize($column, $parameters, $keyword)
214
                );
215
            }
216
        }
217
    }
218
219
    /**
220
     * Build Query Builder Parameters.
221
     *
222
     * @return array
223
     */
224
    protected function parameterize()
225
    {
226
        $args       = func_get_args();
227
        $keyword    = count($args) > 2 ? $args[2] : $args[1];
228
        $parameters = Helper::buildParameters($args);
229
        $parameters = Helper::replacePatternWithKeyword($parameters, $keyword, '$1');
230
231
        return $parameters;
232
    }
233
234
    /**
235
     * Get eager loads keys if eloquent.
236
     *
237
     * @return array
238
     */
239
    protected function getEagerLoads()
240
    {
241
        if ($this->query_type == 'eloquent') {
242
            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...
243
        }
244
245
        return [];
246
    }
247
248
    /**
249
     * Add relation query on global search.
250
     *
251
     * @param mixed $query
252
     * @param string $relation
253
     * @param string $column
254
     * @param string $keyword
255
     */
256
    protected function compileRelationSearch($query, $relation, $column, $keyword)
257
    {
258
        $myQuery = clone $this->query;
259
260
        /**
261
         * For compile nested relation, we need store all nested relation as array
262
         * and reverse order to apply where query.
263
         * With this method we can create nested sub query with properly relation.
264
         */
265
266
        /**
267
         * Store all relation data that require in next step
268
         */
269
        $relationChunk = [];
270
271
        /**
272
         * Store last eloquent query builder for get next relation.
273
         */
274
        $lastQuery = $query;
275
276
        $relations    = explode('.', $relation);
277
        $lastRelation = end($relations);
278
        foreach ($relations as $relation) {
279
            $relationType = $myQuery->getModel()->{$relation}();
280
            $myQuery->orWhereHas($relation, function ($builder) use (
281
                $column,
282
                $keyword,
283
                $query,
284
                $relationType,
285
                $relation,
286
                $lastRelation,
287
                &$relationChunk,
288
                &$lastQuery
289
            ) {
290
                $builder->select($this->connection->raw('count(1)'));
291
292
                // We will perform search on last relation only.
293
                if ($relation == $lastRelation) {
294
                    $this->compileQuerySearch($builder, $column, $keyword, '');
295
                }
296
297
                // Put require object to next step!!
298
                $relationChunk[$relation] = [
299
                    'builder'      => $builder,
300
                    'relationType' => $relationType,
301
                    'query'        => $lastQuery,
302
                ];
303
304
                // This is trick make sub query.
305
                $lastQuery = $builder;
306
            });
307
308
            // This is trick to make nested relation by pass previous relation to be next query eloquent builder
309
            $myQuery = $relationType;
310
        }
311
312
        /**
313
         * Reverse them all
314
         */
315
        $relationChunk = array_reverse($relationChunk, true);
316
317
        /**
318
         * Create valuable for use in check last relation
319
         */
320
        end($relationChunk);
321
        $lastRelation = key($relationChunk);
322
        reset($relationChunk);
323
324
        /**
325
         * Walking ...
326
         */
327
        foreach ($relationChunk as $relation => $chunk) {
328
            // Prepare variables
329
            $builder      = $chunk['builder'];
330
            $query        = $chunk['query'];
331
            $bindings     = $builder->getBindings();
332
            $builder      = "({$builder->toSql()}) >= 1";
333
334
            // Check if it last relation we will use orWhereRaw
335
            if ($lastRelation == $relation) {
336
                $relationMethod = "orWhereRaw";
337
            } else {
338
                // For case parent relation of nested relation.
339
                // We must use and for properly query and get correct result
340
                $relationMethod = "whereRaw";
341
            }
342
343
            $query->{$relationMethod}($builder, $bindings);
344
        }
345
    }
346
347
    /**
348
     * Compile query builder where clause depending on configurations.
349
     *
350
     * @param mixed $query
351
     * @param string $column
352
     * @param string $keyword
353
     * @param string $relation
354
     */
355
    protected function compileQuerySearch($query, $column, $keyword, $relation = 'or')
356
    {
357
        $column = $this->addTablePrefix($query, $column);
358
        $column = $this->castColumn($column);
359
        $sql    = $column . ' LIKE ?';
360
361
        if ($this->isCaseInsensitive()) {
362
            $sql = 'LOWER(' . $column . ') LIKE ?';
363
        }
364
365
        $query->{$relation . 'WhereRaw'}($sql, [$this->prepareKeyword($keyword)]);
366
    }
367
368
    /**
369
     * Patch for fix about ambiguous field.
370
     * Ambiguous field error will appear when query use join table and search with keyword.
371
     *
372
     * @param mixed $query
373
     * @param string $column
374
     * @return string
375
     */
376
    protected function addTablePrefix($query, $column)
377
    {
378
        // Check if field does not have a table prefix
379
        if (strpos($column, '.') === false) {
380
            // Alternative method to check instanceof \Illuminate\Database\Eloquent\Builder
381
            if (method_exists($query, 'getQuery')) {
382
                $q = $query->getQuery();
383
            } else {
384
                $q = $query;
385
            }
386
387
            if (! $q->from instanceof Expression) {
388
                // Get table from query and add it.
389
                $column = $q->from . '.' . $column;
390
            }
391
        }
392
393
        return $this->wrap($column);
394
    }
395
396
    /**
397
     * Wrap a column and cast in pgsql.
398
     *
399
     * @param  string $column
400
     * @return string
401
     */
402
    protected function castColumn($column)
403
    {
404
        if ($this->database === 'pgsql') {
405
            $column = 'CAST(' . $column . ' as TEXT)';
406
        } elseif ($this->database === 'firebird') {
407
            $column = 'CAST(' . $column . ' as VARCHAR(255))';
408
        }
409
410
        return $column;
411
    }
412
413
    /**
414
     * Prepare search keyword based on configurations.
415
     *
416
     * @param string $keyword
417
     * @return string
418
     */
419
    protected function prepareKeyword($keyword)
420
    {
421
        if ($this->isCaseInsensitive()) {
422
            $keyword = Str::lower($keyword);
423
        }
424
425
        if ($this->isWildcard()) {
426
            $keyword = $this->wildcardLikeString($keyword);
427
        }
428
429
        if ($this->isSmartSearch()) {
430
            $keyword = "%$keyword%";
431
        }
432
433
        return $keyword;
434
    }
435
436
    /**
437
     * Perform column search.
438
     *
439
     * @return void
440
     */
441
    public function columnSearch()
442
    {
443
        $columns = $this->request->columns();
444
445
        foreach ($columns as $index => $column) {
446
            if (! $this->request->isColumnSearchable($index)) {
447
                continue;
448
            }
449
450
            $column = $this->getColumnName($index);
451
452
            if (isset($this->columnDef['filter'][$column])) {
453
                $columnDef = $this->columnDef['filter'][$column];
454
                // get a raw keyword (without wildcards)
455
                $keyword = $this->getSearchKeyword($index, true);
456
                $builder = $this->getQueryBuilder();
457
458 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...
459
                    $whereQuery = $builder->newQuery();
460
                    call_user_func_array($columnDef['method'], [$whereQuery, $keyword]);
461
                    $builder->addNestedWhereQuery($whereQuery);
462
                } else {
463
                    $this->compileColumnQuery(
464
                        $builder,
465
                        $columnDef['method'],
466
                        $columnDef['parameters'],
467
                        $column,
468
                        $keyword
0 ignored issues
show
Bug introduced by
It seems like $keyword defined by $this->getSearchKeyword($index, true) on line 455 can also be of type array; however, Yajra\Datatables\Engines...e::compileColumnQuery() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
469
                    );
470
                }
471 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...
472
                if (count(explode('.', $column)) > 1) {
473
                    $eagerLoads     = $this->getEagerLoads();
474
                    $parts          = explode('.', $column);
475
                    $relationColumn = array_pop($parts);
476
                    $relation       = implode('.', $parts);
477
                    if (in_array($relation, $eagerLoads)) {
478
                        $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
479
                    }
480
                }
481
482
                $keyword = $this->getSearchKeyword($index);
483
                $this->compileColumnSearch($index, $column, $keyword);
0 ignored issues
show
Bug introduced by
It seems like $keyword defined by $this->getSearchKeyword($index) on line 482 can also be of type array; however, Yajra\Datatables\Engines...::compileColumnSearch() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
484
            }
485
486
            $this->isFilterApplied = true;
487
        }
488
    }
489
490
    /**
491
     * Get proper keyword to use for search.
492
     *
493
     * @param int $i
494
     * @param bool $raw
495
     * @return string
496
     */
497
    protected function getSearchKeyword($i, $raw = false)
498
    {
499
        $keyword = $this->request->columnKeyword($i);
500
        if ($raw || $this->request->isRegex($i)) {
501
            return $keyword;
502
        }
503
504
        return $this->setupKeyword($keyword);
0 ignored issues
show
Bug introduced by
It seems like $keyword defined by $this->request->columnKeyword($i) on line 499 can also be of type array; however, Yajra\Datatables\Engines...eEngine::setupKeyword() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
505
    }
506
507
    /**
508
     * Join eager loaded relation and get the related column name.
509
     *
510
     * @param string $relation
511
     * @param string $relationColumn
512
     * @return string
513
     */
514
    protected function joinEagerLoadedColumn($relation, $relationColumn)
515
    {
516
        $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...
517
        switch (true) {
518
            case $model instanceof BelongsToMany:
519
                $pivot   = $model->getTable();
520
                $pivotPK = $model->getExistenceCompareKey();
521
                $pivotFK = $model->getQualifiedParentKeyName();
522
                $this->performJoin($pivot, $pivotPK, $pivotFK);
523
524
                $related = $model->getRelated();
525
                $table   = $related->getTable();
526
                $tablePK = $related->getForeignKey();
527
                $foreign = $pivot . '.' . $tablePK;
528
                $other   = $related->getQualifiedKeyName();
529
530
                $this->query->addSelect($table . '.' . $relationColumn);
0 ignored issues
show
Bug introduced by
The method addSelect 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...
531
                break;
532
533
            case $model instanceof HasOneOrMany:
534
                $table   = $model->getRelated()->getTable();
535
                $foreign = $model->getQualifiedForeignKeyName();
536
                $other   = $model->getQualifiedParentKeyName();
537
                break;
538
539
            case $model instanceof BelongsTo:
540
                $table   = $model->getRelated()->getTable();
541
                $foreign = $model->getQualifiedForeignKey();
542
                $other   = $model->getQualifiedOwnerKeyName();
543
                break;
544
545
            default:
546
                $table   = $model->getRelated()->getTable();
547
                $foreign = $model->getQualifiedForeignKey();
548
                $other   = $model->getQualifiedOtherKeyName();
549
        }
550
551
        $this->performJoin($table, $foreign, $other);
552
553
        return $table . '.' . $relationColumn;
554
    }
555
556
    /**
557
     * Perform join query.
558
     *
559
     * @param string $table
560
     * @param string $foreign
561
     * @param string $other
562
     */
563
    protected function performJoin($table, $foreign, $other)
564
    {
565
        $joins = [];
566
        foreach ((array) $this->getQueryBuilder()->joins as $key => $join) {
567
            $joins[] = $join->table;
568
        }
569
570
        if (! in_array($table, $joins)) {
571
            $this->getQueryBuilder()->leftJoin($table, $foreign, '=', $other);
572
        }
573
    }
574
575
    /**
576
     * Compile queries for column search.
577
     *
578
     * @param int $i
579
     * @param mixed $column
580
     * @param string $keyword
581
     */
582
    protected function compileColumnSearch($i, $column, $keyword)
583
    {
584
        if ($this->request->isRegex($i)) {
585
            $column = strstr($column, '(') ? $this->connection->raw($column) : $column;
586
            $this->regexColumnSearch($column, $keyword);
587
        } else {
588
            $this->compileQuerySearch($this->query, $column, $keyword, '');
589
        }
590
    }
591
592
    /**
593
     * Compile regex query column search.
594
     *
595
     * @param mixed $column
596
     * @param string $keyword
597
     */
598
    protected function regexColumnSearch($column, $keyword)
599
    {
600
        if ($this->isOracleSql()) {
601
            $sql = ! $this->isCaseInsensitive() ? 'REGEXP_LIKE( ' . $column . ' , ? )' : 'REGEXP_LIKE( LOWER(' . $column . ') , ?, \'i\' )';
602
            $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...
603
        } elseif ($this->database == 'pgsql') {
604
            $sql = ! $this->isCaseInsensitive() ? $column . ' ~ ?' : $column . ' ~* ? ';
605
            $this->query->whereRaw($sql, [$keyword]);
606
        } else {
607
            $sql = ! $this->isCaseInsensitive() ? $column . ' REGEXP ?' : 'LOWER(' . $column . ') REGEXP ?';
608
            $this->query->whereRaw($sql, [Str::lower($keyword)]);
609
        }
610
    }
611
612
    /**
613
     * Perform sorting of columns.
614
     *
615
     * @return void
616
     */
617
    public function ordering()
618
    {
619
        if ($this->orderCallback) {
620
            call_user_func($this->orderCallback, $this->getQueryBuilder());
621
622
            return;
623
        }
624
625
        foreach ($this->request->orderableColumns() as $orderable) {
626
            $column = $this->getColumnName($orderable['column'], true);
627
628
            if ($this->isBlacklisted($column)) {
629
                continue;
630
            }
631
632
            if (isset($this->columnDef['order'][$column])) {
633
                $method     = $this->columnDef['order'][$column]['method'];
634
                $parameters = $this->columnDef['order'][$column]['parameters'];
635
                $this->compileColumnQuery(
636
                    $this->getQueryBuilder(),
637
                    $method,
638
                    $parameters,
639
                    $column,
640
                    $orderable['direction']
641
                );
642
            } else {
643
                $valid = 1;
644
                if (count(explode('.', $column)) > 1) {
645
                    $eagerLoads     = $this->getEagerLoads();
646
                    $parts          = explode('.', $column);
647
                    $relationColumn = array_pop($parts);
648
                    $relation       = implode('.', $parts);
649
650
                    if (in_array($relation, $eagerLoads)) {
651
                        $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...
652
                        if (! ($relationship instanceof MorphToMany)) {
653
                            $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
654
                        } else {
655
                            $valid = 0;
656
                        }
657
                    }
658
                }
659
660
                if ($valid == 1) {
661
                    if ($this->nullsLast) {
662
                        $this->getQueryBuilder()->orderByRaw($this->getNullsLastSql($column, $orderable['direction']));
663
                    } else {
664
                        $this->getQueryBuilder()->orderBy($column, $orderable['direction']);
665
                    }
666
                }
667
            }
668
        }
669
    }
670
671
    /**
672
     * Get NULLS LAST SQL.
673
     *
674
     * @param  string $column
675
     * @param  string $direction
676
     * @return string
677
     */
678
    protected function getNullsLastSql($column, $direction)
679
    {
680
        $sql = Config::get('datatables.nulls_last_sql', '%s %s NULLS LAST');
681
682
        return sprintf($sql, $column, $direction);
683
    }
684
685
    /**
686
     * Perform pagination
687
     *
688
     * @return void
689
     */
690
    public function paging()
691
    {
692
        $this->query->skip($this->request->input('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...
693
                    ->take((int) $this->request->input('length') > 0 ? $this->request->input('length') : 10);
694
    }
695
696
    /**
697
     * Get results
698
     *
699
     * @return array|static[]
700
     */
701
    public function results()
702
    {
703
        return $this->query->get();
704
    }
705
}
706