Passed
Pull Request — main (#71)
by
unknown
02:47
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 Botble\Blog\Http\Resources\CategoryResource;
0 ignored issues
show
Bug introduced by
The type Botble\Blog\Http\Resources\CategoryResource 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...
7
use Botble\Blog\Repositories\Interfaces\CategoryInterface;
0 ignored issues
show
Bug introduced by
The type Botble\Blog\Repositories...faces\CategoryInterface 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...
8
use Botble\Blog\Supports\FilterCategory;
0 ignored issues
show
Bug introduced by
The type Botble\Blog\Supports\FilterCategory 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...
9
use CSlant\Blog\Api\Enums\StatusEnum;
10
use CSlant\Blog\Api\Http\Resources\Category\ListCategoryResource;
11
use CSlant\Blog\Api\OpenApi\Schemas\Resources\Category\CategoryListResourceSchema;
12
use CSlant\Blog\Api\OpenApi\Schemas\Resources\Category\CategoryModelResourceSchema;
13
use CSlant\Blog\Api\Services\CategoryService;
14
use CSlant\Blog\Core\Facades\Base\SlugHelper;
15
use CSlant\Blog\Core\Http\Controllers\Base\BaseCategoryController;
16
use CSlant\Blog\Core\Models\Category;
17
use CSlant\Blog\Core\Models\Slug;
18
use Illuminate\Http\JsonResponse;
19
use Illuminate\Http\RedirectResponse;
20
use Illuminate\Http\Request;
21
use Illuminate\Http\Resources\Json\JsonResource;
22
use OpenApi\Attributes\Get;
23
use OpenApi\Attributes\Items;
24
use OpenApi\Attributes\JsonContent;
25
use OpenApi\Attributes\Parameter;
26
use OpenApi\Attributes\Property;
27
use OpenApi\Attributes\Response;
28
use OpenApi\Attributes\Schema;
29
30
/**
31
 * Class CategoryController
32
 *
33
 * @package CSlant\Blog\Api\Http\Controllers
34
 *
35
 * @group Blog API
36
 *
37
 * @authenticated
38
 *
39
 * @method BaseHttpResponse httpResponse()
40
 * @method BaseHttpResponse setData(mixed $data)
41
 * @method BaseHttpResponse|JsonResource|JsonResponse|RedirectResponse toApiResponse()
42
 */
43
class CategoryController extends BaseCategoryController
44
{
45
    protected CategoryService $categoryService;
46
47
    public function __construct(CategoryService $categoryService)
48
    {
49
        $this->categoryService = $categoryService;
50
    }
51
52
    #[
53
        Get(
54
            path: "/categories",
55
            operationId: "categoryGetAllWithFilter",
56
            description: "Get all categories with pagination (10 items per page by default, page 1 by default)
57
            
58
    This API will get records from the database and return them as a paginated list. 
59
    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.
60
            ",
61
            summary: "Get all categories with pagination",
62
            tags: ["Category"],
63
            parameters: [
64
                new Parameter(
65
                    name: 'per_page',
66
                    description: 'Number of items per page',
67
                    in: 'query',
68
                    required: false,
69
                    schema: new Schema(type: 'integer', default: 10)
70
                ),
71
                new Parameter(
72
                    name: 'page',
73
                    description: 'Page number',
74
                    in: 'query',
75
                    required: false,
76
                    schema: new Schema(type: 'integer', default: 1)
77
                ),
78
            ],
79
            responses: [
80
                new Response(
81
                    response: 200,
82
                    description: "Get categories successfully",
83
                    content: new JsonContent(
84
                        properties: [
85
                            new Property(
86
                                property: 'error',
87
                                description: 'Error status',
88
                                type: 'boolean',
89
                                default: false
90
                            ),
91
                            new Property(
92
                                property: "data",
93
                                description: "Data of model",
94
                                type: "array",
95
                                items: new Items(ref: CategoryListResourceSchema::class)
96
                            ),
97
                        ]
98
                    )
99
                ),
100
                new Response(
101
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\BadRequestResponseSchema::class,
102
                    response: 400,
103
                ),
104
                new Response(
105
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\ErrorNotFoundResponseSchema::class,
106
                    response: 404,
107
                ),
108
                new Response(
109
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\InternalServerResponseSchema::class,
110
                    response: 500,
111
                ),
112
            ]
113
        )
114
    ]
115
    public function index(Request $request): BaseHttpResponse|JsonResponse|JsonResource|RedirectResponse
116
    {
117
        $data = Category::query()
118
            ->wherePublished()
119
            ->orderByDesc('created_at')
120
            ->with(['slugable'])
121
            ->paginate($request->integer('per_page', 10) ?: 10);
122
123
        return $this
124
            ->httpResponse()
125
            ->setData(ListCategoryResource::collection($data))
126
            ->toApiResponse();
127
    }
128
129
    #[
130
        Get(
131
            path: "/categories/filters",
132
            operationId: "categoryGetWithFilter",
133
            description: "Get all categories with filters and pagination (10 items per page by default, page 1 by default)
134
            
135
    This API will get records from the database and return them as a paginated list. 
136
    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.
137
            ",
138
            summary: "Get category filters",
139
            tags: ['Category'],
140
            parameters: [
141
                new Parameter(
142
                    name: 'order_by',
143
                    description: 'Field to order by',
144
                    in: 'query',
145
                    required: false,
146
                    schema: new Schema(type: 'string', default: 'created_at')
147
                ),
148
                new Parameter(
149
                    name: 'order',
150
                    description: 'Order direction: 
151
                        ASC for ascending
152
                        DESC for descending',
153
                    in: 'query',
154
                    required: false,
155
                    schema: new Schema(type: 'string', default: 'ASC', enum: ['ASC', 'DESC'])
156
                ),
157
                new Parameter(
158
                    name: 'per_page',
159
                    description: 'Number of items per page',
160
                    in: 'query',
161
                    required: false,
162
                    schema: new Schema(type: 'integer', default: 10)
163
                ),
164
                new Parameter(
165
                    name: 'page',
166
                    description: 'Page number',
167
                    in: 'query',
168
                    required: false,
169
                    schema: new Schema(type: 'integer', default: 1)
170
                ),
171
            ],
172
            responses: [
173
              new Response(
174
                  response: 200,
175
                  description: "Get filters successfully",
176
                  content: new JsonContent(
177
                      properties: [
178
                            new Property(
179
                                property: 'error',
180
                                description: 'Error status',
181
                                type: 'boolean',
182
                                default: false
183
                            ),
184
                            new Property(
185
                                property: "data",
186
                                description: "Filter data",
187
                                type: "array",
188
                                items: new Items(ref: CategoryModelResourceSchema::class)
189
                            ),
190
                        ]
191
                  )
192
              ),
193
            ],
194
        )
195
    ]
196
    public function getFilters(Request $request, CategoryInterface $categoryRepository): BaseHttpResponse|JsonResponse|JsonResource|RedirectResponse
197
    {
198
        $filters = FilterCategory::setFilters($request->input());
199
        $data = $this->categoryService->getCustomFilters((array) $filters);
200
201
        return $this
202
            ->httpResponse()
203
            ->setData(CategoryResource::collection($data))
204
            ->toApiResponse();
205
    }
206
207
    /**
208
     *  Get category by slug
209
     *
210
     * @group Blog
211
     * @queryParam slug Find by slug of category.
212
     *
213
     * @param  string  $slug
214
     *
215
     * @return BaseHttpResponse|JsonResource|JsonResponse|RedirectResponse
216
     */
217
    #[
218
        Get(
219
            path: "/categories/{slug}",
220
            operationId: "categoryFilterBySlug",
221
            description: "Get the category by slug
222
            
223
    This API will get records from the database and return the category by slug.
224
            ",
225
            summary: "Get category by slug",
226
            tags: ["Category"],
227
            parameters: [
228
                new Parameter(
229
                    name: 'slug',
230
                    description: 'Category slug',
231
                    in: 'path',
232
                    required: true,
233
                    schema: new Schema(type: 'string', example: 'php')
234
                ),
235
            ],
236
            responses: [
237
                new Response(
238
                    response: 200,
239
                    description: "Get category successfully",
240
                    content: new JsonContent(
241
                        properties: [
242
                            new Property(
243
                                property: 'error',
244
                                description: 'Error status',
245
                                type: 'boolean',
246
                                default: false
247
                            ),
248
                            new Property(
249
                                property: "data",
250
                                ref: CategoryListResourceSchema::class,
251
                                description: "Data of model",
252
                                type: "object",
253
                            ),
254
                        ]
255
                    )
256
                ),
257
                new Response(
258
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\BadRequestResponseSchema::class,
259
                    response: 400,
260
                ),
261
                new Response(
262
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\ErrorNotFoundResponseSchema::class,
263
                    response: 404,
264
                ),
265
                new Response(
266
                    ref: \CSlant\Blog\Api\OpenApi\Responses\Errors\InternalServerResponseSchema::class,
267
                    response: 500,
268
                ),
269
            ]
270
        )
271
    ]
272
    public function findBySlug(string $slug): JsonResponse|RedirectResponse|JsonResource|BaseHttpResponse
273
    {
274
        /** @var Slug $slug */
275
        $slug = SlugHelper::getSlug($slug, SlugHelper::getPrefix(Category::getBaseModel()));
276
277
        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...
278
            return $this
279
                ->httpResponse()
280
                ->setError()
281
                ->setCode(404)
282
                ->setMessage('Not found');
283
        }
284
285
        $category = Category::query()
286
            ->with(['slugable'])
287
            ->where([
288
                'id' => $slug->reference_id,
289
                'status' => StatusEnum::PUBLISHED,
290
            ])
291
            ->first();
292
293
        if (!$category) {
294
            return $this
295
                ->httpResponse()
296
                ->setError()
297
                ->setCode(404)
298
                ->setMessage('Not found');
299
        }
300
301
        return $this
302
            ->httpResponse()
303
            ->setData(ListCategoryResource::make($category))
304
            ->toApiResponse();
305
    }
306
}
307