Passed
Pull Request — main (#51)
by
unknown
02:34
created

PostController::index()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 81
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

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