EventController::deleteImageAction()   B
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 19

Duplication

Lines 7
Ratio 24.14 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 7
loc 29
ccs 11
cts 11
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 19
nc 4
nop 2
crap 4
1
<?php
2
3
namespace AppBundle\Controller;
4
5
use AppBundle\Controller\Infrastructure\RestController;
6
use AppBundle\Entity\Event;
7
use AppBundle\Entity\Image;
8
use AppBundle\Entity\Repository\EventRepository;
9
use AppBundle\Entity\Repository\ImageRepository;
10
use AppBundle\Form\Event\EventFormType;
11
use AppBundle\Form\Event\LinksCollectionFormType;
12
use AppBundle\Response\ApiError;
13
use AppBundle\Response\ApiValidationError;
14
use AppBundle\Response\CollectionApiResponse;
15
use AppBundle\Response\EmptyApiResponse;
16
use AppBundle\Response\Infrastructure\AbstractApiResponse;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
19
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
24
/**
25
 * @author Vehsamrak
26
 * @Route("event")
27
 */
28
class EventController extends RestController
29
{
30
31
    /**
32
     * Find events by name part
33
     * @Route("s/like/{searchString}/{limit}/{offset}", name="events_find_like")
34
     * @Method("GET")
35
     * @ApiDoc(
36
     *     section="Event",
37
     *     statusCodes={
38
     *         200="OK",
39
     *     }
40
     * )
41
     * @param string $searchString Search string
42
     * @param int $limit Limit results. Default is 50
43
     * @param int $offset Starting serial number of result collection. Default is 0
44
     */
45
    public function findLikeAction($searchString = null, $limit = 50, $offset = null)
46
    {
47
        $eventRepository = $this->get('rockparade.event_repository');
48
        $events = $eventRepository->findLike($searchString);
49
        $total = $events->count();
50 4
51
        $limit = (int) filter_var($limit, FILTER_VALIDATE_INT);
52 4
        $offset = (int) filter_var($offset, FILTER_VALIDATE_INT);
53 4
54 4
        $events = $events->slice($offset, $limit ?: null);
55
56 4
        $response = new CollectionApiResponse(
57 4
            $events,
58
            Response::HTTP_OK,
59 4
            $total,
60
            $limit,
61 4
            $offset
62
        );
63 4
64
        return $this->respond($response);
65
    }
66
67
    /**
68
     * List all events
69 4
     * @Route("s/{limit}/{offset}", name="events_list")
70
     * @Method("GET")
71
     * @ApiDoc(
72
     *     section="Event",
73
     *     statusCodes={
74
     *         200="OK",
75
     *     }
76
     * )
77
     * @param int $limit Limit results. Default is 50
78
     * @param int $offset Starting serial number of result collection. Default is 0
79
     */
80
    public function listAction($limit = null, $offset = null): Response
81
    {
82
        return $this->listEntities($this->get('rockparade.event_repository'), $limit, $offset);
83
    }
84
85 1
    /**
86
     * View event by id
87 1
     * @Route("/{id}", name="event_view")
88
     * @Method("GET")
89
     * @ApiDoc(
90
     *     section="Event",
91
     *     statusCodes={
92
     *         200="Event was found",
93
     *         404="Event with given id was not found",
94
     *     }
95
     * )
96
     * @param string $id event id
97
     */
98
    public function viewAction(string $id): Response
99
    {
100
        return $this->viewEntity($this->get('rockparade.event_repository'), $id);
101
    }
102
103 6
    /**
104
     * Create new event
105 6
     * @Route("")
106
     * @Method("POST")
107
     * @Security("has_role('ROLE_USER')")
108
     * @ApiDoc(
109
     *     section="Event",
110
     *     requirements={
111
     *         {
112
     *             "name"="name",
113
     *             "dataType"="string",
114
     *             "requirement"="true",
115
     *             "description"="event name"
116
     *         },
117
     *         {
118
     *             "name"="date",
119
     *             "dataType"="date (dd-MM-yyyy HH:mm)",
120
     *             "requirement"="true",
121
     *             "description"="event date"
122
     *         },
123
     *         {
124
     *             "name"="description",
125
     *             "dataType"="text",
126
     *             "requirement"="true",
127
     *             "description"="event description"
128
     *         },
129
     *         {
130
     *             "name"="place",
131
     *             "dataType"="text",
132
     *             "requirement"="true",
133
     *             "description"="event place"
134
     *         },
135
     *     },
136
     *     statusCodes={
137
     *         201="New event was created. Link to new resource in header 'Location'",
138
     *         400="Validation error",
139
     *         401="Authentication required",
140
     *     }
141
     * )
142 2
     */
143
    public function createAction(Request $request): Response
144 2
    {
145
        $response = $this->createOrUpdateEvent($request);
146 2
147
        return $this->respond($response);
148
    }
149
150
    /**
151
     * Edit event
152
     * @Route("/{id}", name="event_edit")
153
     * @Method("PUT")
154
     * @Security("has_role('ROLE_USER')")
155
     * @ApiDoc(
156
     *     section="Event",
157
     *     requirements={
158
     *         {
159
     *             "name"="name",
160
     *             "dataType"="string",
161
     *             "requirement"="true",
162
     *             "description"="event name"
163
     *         },
164
     *         {
165
     *             "name"="date",
166
     *             "dataType"="date (dd-MM-yyyy HH:mm)",
167
     *             "requirement"="true",
168
     *             "description"="event date"
169
     *         },
170
     *         {
171
     *             "name"="description",
172
     *             "dataType"="string",
173
     *             "requirement"="true",
174
     *             "description"="event description"
175
     *         },
176
     *         {
177
     *             "name"="place",
178
     *             "dataType"="text",
179
     *             "requirement"="true",
180
     *             "description"="event place"
181
     *         },
182
     *     },
183
     *     statusCodes={
184
     *         204="Event was edited with new data",
185 2
     *         400="Validation error",
186
     *         401="Authentication required",
187 2
     *         404="Event with given id was not found",
188
     *     }
189 2
     * )
190
     * @param string $id event id
191
     */
192
    public function editAction(Request $request, string $id): Response
193
    {
194
        $response = $this->createOrUpdateEvent($request, $id);
195
196
        return $this->respond($response);
197
    }
198
199
    /**
200
     * Delete event
201
     * @Route("/{id}", name="event_delete")
202
     * @Method("DELETE")
203
     * @Security("has_role('ROLE_USER')")
204
     * @ApiDoc(
205
     *     section="Event",
206
     *     statusCodes={
207
     *         204="Event was deleted",
208 1
     *         401="Authentication required",
209
     *         403="Only event creator can delete event",
210
     *         404="Event with given id was not found",
211 1
     *     }
212
     * )
213 1
     * @param string $id event id
214
     */
215 1
    public function deleteEvent(string $id): Response
216 1
    {
217 1
        /** @var EventRepository $eventRepository */
218 1
        $eventRepository = $this->get('rockparade.event_repository');
219
        /** @var Event $event */
220 1
        $event = $eventRepository->findOneById($id);
221
222 1
        if ($event) {
223
            if ($event->getCreator() === $this->getUser()) {
224
                $eventRepository->remove($event);
225
                $eventRepository->flush();
226
227
                $response = new EmptyApiResponse(Response::HTTP_NO_CONTENT);
228
            } else {
229 1
                $response = new ApiError('Only event creator can delete event.', Response::HTTP_FORBIDDEN);
230
            }
231
        } else {
232
            $eventService = $this->get('rockparade.event');
233
            $response = $eventService->createEventNotFoundErrorResult($id);
234
        }
235
236
        return $this->respond($response);
237
    }
238
239
    /**
240
     * Add image to event
241
     * @Route("/{id}/image", name="event_image_add")
242
     * @Method("POST")
243
     * @Security("has_role('ROLE_USER')")
244
     * @ApiDoc(
245
     *     section="Event",
246
     *     statusCodes={
247
     *         200="OK",
248 4
     *         401="Authentication required",
249
     *         403="Only event creator can add images",
250 4
     *         404="Event with given id was not found",
251 4
     *     }
252
     * )
253 4
     * @param string $id event id
254
     */
255
    public function addImageAction(Request $request, string $id): Response
256
    {
257
        $eventService = $this->get('rockparade.event');
258
        $response = $eventService->addImageToEvent($id, $this->getUser(), $request->get('image'));
259
260
        return $this->respond($response);
261
    }
262
263
    /**
264
     * Get event image
265
     * @Route("/{id}/image/{imageName}", name="event_image_view")
266
     * @Method("GET")
267
     * @ApiDoc(
268
     *     section="Event",
269
     *     statusCodes={
270
     *         200="OK",
271 1
     *         404="Event with given id was not found",
272
     *         404="Image with given name was not found",
273
     *     }
274 1
     * )
275 1
     * @param string $id event id
276 1
     * @param string $imageName image name
277
     */
278 1
    public function viewImageAction(string $id, string $imageName): Response
279 1
    {
280 1
        /** @var EventRepository $eventRepository */
281
        $eventRepository = $this->get('rockparade.event_repository');
282 1
        $event = $eventRepository->findOneById($id);
283 1
        $entityService = $this->get('rockparade.entity_service');
284
285 1
        if ($event) {
286
            $image = $event->getImageWithName($imageName);
287
            $apiResponseFactory = $this->get('rockparade.api_response_factory');
288
289
            if ($image) {
290
                $response = $apiResponseFactory->createImageResponse($image);
291 1
            } else {
292
                $response = $entityService->createEntityNotFoundResponse(Image::class, $imageName);
293
            }
294
        } else {
295
            $response = $entityService->createEntityNotFoundResponse(Event::class, $id);
296
        }
297
298
        return $this->respond($response);
299
    }
300
301
    /**
302
     * Delete event image
303
     * @Route("/{id}/image/{imageId}", name="event_image_delete")
304
     * @Method("DELETE")
305
     * @Security("has_role('ROLE_USER')")
306
     * @ApiDoc(
307
     *     section="Event",
308
     *     statusCodes={
309
     *         200="OK",
310
     *         401="Authentication required",
311
     *         403="Only event creator can delete images",
312 2
     *         404="Event with given id was not found",
313
     *         404="Image with given id was not found",
314
     *     }
315 2
     * )
316
     * @param string $id event id
317 2
     * @param string $imageId image id
318 2
     */
319 2
    public function deleteImageAction(string $id, string $imageId)
320
    {
321 2
        /** @var EventRepository $eventRepository */
322 2
        $eventRepository = $this->get('rockparade.event_repository');
323 1
        /** @var ImageRepository $imageRepository */
324
        $imageRepository = $this->get('rockparade.image_repository');
325 1
        $event = $eventRepository->findOneById($id);
326
        $entityService = $this->get('rockparade.entity_service');
327 1
328 1
        if ($event) {
329 1
            if ($this->getUser()->getLogin() !== $event->getCreator()->getLogin()) {
330 1
                $response = new ApiError('Only event creator can delete images.', Response::HTTP_FORBIDDEN);
331
            } else {
332 2
                $image = $imageRepository->findOneById($imageId);
333
334 View Code Duplication
                if ($image) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
335
                    $event->removeImage($image);
336
                    $eventRepository->flush();
337
                    $response = new EmptyApiResponse(Response::HTTP_OK);
338
                } else {
339 2
                    $response = $entityService->createEntityNotFoundResponse(Image::class, $imageId);
340
                }
341
            }
342
        } else {
343
            $response = $entityService->createEntityNotFoundResponse(Event::class, $id);
344
        }
345
346
        return $this->respond($response);
347
    }
348
349
    /**
350
     * Add links to event
351
     * @Route("/{id}/links", name="event_links_add")
352
     * @Method("POST")
353
     * @Security("has_role('ROLE_USER')")
354
     * @ApiDoc(
355
     *     section="Event",
356
     *     requirements={
357
     *         {
358
     *             "name"="links",
359
     *             "dataType"="array",
360
     *             "requirement"="true",
361
     *             "description"="list of links"
362
     *         },
363
     *         {
364
     *             "name"="links[0][url]",
365
     *             "dataType"="string",
366
     *             "requirement"="true",
367
     *             "description"="link url"
368
     *         },
369
     *         {
370
     *             "name"="links[0][description]",
371
     *             "dataType"="string",
372
     *             "requirement"="false",
373
     *             "description"="link description"
374
     *         },
375
     *     },
376
     *     statusCodes={
377
     *         201="Link created and added to event",
378
     *         400="Links must have unique url",
379 3
     *         401="Authentication required",
380
     *         403="Only event creator can add links",
381 3
     *         404="Event with given id was not found",
382
     *     }
383 3
     * )
384 3
     * @param string $id event id
385
     */
386 3
    public function addLinksAction(Request $request, string $id): Response
387
    {
388 3
        $eventService = $this->get('rockparade.event');
389
390
        $form = $this->createForm(LinksCollectionFormType::class);
391
        $this->processForm($request, $form);
392
393
        $response = $eventService->addLinksToEvent($id, $this->getUser(), $form);
394
395
        return $this->respond($response);
396
    }
397
398
    /**
399
     * Delete link from event
400
     * @Route("/{id}/link/{linkId}", name="event_link_delete")
401
     * @Method("DELETE")
402
     * @Security("has_role('ROLE_USER')")
403
     * @ApiDoc(
404
     *     section="Event",
405
     *     statusCodes={
406
     *         200="OK",
407
     *         401="Authentication required",
408
     *         403="Only event creator can delete links",
409 2
     *         404="Event with given id was not found",
410
     *         404="Link with given id was not found",
411 2
     *     }
412 2
     * )
413
     * @param string $id event id
414 2
     * @param string $linkId link id
415
     */
416
    public function deleteLinkAction(string $id, string $linkId)
417 4
    {
418
        $eventService = $this->get('rockparade.event');
419
        $response = $eventService->removeLinksFromEvent($id, $linkId, $this->getUser());
420 4
421 4
        return $this->respond($response);
422 4
    }
423 4
424 4
    private function createOrUpdateEvent(Request $request, string $id = null): AbstractApiResponse
425
    {
426 4
        $form = $this->createForm(EventFormType::class);
427
        $this->processForm($request, $form);
428
429
        if ($form->isValid()) {
430 4
            $eventService = $this->get('rockparade.event');
431
            $id = (string) $id;
432 4
433
            if ($id) {
434
                $response = $eventService->editEventByForm($form, $id);
435 4
            } else {
436
                $response = $eventService->createEventByForm($form, $this->getUser());
437 4
            }
438 4
        } else {
439
            $response = new ApiValidationError($form);
440 4
        }
441 2
442 2
        return $response;
443
    }
444
}
445