Completed
Push — master ( fd532c...18a507 )
by Song
04:27
created

HasQuickSearch::applyWhereLikeQuery()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 3
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Grid\Concerns;
4
5
use Encore\Admin\Grid\Column;
6
use Encore\Admin\Grid\Tools\QuickSearch;
7
use Illuminate\Support\Str;
8
9
trait HasQuickSearch
10
{
11
    /**
12
     * @var string
13
     */
14
    public static $searchKey = '__search__';
15
16
    /**
17
     * @var array|string|\Closure
18
     */
19
    protected $search;
20
21
    /**
22
     * @param array|string|\Closure
23
     * @return $this
24
     */
25
    public function quickSearch($search = null)
26
    {
27
        if (func_num_args() > 1) {
28
            $this->search = func_get_args();
29
        } else {
30
            $this->search = $search;
31
        }
32
33
        $this->tools->append(new QuickSearch());
0 ignored issues
show
Bug introduced by
The property tools does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
34
35
        return $this;
36
    }
37
38
    /**
39
     * Apply the search query to the query.
40
     *
41
     * @return mixed|void
42
     */
43
    protected function applyQuickSearch()
44
    {
45
        if (!$query = request()->get(static::$searchKey)) {
46
            return;
47
        }
48
49
        if ($this->search instanceof \Closure) {
50
            return call_user_func($this->search, $this->model(), $query);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
51
        }
52
53
        if (is_string($this->search)) {
54
            $this->search = [$this->search];
55
        }
56
57
        if (is_array($this->search)) {
58
            foreach ($this->search as $column) {
59
                $this->applyWhereLikeQuery($column, true, '%'.$query.'%');
60
            }
61
        } elseif (is_null($this->search)) {
62
            $this->dispatchSearchQuery($query);
63
        }
64
    }
65
66
    protected function mappingColumnAndConditions($queries)
67
    {
68
        $columnMap = $this->columns->mapWithKeys(function (Column $column) {
0 ignored issues
show
Bug introduced by
The property columns does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
69
70
            $label = $column->getLabel();
71
            $name  = $column->getName();
72
73
            return [$label => $name, $name => $name];
74
        });
75
76
        return collect($queries)->map(function ($query) use ($columnMap) {
77
            $segments = explode(':', $query, 2);
78
79
            if (count($segments) != 2) {
80
                return;
81
            }
82
83
            $or = false;
84
85
            list($column, $condition) = $segments;
86
87
            if (Str::startsWith($column, '|')) {
88
                $or = true;
89
                $column = substr($column, 1);
90
            }
91
92
            $column = $columnMap[$column];
93
94
            return [$column, $condition, $or];
95
        })->filter()->toArray();
96
    }
97
98
    protected function dispatchSearchQuery($query)
99
    {
100
        $queries = preg_split('/\s(?=([^"]*"[^"]*")*[^"]*$)/', trim($query));
101
102
        $mapping = $this->mappingColumnAndConditions($queries);
103
104
        foreach ($mapping as list($column, $condition, $or)) {
105
106
            if (preg_match('/(?<not>!?)\((?<values>.+)\)/', $condition, $match) !== 0) {
107
                $this->applyWhereInQuery($column, $or, $match['not'], $match['values']);
108
                continue;
109
            }
110
111
            if (preg_match('/\[(?<start>.*?),(?<end>.*?)]/', $condition, $match) !== 0) {
112
                $this->applyWhereBetweenQuery($column, $or, $match['start'], $match['end']);
113
                continue;
114
            }
115
116
            if (preg_match('/(?<function>date|time|day|month|year),(?<value>.*)/', $condition, $match) !== 0) {
117
                $this->applyWhereDatetimeQuery($column, $or, $match['function'], $match['value']);
118
                continue;
119
            }
120
121
            if (preg_match('/(?<pattern>%[^%]+%)/', $condition, $match) !== 0) {
122
                $this->applyWhereLikeQuery($column, $or, $match['pattern']);
123
                continue;
124
            }
125
126 View Code Duplication
            if (preg_match('/\/(?<value>.*)\//', $condition, $match) !== 0) {
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...
127
                $this->applyWhereQuery($column, $or, 'REGEXP', $match['value']);
128
                continue;
129
            }
130
131 View Code Duplication
            if (preg_match('/(?<operator>>=?|<=?|!=|%){0,1}(?<value>.*)/', $condition, $match) !== 0) {
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...
132
                $this->applyWhereQuery($column, $or, $match['operator'], $match['value']);
133
                continue;
134
            }
135
        }
136
    }
137
138
    protected function applyWhereLikeQuery($column, $or, $pattern)
139
    {
140
        $connectionType = $this->model()->eloquent()->getConnection()->getDriverName();
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
141
        $likeOperator   = $connectionType == 'pgsql' ? 'ilike' : 'like';
142
143
        $method = $or ? 'orWhere' : 'where';
144
145
        $this->model()->{$method}($column, $likeOperator, $pattern);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
146
    }
147
148
    protected function applyWhereDatetimeQuery($column, $or, $function, $value)
149
    {
150
        $method = ($or ? 'orWhere' : 'where') . ucfirst($function);
151
152
        $this->model()->$method($column, $value);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
153
    }
154
155
    protected function applyWhereInQuery($column, $or, $not, $values)
0 ignored issues
show
Unused Code introduced by
The parameter $not is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
156
    {
157
        $values = explode(',', $values);
158
159
        foreach ($values as $key => $value) {
160
            if ($value === 'NULL') {
161
                $values[$key] = null;
162
            }
163
        }
164
165
        $method = $or ? 'orWhereIn' : 'whereIn';
166
167
        $this->model()->$method($column, $values);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
168
    }
169
170
    protected function applyWhereBetweenQuery($column, $or, $start, $end)
171
    {
172
        $method = $or ? 'orWhereBetween' : 'whereBetween';
173
174
        $this->model()->$method($column, [$start, $end]);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
175
    }
176
177
    protected function applyWhereQuery($column, $or, $operator, $value)
178
    {
179
        $method = $or ? 'orWhere' : 'where';
180
181
        $operator = $operator ?: '=';
182
183
        if ($operator == '%') {
184
            $operator = 'like';
185
            $value = "%{$value}%";
186
        }
187
188
        if ($value === 'NULL') {
189
            $value = null;
190
        }
191
192
        if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
193
            $value = substr($value, 1, -1);
194
        }
195
196
        $this->model()->{$method}($column, $operator, $value);
0 ignored issues
show
Bug introduced by
It seems like model() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
197
    }
198
}