Passed
Push — main ( 327ac0...2d65ac )
by Tan
02:35
created

CategoryController::index()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 75
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 54
c 2
b 0
f 0
dl 0
loc 75
rs 9.0036
cc 2
nc 1
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace CSlant\Blog\Api\Http\Controllers;
4
5
use Botble\Base\Http\Responses\BaseHttpResponse;
0 ignored issues
show
Bug introduced by
The type Botble\Base\Http\Responses\BaseHttpResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use CSlant\Blog\Api\Enums\StatusEnum;
7
use CSlant\Blog\Api\Http\Resources\ListCategoryResource;
8
use CSlant\Blog\Api\OpenApi\Schemas\Resources\Category\CategoryListResourceSchema;
9
use CSlant\Blog\Core\Facades\Base\SlugHelper;
10
use CSlant\Blog\Core\Http\Controllers\Base\BaseCategoryController;
11
use CSlant\Blog\Core\Models\Category;
12
use CSlant\Blog\Core\Models\Slug;
13
use Illuminate\Http\JsonResponse;
14
use Illuminate\Http\RedirectResponse;
15
use Illuminate\Http\Request;
16
use Illuminate\Http\Resources\Json\JsonResource;
17
use OpenApi\Attributes\Get;
18
use OpenApi\Attributes\Items;
19
use OpenApi\Attributes\JsonContent;
20
use OpenApi\Attributes\Parameter;
21
use OpenApi\Attributes\Property;
22
use OpenApi\Attributes\Response;
23
use OpenApi\Attributes\Schema;
24
25
/**
26
 * Class CategoryController
27
 *
28
 * @package CSlant\Blog\Api\Http\Controllers
29
 *
30
 * @group Blog API
31
 *
32
 * @authenticated
33
 *
34
 * @method BaseHttpResponse httpResponse()
35
 * @method BaseHttpResponse setData(mixed $data)
36
 * @method BaseHttpResponse|JsonResource|JsonResponse|RedirectResponse toApiResponse()
37
 */
38
class CategoryController extends BaseCategoryController
39
{
40
    #[
41
        Get(
42
            path: "/categories",
43
            operationId: "categoryGetAllWithFilter",
44
            description: "Get all categories with pagination (10 items per page by default, page 1 by default)
45
            
46
    This API will get records from the database and return them as a paginated list. 
47
    The default number of items per page is 10 and the default page number is 1. You can change these values by passing the `per_page` and `page` query parameters.
48
            ",
49
            summary: "Get all categories with pagination",
50
            tags: ["Category"],
51
            parameters: [
52
                new Parameter(
53
                    name: 'per_page',
54
                    description: 'Number of items per page',
55
                    in: 'query',
56
                    required: false,
57
                    schema: new Schema(type: 'integer', default: 10)
58
                ),
59
                new Parameter(
60
                    name: 'page',
61
                    description: 'Page number',
62
                    in: 'query',
63
                    required: false,
64
                    schema: new Schema(type: 'integer', default: 1)
65
                ),
66
            ],
67
            responses: [
68
                new Response(
69
                    response: 200,
70
                    description: "Get categories successfully",
71
                    content: new JsonContent(
72
                        properties: [
73
                            new Property(
74
                                property: 'error',
75
                                description: 'Error status',
76
                                type: 'boolean',
77
                                default: false
78
                            ),
79
                            new Property(
80
                                property: "data",
81
                                description: "Data of model",
82
                                type: "array",
83
                                items: new Items(ref: CategoryListResourceSchema::class)
84
                            ),
85
                        ]
86
                    )
87
                ),
88
                new Response(
89
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\BadRequestResponseSchema::class,
90
                    response: 400,
91
                ),
92
                new Response(
93
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\ErrorNotFoundResponseSchema::class,
94
                    response: 404,
95
                ),
96
                new Response(
97
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\InternalServerResponseSchema::class,
98
                    response: 500,
99
                ),
100
            ]
101
        )
102
    ]
103
    public function index(Request $request): BaseHttpResponse|JsonResponse|JsonResource|RedirectResponse
104
    {
105
        $data = Category::query()
106
            ->wherePublished()
107
            ->orderByDesc('created_at')
108
            ->with(['slugable'])
109
            ->paginate($request->integer('per_page', 10) ?: 10);
110
111
        return $this
112
            ->httpResponse()
113
            ->setData(ListCategoryResource::collection($data))
114
            ->toApiResponse();
115
    }
116
117
    /**
118
     *  Get category by slug
119
     *
120
     * @group Blog
121
     * @queryParam slug Find by slug of category.
122
     *
123
     * @param  string  $slug
124
     *
125
     * @return BaseHttpResponse|JsonResource|JsonResponse|RedirectResponse
126
     */
127
    #[
128
        Get(
129
            path: "/categories/{slug}",
130
            operationId: "categoryFilterBySlug",
131
            description: "Get the category by slug
132
            
133
    This API will get records from the database and return the category by slug.
134
            ",
135
            summary: "Get category by slug",
136
            tags: ["Category"],
137
            parameters: [
138
                new Parameter(
139
                    name: 'slug',
140
                    description: 'Category slug',
141
                    in: 'path',
142
                    required: true,
143
                    schema: new Schema(type: 'string', example: 'php')
144
                ),
145
            ],
146
            responses: [
147
                new Response(
148
                    response: 200,
149
                    description: "Get category successfully",
150
                    content: new JsonContent(
151
                        properties: [
152
                            new Property(
153
                                property: 'error',
154
                                description: 'Error status',
155
                                type: 'boolean',
156
                                default: false
157
                            ),
158
                            new Property(
159
                                property: "data",
160
                                ref: CategoryListResourceSchema::class,
161
                                description: "Data of model",
162
                                type: "object",
163
                            ),
164
                        ]
165
                    )
166
                ),
167
                new Response(
168
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\BadRequestResponseSchema::class,
169
                    response: 400,
170
                ),
171
                new Response(
172
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\ErrorNotFoundResponseSchema::class,
173
                    response: 404,
174
                ),
175
                new Response(
176
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\InternalServerResponseSchema::class,
177
                    response: 500,
178
                ),
179
            ]
180
        )
181
    ]
182
    public function findBySlug(string $slug): JsonResponse|RedirectResponse|JsonResource|BaseHttpResponse
183
    {
184
        /** @var Slug $slug */
185
        $slug = SlugHelper::getSlug($slug, SlugHelper::getPrefix(Category::getBaseModel()));
186
187
        if (!$slug) {
0 ignored issues
show
introduced by
$slug is of type CSlant\Blog\Core\Models\Slug, thus it always evaluated to true.
Loading history...
188
            return $this
189
                ->httpResponse()
190
                ->setError()
191
                ->setCode(404)
192
                ->setMessage('Not found');
193
        }
194
195
        $category = Category::query()
196
            ->with(['slugable'])
197
            ->where([
198
                'id' => $slug->reference_id,
199
                'status' => StatusEnum::PUBLISHED,
200
            ])
201
            ->first();
202
203
        if (!$category) {
204
            return $this
205
                ->httpResponse()
206
                ->setError()
207
                ->setCode(404)
208
                ->setMessage('Not found');
209
        }
210
211
        return $this
212
            ->httpResponse()
213
            ->setData(ListCategoryResource::make($category))
214
            ->toApiResponse();
215
    }
216
}
217