1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CSlant\Blog\Api\Services; |
4
|
|
|
|
5
|
|
|
use CSlant\Blog\Api\Supports\Queries\QueryPost; |
6
|
|
|
use CSlant\Blog\Core\Http\Responses\Base\BaseHttpResponse; |
7
|
|
|
use CSlant\Blog\Core\Models\Post; |
8
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator; |
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
|
|
|
* @param array<string, mixed> $filters |
22
|
|
|
* |
23
|
|
|
* @return LengthAwarePaginator<int, Post> |
24
|
|
|
*/ |
25
|
|
|
public function getCustomFilters(array $filters): LengthAwarePaginator |
26
|
|
|
{ |
27
|
|
|
$query = Post::query()->withCount(['comments', 'likes'])->with(['comments', 'likes']); |
28
|
|
|
|
29
|
|
|
$query = QueryPost::setBaseCustomFilterQuery($query, $filters); |
30
|
|
|
|
31
|
|
|
$query = $query |
32
|
|
|
->wherePublished() |
33
|
|
|
->orderBy( |
34
|
|
|
Arr::get($filters, 'order_by', 'updated_at'), |
35
|
|
|
Arr::get($filters, 'order', 'desc') |
36
|
|
|
); |
37
|
|
|
|
38
|
|
|
return $query->paginate((int) $filters['per_page']); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Get navigation posts based on ID sequence |
43
|
|
|
* Previous = ID smaller than current, Next = ID larger than current |
44
|
|
|
* |
45
|
|
|
* @param Post $currentPost |
46
|
|
|
* @return array{previous: null|Post, next: null|Post} |
47
|
|
|
*/ |
48
|
|
|
public function getNavigationPosts(Post $currentPost): array |
49
|
|
|
{ |
50
|
|
|
$currentId = $currentPost->id; |
51
|
|
|
|
52
|
|
|
// Get previous post (ID smaller than current, order by ID desc to get the closest one) |
53
|
|
|
$previous = Post::query() |
54
|
|
|
->wherePublished() |
55
|
|
|
->where('id', '<', $currentId) |
56
|
|
|
->with(['slugable', 'author']) |
57
|
|
|
->orderBy('id', 'desc') |
58
|
|
|
->first(); |
59
|
|
|
|
60
|
|
|
// Get next post (ID larger than current, order by ID asc to get the closest one) |
61
|
|
|
$next = Post::query() |
62
|
|
|
->wherePublished() |
63
|
|
|
->where('id', '>', $currentId) |
64
|
|
|
->with(['slugable', 'author']) |
65
|
|
|
->orderBy('id', 'asc') |
66
|
|
|
->first(); |
67
|
|
|
|
68
|
|
|
return [ |
69
|
|
|
'previous' => $previous, |
70
|
|
|
'next' => $next, |
71
|
|
|
]; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|