forked from nicolaslopezj/searchable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchableTrait.php
335 lines (289 loc) · 10.2 KB
/
SearchableTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<?php namespace Nicolaslopezj\Searchable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Trait SearchableTrait
* @package Nicolaslopezj\Searchable
* @property array $searchable
* @property string $table
* @property string $primaryKey
* @method string getTable()
*/
trait SearchableTrait
{
/**
* @var array
*/
protected $search_bindings = [];
/**
* Creates the search scope.
*
* @param \Illuminate\Database\Eloquent\Builder $q
* @param string $search
* @param float|null $threshold
* @param boolean $entireText
* @param boolean $entireTextOnly
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch(Builder $q, $search, $threshold = null, $entireText = false, $entireTextOnly = false)
{
return $this->scopeSearchRestricted($q, $search, null, $threshold, $entireText, $entireTextOnly);
}
public function scopeSearchRestricted(Builder $q, $search, $restriction, $threshold = null, $entireText = false, $entireTextOnly = false)
{
$query = clone $q;
$query->select($this->getTable() . '.*');
$this->makeJoins($query);
if ( ! $search)
{
return $q;
}
$search = mb_strtolower(trim($search));
preg_match_all('/(?:")((?:\\\\.|[^\\\\"])*)(?:")|(\S+)/', $search, $matches);
$words = $matches[1];
for ($i = 2; $i < count($matches); $i++) {
$words = array_filter($words) + $matches[$i];
}
$selects = [];
$this->search_bindings = [];
$relevance_count = 0;
foreach ($this->getColumns() as $column => $relevance)
{
$relevance_count += $relevance;
if (!$entireTextOnly) {
$queries = $this->getSearchQueriesForColumn($query, $column, $relevance, $words);
} else {
$queries = [];
}
if ( ($entireText === true && count($words) > 1) || $entireTextOnly === true )
{
$queries[] = $this->getSearchQuery($query, $column, $relevance, [$search], 50, '', '');
$queries[] = $this->getSearchQuery($query, $column, $relevance, [$search], 30, '%', '%');
}
foreach ($queries as $select)
{
$selects[] = $select;
}
}
$this->addSelectsToQuery($query, $selects);
// Default the threshold if no value was passed.
if (is_null($threshold)) {
$threshold = $relevance_count / 4;
}
$this->filterQueryWithRelevance($query, $selects, $threshold);
$this->makeGroupBy($query);
if(is_callable($restriction)) {
$query = $restriction($query);
}
$this->mergeQueries($query, $q);
return $q;
}
/**
* Returns database driver Ex: mysql, pgsql, sqlite.
*
* @return array
*/
protected function getDatabaseDriver() {
$key = $this->connection ?: Config::get('database.default');
return Config::get('database.connections.' . $key . '.driver');
}
/**
* Returns the search columns.
*
* @return array
*/
protected function getColumns()
{
if (array_key_exists('columns', $this->searchable)) {
$driver = $this->getDatabaseDriver();
$prefix = Config::get("database.connections.$driver.prefix");
$columns = [];
foreach($this->searchable['columns'] as $column => $priority){
$columns[$prefix . $column] = $priority;
}
return $columns;
} else {
return DB::connection()->getSchemaBuilder()->getColumnListing($this->table);
}
}
/**
* Returns whether or not to keep duplicates.
*
* @return array
*/
protected function getGroupBy()
{
if (array_key_exists('groupBy', $this->searchable)) {
return $this->searchable['groupBy'];
}
return false;
}
/**
* Returns the table columns.
*
* @return array
*/
public function getTableColumns()
{
return $this->searchable['table_columns'];
}
/**
* Returns the tables that are to be joined.
*
* @return array
*/
protected function getJoins()
{
return array_get($this->searchable, 'joins', []);
}
/**
* Adds the sql joins to the query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
*/
protected function makeJoins(Builder $query)
{
foreach ($this->getJoins() as $table => $keys) {
$query->leftJoin($table, function ($join) use ($keys) {
$join->on($keys[0], '=', $keys[1]);
if (array_key_exists(2, $keys) && array_key_exists(3, $keys)) {
$join->whereRaw($keys[2] . ' = "' . $keys[3] . '"');
}
});
}
}
/**
* Makes the query not repeat the results.
*
* @param \Illuminate\Database\Eloquent\Builder $query
*/
protected function makeGroupBy(Builder $query)
{
if ($groupBy = $this->getGroupBy()) {
$query->groupBy($groupBy);
} else {
$driver = $this->getDatabaseDriver();
if ($driver == 'sqlsrv') {
$columns = $this->getTableColumns();
} else {
$columns = $this->getTable() . '.' .$this->primaryKey;
}
$query->groupBy($columns);
$joins = array_keys(($this->getJoins()));
foreach ($this->getColumns() as $column => $relevance) {
array_map(function ($join) use ($column, $query) {
if (Str::contains($column, $join)) {
$query->groupBy($column);
}
}, $joins);
}
}
}
/**
* Puts all the select clauses to the main query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $selects
*/
protected function addSelectsToQuery(Builder $query, array $selects)
{
$query->selectRaw('max(' . implode(' + ', $selects) . ') as relevance', $this->search_bindings);
}
/**
* Adds the relevance filter to the query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $selects
* @param float $relevance_count
*/
protected function filterQueryWithRelevance(Builder $query, array $selects, $relevance_count)
{
$comparator = $this->getDatabaseDriver() != 'mysql' ? implode(' + ', $selects) : 'relevance';
$relevance_count=number_format($relevance_count,2,'.','');
$query->havingRaw("$comparator >= $relevance_count");
$query->orderBy('relevance', 'desc');
// add bindings to postgres
}
/**
* Returns the search queries for the specified column.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param float $relevance
* @param array $words
* @return array
*/
protected function getSearchQueriesForColumn(Builder $query, $column, $relevance, array $words)
{
$queries = [];
$queries[] = $this->getSearchQuery($query, $column, $relevance, $words, 15);
$queries[] = $this->getSearchQuery($query, $column, $relevance, $words, 5, '', '%');
$queries[] = $this->getSearchQuery($query, $column, $relevance, $words, 1, '%', '%');
return $queries;
}
/**
* Returns the sql string for the given parameters.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param string $relevance
* @param array $words
* @param string $compare
* @param float $relevance_multiplier
* @param string $pre_word
* @param string $post_word
* @return string
*/
protected function getSearchQuery(Builder $query, $column, $relevance, array $words, $relevance_multiplier, $pre_word = '', $post_word = '')
{
$like_comparator = $this->getDatabaseDriver() == 'pgsql' ? 'ILIKE' : 'LIKE';
$cases = [];
foreach ($words as $word)
{
$cases[] = $this->getCaseCompare($column, $like_comparator, $relevance * $relevance_multiplier);
$this->search_bindings[] = $pre_word . $word . $post_word;
}
return implode(' + ', $cases);
}
/**
* Returns the comparison string.
*
* @param string $column
* @param string $compare
* @param float $relevance
* @return string
*/
protected function getCaseCompare($column, $compare, $relevance) {
if($this->getDatabaseDriver() == 'pgsql') {
$field = "LOWER(" . $column . ") " . $compare . " ?";
return '(case when ' . $field . ' then ' . $relevance . ' else 0 end)';
}
$column = str_replace('.', '`.`', $column);
$field = "LOWER(`" . $column . "`) " . $compare . " ?";
return '(case when ' . $field . ' then ' . $relevance . ' else 0 end)';
}
/**
* Merge our cloned query builder with the original one.
*
* @param \Illuminate\Database\Eloquent\Builder $clone
* @param \Illuminate\Database\Eloquent\Builder $original
*/
protected function mergeQueries(Builder $clone, Builder $original) {
$tableName = DB::connection($this->connection)->getTablePrefix() . $this->getTable();
if ($this->getDatabaseDriver() == 'pgsql') {
$original->from(DB::connection($this->connection)->raw("({$clone->toSql()}) as {$tableName}"));
} else {
$original->from(DB::connection($this->connection)->raw("({$clone->toSql()}) as `{$tableName}`"));
}
// First create a new array merging bindings
$mergedBindings = array_merge_recursive(
$clone->getBindings(),
$original->getBindings()
);
// Then apply bindings WITHOUT global scopes which are already included. If not, there is a strange behaviour
// with some scope's bindings remaning
$original->withoutGlobalScopes()->setBindings($mergedBindings);
}
}