Completed
Push — master ( 89c4c4...0563f6 )
by Arjay
02:35
created

QueryBuilderEngine::isOracleSql()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Yajra\Datatables\Engines;
4
5
use Closure;
6
use Illuminate\Database\Query\Builder;
7
use Illuminate\Support\Str;
8
use Yajra\Datatables\Helper;
9
use Yajra\Datatables\Request;
10
11
/**
12
 * Class QueryBuilderEngine.
13
 *
14
 * @package Yajra\Datatables\Engines
15
 * @author  Arjay Angeles <[email protected]>
16
 */
17
class QueryBuilderEngine extends BaseEngine
18
{
19
    /**
20
     * @param \Illuminate\Database\Query\Builder $builder
21
     * @param \Yajra\Datatables\Request $request
22
     */
23
    public function __construct(Builder $builder, Request $request)
24
    {
25
        $this->query = $builder;
26
        $this->init($request, $builder);
27
    }
28
29
    /**
30
     * Initialize attributes.
31
     *
32
     * @param  \Yajra\Datatables\Request $request
33
     * @param  \Illuminate\Database\Query\Builder $builder
34
     * @param  string $type
35
     */
36
    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...
37
    {
38
        $this->request    = $request;
39
        $this->query_type = $type;
40
        $this->columns    = $builder->columns;
41
        $this->connection = $builder->getConnection();
42
        $this->prefix     = $this->connection->getTablePrefix();
43
        $this->database   = $this->connection->getDriverName();
44
        if ($this->isDebugging()) {
45
            $this->connection->enableQueryLog();
46
        }
47
    }
48
49
    /**
50
     * Set auto filter off and run your own filter.
51
     * Overrides global search
52
     *
53
     * @param \Closure $callback
54
     * @return $this
55
     */
56
    public function filter(Closure $callback)
57
    {
58
        $this->overrideGlobalSearch($callback, $this->query);
59
60
        return $this;
61
    }
62
63
    /**
64
     * Organizes works
65
     *
66
     * @param bool $mDataSupport
67
     * @param bool $orderFirst
68
     * @return \Illuminate\Http\JsonResponse
69
     */
70
    public function make($mDataSupport = false, $orderFirst = false)
71
    {
72
        return parent::make($mDataSupport, $orderFirst);
73
    }
74
75
    /**
76
     * Count total items.
77
     *
78
     * @return integer
79
     */
80
    public function totalCount()
81
    {
82
        return $this->count();
83
    }
84
85
    /**
86
     * Counts current query.
87
     *
88
     * @return int
89
     */
90
    public function count()
91
    {
92
        $myQuery = clone $this->query;
93
        // if its a normal query ( no union, having and distinct word )
94
        // replace the select with static text to improve performance
95
        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...
96
            $row_count = $this->connection->getQueryGrammar()->wrap('row_count');
97
            $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...
98
        }
99
100
        return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table'))
101
                                ->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...
102
    }
103
104
    /**
105
     * Perform global search.
106
     *
107
     * @return void
108
     */
109
    public function filtering()
110
    {
111
        $this->query->where(
112
            function ($query) {
113
                $globalKeyword = $this->setupKeyword($this->request->keyword());
114
                $queryBuilder  = $this->getQueryBuilder($query);
115
116
                foreach ($this->request->searchableColumnIndex() as $index) {
117
                    $columnName = $this->getColumnName($index);
118
                    if ($this->isBlacklisted($columnName)) {
119
                        continue;
120
                    }
121
122
                    // check if custom column filtering is applied
123
                    if (isset($this->columnDef['filter'][$columnName])) {
124
                        $columnDef = $this->columnDef['filter'][$columnName];
125
                        // check if global search should be applied for the specific column
126
                        $applyGlobalSearch = count($columnDef['parameters']) == 0 || end($columnDef['parameters']) !== false;
127
                        if (! $applyGlobalSearch) {
128
                            continue;
129
                        }
130
131
                        if ($columnDef['method'] instanceof Closure) {
132
                            $whereQuery = $queryBuilder->newQuery();
133
                            call_user_func_array($columnDef['method'], [$whereQuery, $this->request->keyword()]);
134
                            $queryBuilder->addNestedWhereQuery($whereQuery, 'or');
135
                        } else {
136
                            $this->compileColumnQuery(
137
                                $queryBuilder,
138
                                Helper::getOrMethod($columnDef['method']),
139
                                $columnDef['parameters'],
140
                                $columnName,
141
                                $this->request->keyword()
142
                            );
143
                        }
144
                    } else {
145
                        if (count(explode('.', $columnName)) > 1) {
146
                            $eagerLoads     = $this->getEagerLoads();
147
                            $parts          = explode('.', $columnName);
148
                            $relationColumn = array_pop($parts);
149
                            $relation       = implode('.', $parts);
150
                            if (in_array($relation, $eagerLoads)) {
151
                                $this->compileRelationSearch(
152
                                    $queryBuilder,
153
                                    $relation,
154
                                    $relationColumn,
155
                                    $globalKeyword
156
                                );
157
                            } else {
158
                                $this->compileGlobalSearch($queryBuilder, $columnName, $globalKeyword);
159
                            }
160
                        } else {
161
                            $this->compileGlobalSearch($queryBuilder, $columnName, $globalKeyword);
162
                        }
163
                    }
164
165
                    $this->isFilterApplied = true;
166
                }
167
            }
168
        );
169
    }
170
171
    /**
172
     * Perform filter column on selected field.
173
     *
174
     * @param mixed $query
175
     * @param string|Closure $method
176
     * @param mixed $parameters
177
     * @param string $column
178
     * @param string $keyword
179
     */
180
    protected function compileColumnQuery($query, $method, $parameters, $column, $keyword)
181
    {
182
        if (method_exists($query, $method)
183
            && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters()
184
        ) {
185
            if (Str::contains(Str::lower($method), 'raw')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 180 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...
186
                || Str::contains(Str::lower($method), 'exists')
0 ignored issues
show
Bug introduced by
It seems like $method defined by parameter $method on line 180 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...
187
            ) {
188
                call_user_func_array(
189
                    [$query, $method],
190
                    $this->parameterize($parameters, $keyword)
191
                );
192
            } else {
193
                call_user_func_array(
194
                    [$query, $method],
195
                    $this->parameterize($column, $parameters, $keyword)
196
                );
197
            }
198
        }
199
    }
200
201
    /**
202
     * Build Query Builder Parameters.
203
     *
204
     * @return array
205
     */
206
    protected function parameterize()
207
    {
208
        $args       = func_get_args();
209
        $keyword    = count($args) > 2 ? $args[2] : $args[1];
210
        $parameters = Helper::buildParameters($args);
211
        $parameters = Helper::replacePatternWithKeyword($parameters, $keyword, '$1');
212
213
        return $parameters;
214
    }
215
216
    /**
217
     * Get eager loads keys if eloquent.
218
     *
219
     * @return array
220
     */
221
    protected function getEagerLoads()
222
    {
223
        if ($this->query_type == 'eloquent') {
224
            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...
225
        }
226
227
        return [];
228
    }
229
230
    /**
231
     * Add relation query on global search.
232
     *
233
     * @param mixed $query
234
     * @param string $relation
235
     * @param string $column
236
     * @param string $keyword
237
     */
238
    protected function compileRelationSearch($query, $relation, $column, $keyword)
239
    {
240
        $myQuery = clone $this->query;
241
        $myQuery->orWhereHas($relation, function ($q) use ($column, $keyword, $query) {
0 ignored issues
show
Bug introduced by
The method orWhereHas 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...
242
            $sql = $q->select($this->connection->raw('count(1)'))
243
                     ->where($column, 'like', $keyword)
244
                     ->toSql();
245
            $sql = "($sql) >= 1";
246
            $query->orWhereRaw($sql, [$keyword]);
247
        });
248
    }
249
250
    /**
251
     * Add a query on global search.
252
     *
253
     * @param mixed $query
254
     * @param string $column
255
     * @param string $keyword
256
     */
257
    protected function compileGlobalSearch($query, $column, $keyword)
258
    {
259
        $column = $this->castColumn($column);
260
        $sql    = $column . ' LIKE ?';
261
        if ($this->isCaseInsensitive()) {
262
            $sql     = 'LOWER(' . $column . ') LIKE ?';
263
            $keyword = Str::lower($keyword);
264
        }
265
266
        $query->orWhereRaw($sql, [$keyword]);
267
    }
268
269
    /**
270
     * Wrap a column and cast in pgsql.
271
     *
272
     * @param  string $column
273
     * @return string
274
     */
275
    public function castColumn($column)
276
    {
277
        $column = $this->connection->getQueryGrammar()->wrap($column);
278
        if ($this->database === 'pgsql') {
279
            $column = 'CAST(' . $column . ' as TEXT)';
280
        }
281
282
        return $column;
283
    }
284
285
    /**
286
     * Perform column search.
287
     *
288
     * @return void
289
     */
290
    public function columnSearch()
291
    {
292
        $columns = $this->request->get('columns', []);
293
294
        foreach ($columns as $index => $column) {
295
            if (! $this->request->isColumnSearchable($index)) {
296
                continue;
297
            }
298
299
            $column = $this->getColumnName($index);
300
301
            if (isset($this->columnDef['filter'][$column])) {
302
                $columnDef = $this->columnDef['filter'][$column];
303
                // get a raw keyword (without wildcards)
304
                $keyword = $this->getSearchKeyword($index, true);
305
                $builder = $this->getQueryBuilder();
306
307
                if ($columnDef['method'] instanceof Closure) {
308
                    $whereQuery = $builder->newQuery();
309
                    call_user_func_array($columnDef['method'], [$whereQuery, $keyword]);
310
                    $builder->addNestedWhereQuery($whereQuery);
311
                } else {
312
                    $this->compileColumnQuery(
313
                        $builder,
314
                        $columnDef['method'],
315
                        $columnDef['parameters'],
316
                        $column,
317
                        $keyword
318
                    );
319
                }
320
            } else {
321
                $column  = $this->castColumn($column);
322
                $keyword = $this->getSearchKeyword($index);
323
324
                if ($this->isCaseInsensitive()) {
325
                    $this->compileColumnSearch($index, $column, $keyword, false);
326
                } else {
327
                    $col = strstr($column, '(') ? $this->connection->raw($column) : $column;
328
                    $this->compileColumnSearch($index, $col, $keyword, true);
329
                }
330
            }
331
332
            $this->isFilterApplied = true;
333
        }
334
    }
335
336
    /**
337
     * Get proper keyword to use for search.
338
     *
339
     * @param int $i
340
     * @param bool $raw
341
     * @return string
342
     */
343
    private function getSearchKeyword($i, $raw = false)
344
    {
345
        $keyword = $this->request->columnKeyword($i);
346
        if ($raw || $this->request->isRegex($i)) {
347
            return $keyword;
348
        }
349
350
        return $this->setupKeyword($keyword);
351
    }
352
353
    /**
354
     * Compile queries for column search.
355
     *
356
     * @param int $i
357
     * @param mixed $column
358
     * @param string $keyword
359
     * @param bool $caseSensitive
360
     */
361
    protected function compileColumnSearch($i, $column, $keyword, $caseSensitive = true)
362
    {
363
        if ($this->request->isRegex($i)) {
364
            $this->regexColumnSearch($column, $keyword, $caseSensitive);
365
        } else {
366
            $sql     = $caseSensitive ? $column . ' LIKE ?' : 'LOWER(' . $column . ') LIKE ?';
367
            $keyword = $caseSensitive ? $keyword : Str::lower($keyword);
368
            $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...
369
        }
370
    }
371
372
    /**
373
     * Compile regex query column search.
374
     *
375
     * @param mixed $column
376
     * @param string $keyword
377
     * @param bool $caseSensitive
378
     */
379
    protected function regexColumnSearch($column, $keyword, $caseSensitive = true)
380
    {
381
        if ($this->isOracleSql()) {
382
            $sql = $caseSensitive ? 'REGEXP_LIKE( ' . $column . ' , ? )' : 'REGEXP_LIKE( LOWER(' . $column . ') , ?, \'i\' )';
383
            $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...
384
        } else {
385
            $sql = $caseSensitive ? $column . ' REGEXP ?' : 'LOWER(' . $column . ') REGEXP ?';
386
            $this->query->whereRaw($sql, [Str::lower($keyword)]);
387
        }
388
    }
389
390
    /**
391
     * Perform sorting of columns.
392
     *
393
     * @return void
394
     */
395
    public function ordering()
396
    {
397
        if ($this->orderCallback) {
398
            call_user_func($this->orderCallback, $this->getQueryBuilder());
399
400
            return;
401
        }
402
403
        foreach ($this->request->orderableColumns() as $orderable) {
404
            $column = $this->getColumnName($orderable['column'], true);
405
406
            if ($this->isBlacklisted($column)) {
407
                continue;
408
            }
409
410
            if (isset($this->columnDef['order'][$column])) {
411
                $method     = $this->columnDef['order'][$column]['method'];
412
                $parameters = $this->columnDef['order'][$column]['parameters'];
413
                $this->compileColumnQuery(
414
                    $this->getQueryBuilder(),
415
                    $method,
416
                    $parameters,
417
                    $column,
418
                    $orderable['direction']
419
                );
420
            } else {
421
                if (count(explode('.', $column)) > 1) {
422
                    $eagerLoads     = $this->getEagerLoads();
423
                    $parts          = explode('.', $column);
424
                    $relationColumn = array_pop($parts);
425
                    $relation       = implode('.', $parts);
426
427
                    if (in_array($relation, $eagerLoads)) {
428
                        $column = $this->joinEagerLoadedColumn($relation, $relationColumn);
429
                    }
430
                }
431
432
                $this->getQueryBuilder()->orderBy($column, $orderable['direction']);
433
            }
434
        }
435
    }
436
437
    /**
438
     * Join eager loaded relation and get the related column name.
439
     *
440
     * @param string $relation
441
     * @param string $relationColumn
442
     * @return string
443
     */
444
    protected function joinEagerLoadedColumn($relation, $relationColumn)
445
    {
446
        $table   = $this->query->getRelation($relation)->getRelated()->getTable();
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...
447
        $foreign = $this->query->getRelation($relation)->getQualifiedForeignKey();
448
        $other   = $this->query->getRelation($relation)->getQualifiedOtherKeyName();
449
        $column  = $table . '.' . $relationColumn;
450
451
        $joins = [];
452
        foreach ((array) $this->getQueryBuilder()->joins as $key => $join) {
453
            $joins[] = $join->table;
454
        }
455
456
        if (! in_array($table, $joins)) {
457
            $this->getQueryBuilder()
458
                 ->leftJoin($table, $foreign, '=', $other);
459
        }
460
461
        return $column;
462
    }
463
464
    /**
465
     * Perform pagination
466
     *
467
     * @return void
468
     */
469
    public function paging()
470
    {
471
        $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...
472
                    ->take((int) $this->request['length'] > 0 ? $this->request['length'] : 10);
473
    }
474
475
    /**
476
     * Get results
477
     *
478
     * @return array|static[]
479
     */
480
    public function results()
481
    {
482
        return $this->query->get();
483
    }
484
}
485