|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace CSlant\Blog\Api\Services; |
|
4
|
|
|
|
|
5
|
|
|
use CSlant\Blog\Core\Http\Responses\Base\BaseHttpResponse; |
|
6
|
|
|
use CSlant\Blog\Core\Models\Post; |
|
7
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator; |
|
8
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
9
|
|
|
use Illuminate\Support\Arr; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class PostService |
|
13
|
|
|
* |
|
14
|
|
|
* @package CSlant\Blog\Api\Services |
|
15
|
|
|
* |
|
16
|
|
|
* @method BaseHttpResponse httpResponse() |
|
17
|
|
|
*/ |
|
18
|
|
|
class PostService |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* Get posts by filters. |
|
22
|
|
|
* |
|
23
|
|
|
* @param array<string, mixed> $filters |
|
24
|
|
|
* |
|
25
|
|
|
* @return LengthAwarePaginator<Post> |
|
26
|
|
|
*/ |
|
27
|
|
|
public function getCustomFilters(array $filters): LengthAwarePaginator |
|
28
|
|
|
{ |
|
29
|
|
|
$data = Post::query(); |
|
30
|
|
|
|
|
31
|
|
|
if ($filters['categories'] !== null) { |
|
32
|
|
|
$categories = array_filter((array) $filters['categories']); |
|
33
|
|
|
|
|
34
|
|
|
$data = $data->whereHas('categories', function (Builder $query) use ($categories): void { |
|
35
|
|
|
$query->whereIn('categories.id', $categories); |
|
36
|
|
|
}); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
if ($filters['tags'] !== null) { |
|
40
|
|
|
$tags = array_filter((array) $filters['tags']); |
|
41
|
|
|
|
|
42
|
|
|
$data = $data->whereHas('tags', function (Builder $query) use ($tags): void { |
|
43
|
|
|
$query->whereIn('tags.id', $tags); |
|
44
|
|
|
}); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$orderBy = Arr::get($filters, 'order_by', 'updated_at'); |
|
48
|
|
|
$order = Arr::get($filters, 'order', 'desc'); |
|
49
|
|
|
|
|
50
|
|
|
$data = $data |
|
51
|
|
|
->wherePublished() |
|
52
|
|
|
->orderBy($orderBy, $order); |
|
53
|
|
|
|
|
54
|
|
|
return $data->paginate((int) $filters['per_page']); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|