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

PostController::findBySlug()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 89
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

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