-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchAction.php
More file actions
50 lines (43 loc) · 1.67 KB
/
SearchAction.php
File metadata and controls
50 lines (43 loc) · 1.67 KB
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
<?php
declare(strict_types=1);
namespace App\Actions\SearchPage;
use App\Models\Page;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
final class SearchAction
{
/**
* @param array{keyword:string,paks:array<int,int|string>,sites:array<int,string>,page?:int|numeric-string|null} $data
* @return LengthAwarePaginator<int,Page>
*/
public function __invoke(array $data): LengthAwarePaginator
{
$query = Page::query()
->withWhereHas('paks', fn (Builder|Relation $builder) => $builder->whereIn('slug', $data['paks']))
->whereIn('site_name', $data['sites']);
$this->addKeywordQuery($query, $data['keyword']);
return $query->orderBy('last_modified', 'desc')
->paginate(perPage: 50, page: (int) ($data['page'] ?? 1))
->withQueryString();
}
/**
* @param Builder<Page> $builder
*/
private function addKeywordQuery(Builder $builder, string $keyword): void
{
foreach (explode(' ', $keyword) as $word) {
$word = trim($word);
if (str_starts_with($word, '-')) {
$word = trim(substr($word, 1));
if ($word !== '' && $word !== '0') {
$builder->where('title', 'not like', sprintf('%%%s%%', $word));
$builder->where('text', 'not like', sprintf('%%%s%%', $word));
}
} else {
$builder->where('title', 'like', sprintf('%%%s%%', $word));
$builder->where('text', 'like', sprintf('%%%s%%', $word));
}
}
}
}