-
Notifications
You must be signed in to change notification settings - Fork 554
/
FreeTextSearch.php
46 lines (38 loc) · 1.41 KB
/
FreeTextSearch.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
<?php
namespace A17\Twill\Services\Listings\Filters;
use Illuminate\Database\Eloquent\Builder;
/**
* This filter is used internally and will not have any effect when used in your quickfilters/filters list.
*/
class FreeTextSearch extends TwillBaseFilter
{
protected array $searchColumns = [];
protected ?string $searchString = null;
public function applyFilter(Builder $builder): Builder
{
if (!empty($this->searchString) && $this->searchColumns !== []) {
/** @var \A17\Twill\Models\Model $builderModel */
$translatedAttributes = $builder->getModel()->getTranslatedAttributes();
$builder->where(function (Builder $builder) use ($translatedAttributes) {
foreach ($this->searchColumns as $column) {
if (in_array($column, $translatedAttributes, true)) {
$builder->orWhereTranslationLike($column, "%$this->searchString%");
} else {
$builder->orWhere($column, getLikeOperator(), "%$this->searchString%");
}
}
});
}
return $builder;
}
public function searchFor(string $searchString): static
{
$this->searchString = $searchString;
return $this;
}
public function searchColumns(array $columns): static
{
$this->searchColumns = $columns;
return $this;
}
}