Issues (62)

src/Controller/Api/CollectionController.php (2 issues)

Severity
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Command\CreateCollectionCommand;
6
use App\Command\DeleteCollectionCommand;
7
use App\Command\UpdateCollectionCommand;
8
use App\Error\ApiError;
9
use App\Repository\Exception\CollectionNotFoundException;
10
use App\Repository\CollectionRepository;
11
use App\Request\CreateCollectionRequest;
12
use App\Request\UpdateCollectionRequest;
13
use App\Traits\JsonErrorResponse;
14
use Psr\Log\LoggerInterface;
15
use Ramsey\Uuid\Uuid;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
17
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\Messenger\MessageBusInterface;
21
use Symfony\Component\Routing\Annotation\Route;
22
use Symfony\Component\Validator\ConstraintViolationListInterface;
23
use Swagger\Annotations as SWG;
24
use App\CommandHandler\Exception\CollectionNotDeletedException;
25
26
class CollectionController extends AbstractController
27
{
28
    use JsonErrorResponse;
29
30
    /**
31
     * @var MessageBusInterface
32
     */
33
    private $commandBus;
34
    /**
35
     * @var LoggerInterface
36
     */
37
    private $logger;
38
    /**
39
     * @var CollectionRepository
40
     */
41
    private $repository;
42
43
    /**
44
     * @param MessageBusInterface $commandBus
45
     * @param LoggerInterface $logger
46
     * @param CollectionRepository $repository
47
     */
48
    public function __construct(
49
        MessageBusInterface $commandBus,
50
        LoggerInterface $logger,
51
        CollectionRepository $repository
52
    )
53
    {
54
        $this->commandBus = $commandBus;
55
        $this->logger = $logger;
56
        $this->repository = $repository;
57
    }
58
59
    /**
60
     * @Route("/api/collections", name="collection_create", methods={"POST"})
61
     *
62
     * @ParamConverter("request", converter="fos_rest.request_body")
63
     * 
64
     * @SWG\Tag(name="Collections")
65
     * @SWG\Post(
66
     *     @SWG\Parameter(
67
     *          name="body",
68
     *          in="body",
69
     *          required=true,
70
     *          format="application/json",
71
     *          @SWG\Schema(
72
     *              required={"name"},
73
     *              @SWG\Property(property="name", type="string", maxLength=255),
74
     *              @SWG\Property(property="description", type="string"),
75
     *          )
76
     *     )
77
     * )
78
     * @SWG\Response(
79
     *     response=201,
80
     *     description="Returns ID of created Collection",
81
     *     @SWG\Schema(
82
     *          @SWG\Property(property="id", type="string", format="UUID")
83
     *     )
84
     * )
85
     * @SWG\Response(
86
     *     response=422,
87
     *     description="Collection was not created"
88
     * )
89
     * 
90
     * @param CreateCollectionRequest $request
91
     * @param ConstraintViolationListInterface $validationErrors
92
     * @return JsonResponse
93
     */
94
    public function create(CreateCollectionRequest $request, ConstraintViolationListInterface $validationErrors): JsonResponse
95
    {
96
        if ($validationErrors->count()) {
97
            $response = $this->jsonError(ApiError::ENTITY_VALIDATION_ERROR,
0 ignored issues
show
The assignment to $response is dead and can be removed.
Loading history...
98
                'Validations errors for create Collection',
99
                Response::HTTP_BAD_REQUEST,
100
                $this->parseFormErrors($validationErrors)
101
            );
102
        }
103
104
        try {
105
            $id = Uuid::uuid4();
106
            $command = new CreateCollectionCommand(
107
                $id,
108
                $request->getName(),
109
                $request->getDescription()
110
            );
111
            $this->commandBus->dispatch($command);
112
            $response = $this->json(['id' => $id], Response::HTTP_CREATED);
113
        } catch (\Exception $e) {
114
            $this->logger->critical($e->getMessage());
115
            return $this->jsonError(ApiError::ENTITY_CREATE_ERROR,
116
                $e->getMessage(),
117
                Response::HTTP_UNPROCESSABLE_ENTITY
118
            );
119
        }
120
121
        return $response;
122
    }
123
124
    /**
125
     * @Route("/api/collections/{id}", name="collection_get", methods={"GET"})
126
     *
127
     * @SWG\Tag(name="Collections")
128
     * @SWG\Get(
129
     *     @SWG\Parameter(name="id", in="path", type="string", format="UUID"),
130
     *     @SWG\Response(
131
     *          response="200", 
132
     *          description="Collection details",
133
     *          @SWG\Schema(
134
     *              @SWG\Property(property="id", type="string") ,
135
     *              @SWG\Property(property="name", type="string"),
136
     *              @SWG\Property(property="description", type="string")
137
     *         )
138
     *     ),
139
     *     @SWG\Response(response="404", description="Collection not found"),
140
     *     @SWG\Response(response="422", description="Validation failed")
141
     * )
142
     * 
143
     * @param string $id
144
     * @return JsonResponse
145
     */
146
    public function getCollectionAction(string $id): JsonResponse
147
    {
148
        try {
149
            $uuid = Uuid::fromString($id);
150
            $response = $this->json($this->repository->getCollection($uuid));
151
        } catch (\Ramsey\Uuid\Exception\InvalidUuidStringException $e) {
152
            return $this->jsonError(ApiError::ENTITY_UUID_ERROR,
153
                $e->getMessage(),
154
                Response::HTTP_UNPROCESSABLE_ENTITY
155
            );
156
        } catch (CollectionNotFoundException $e) {
157
            return $this->jsonError(ApiError::ENTITY_READ_ERROR,
158
                $e->getMessage(),
159
                Response::HTTP_NOT_FOUND
160
            );
161
        } catch (\Exception $e) {
162
            $this->logger->critical($e->getMessage());
163
            return $this->jsonError(ApiError::ENTITY_READ_ERROR,
164
                'Unknown Collection',
165
                Response::HTTP_NOT_FOUND
166
                );
167
        }
168
169
        return $response;
170
    }
171
172
    /**
173
     * @Route("/api/collections", name="collection_update", methods={"PATCH"})
174
     *
175
     * @ParamConverter("request", converter="fos_rest.request_body")
176
     * 
177
     * @SWG\Tag(name="Collections")
178
     * @SWG\Patch(
179
     *     @SWG\Parameter(
180
     *          name="body",
181
     *          in="body",
182
     *          required=true,
183
     *          format="application/json",
184
     *          @SWG\Schema(
185
     *              required={"id", "name"},
186
     *              @SWG\Property(property="id", type="string", maxLength=255),
187
     *              @SWG\Property(property="name", type="string", maxLength=255),
188
     *              @SWG\Property(property="description", type="string"),
189
     *          )
190
     *     )
191
     * )
192
     * @SWG\Response(
193
     *     response=200,
194
     *     description="Collection has been updated",
195
     *     @SWG\Schema(
196
     *              @SWG\Property(property="id", type="string", maxLength=255),
197
     *              @SWG\Property(property="name", type="string", maxLength=255),
198
     *              @SWG\Property(property="description", type="string"),
199
     *     )
200
     * )
201
     * @SWG\Response(
202
     *     response=422,
203
     *     description="Collection was not updated"
204
     * )
205
     * 
206
     * @param UpdateCollectionRequest $request
207
     * @param ConstraintViolationListInterface $validationErrors
208
     * @return JsonResponse
209
     */
210
    public function update(UpdateCollectionRequest $request, ConstraintViolationListInterface $validationErrors): JsonResponse
211
    {
212
        if ($validationErrors->count()) {
213
            $response = $this->jsonError(ApiError::ENTITY_VALIDATION_ERROR,
0 ignored issues
show
The assignment to $response is dead and can be removed.
Loading history...
214
                'Validations errors for update Collection',
215
                Response::HTTP_BAD_REQUEST,
216
                $this->parseFormErrors($validationErrors)
217
            );
218
        }
219
220
        try {
221
            $command = new UpdateCollectionCommand(
222
                $request->getId(),
223
                $request->getName(),
224
                $request->getDescription()
225
            );
226
            $this->commandBus->dispatch($command);
227
            $collection = $this->repository->getCollection($command->getId());
228
            $response = $this->json($collection, Response::HTTP_OK);
229
        } catch (\Exception $e) {
230
            $this->logger->critical($e->getMessage());
231
            return $this->jsonError(ApiError::ENTITY_CREATE_ERROR,
232
                $e->getMessage(),
233
                Response::HTTP_UNPROCESSABLE_ENTITY
234
            );
235
        }
236
237
        return $response;
238
    }
239
240
    /**
241
     * Delete Collection
242
     *
243
     * @SWG\Tag(name="Collections")
244
     * @SWG\Response(
245
     *     response="204",
246
     *     description="Collection was deleted"
247
     * )
248
     * @SWG\Response(
249
     *     response="404",
250
     *     description="Collection not found",
251
     * )
252
     *
253
     * @SWG\Response(
254
     *     response="422",
255
     *     description="Collection was not removed",
256
     * )
257
     *
258
     * @Route("/api/collections/{id}", name="collection_delete", methods={"DELETE"})
259
     * @param string $id
260
     * @return JsonResponse
261
     */
262
    public function delete(string $id): JsonResponse
263
    {
264
        try {
265
            $uuid = Uuid::fromString($id);
266
            $command = new DeleteCollectionCommand($uuid);
267
            $this->commandBus->dispatch($command);
268
            $response = $this->json(null, Response::HTTP_NO_CONTENT);
269
        } catch (\Ramsey\Uuid\Exception\InvalidUuidStringException $e) {
270
            $response = $this->jsonError(ApiError::ENTITY_UUID_ERROR,
271
                $e->getMessage(),
272
                Response::HTTP_UNPROCESSABLE_ENTITY
273
                );
274
        } catch (CollectionNotFoundException $e) {
275
            $response = $this->jsonError(ApiError::ENTITY_READ_ERROR,
276
                $e->getMessage(),
277
                Response::HTTP_NOT_FOUND
278
                );
279
        } catch (CollectionNotDeletedException $e) {
280
            $response = $this->jsonError(ApiError::ENTITY_DELETE_ERROR,
281
                $e->getMessage(),
282
                Response::HTTP_BAD_REQUEST
283
                );
284
        }
285
        
286
        return $response;
287
    }
288
}
289