Passed
Pull Request — main (#63)
by Tan
05:49 queued 02:49
created

PostService   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 5
Bugs 1 Features 2
Metric Value
wmc 2
eloc 12
c 5
b 1
f 2
dl 0
loc 29
rs 10

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