Passed
Pull Request — main (#63)
by
unknown
06:27 queued 03:11
created

PostService   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 2
Metric Value
eloc 12
c 4
b 0
f 2
dl 0
loc 28
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A getPostByTags() 0 20 2
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 tags.
22
     *
23
     * @param array<string, mixed> $filters
24
     * @return Builder<Post>|LengthAwarePaginator
25
     */
26
    public function getPostByTags(array $filters): Builder|LengthAwarePaginator
27
    {
28
        $data = Post::query();
29
30
        if ($filters['tags'] !== null) {
31
            $tags = array_filter((array) $filters['tags']);
32
33
            $data = $data->whereHas('tags', function (Builder $query) use ($tags): void {
34
                $query->whereIn('tags.id', $tags);
35
            });
36
        }
37
38
        $orderBy = Arr::get($filters, 'order_by', 'updated_at');
39
        $order = Arr::get($filters, 'order', 'desc');
40
41
        $data = $data
42
            ->wherePublished()
43
            ->orderBy($orderBy, $order);
44
45
        return $data->paginate((int) $filters['per_page']);
46
    }
47
}
48