Passed
Push — master ( 63b45b...921011 )
by Petr
04:21
created

EventController::addLinksAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
crap 1
1
<?php
2
3
namespace AppBundle\Controller;
4
5
use AppBundle\Controller\Infrastructure\RestController;
6
use AppBundle\Entity\DTO\CreateEventDTO;
7
use AppBundle\Entity\Repository\EventRepository;
8
use AppBundle\Entity\Repository\ImageRepository;
9
use AppBundle\Form\Event\LinksCollectionType;
10
use AppBundle\Response\ApiError;
11
use AppBundle\Response\ApiValidationError;
12
use AppBundle\Response\CollectionApiResponse;
13
use AppBundle\Response\EmptyApiResponse;
14
use AppBundle\Response\Infrastructure\AbstractApiResponse;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
17
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
19
use Symfony\Component\Form\Extension\Core\Type\DateType;
20
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
21
use Symfony\Component\Form\Extension\Core\Type\TextType;
22
use Symfony\Component\Form\FormBuilder;
23
use Symfony\Component\Form\FormInterface;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\HttpFoundation\Response;
26
use AppBundle\Response\ApiResponse;
27
28
/**
29
 * @Route("event")
30
 * @author Vehsamrak
31
 */
32
class EventController extends RestController
33
{
34
35
    /**
36
     * Find events by name part
37
     * @Route("s/like/{searchString}/{limit}/{offset}", name="events_find_like")
38
     * @Method("GET")
39
     * @ApiDoc(
40
     *     section="Event",
41
     *     statusCodes={
42
     *         200="OK",
43
     *     }
44
     * )
45
     * @param string $searchString Search string
46
     * @param int $limit Limit results. Default is 50
47
     * @param int $offset Starting serial number of result collection. Default is 0
48
     */
49 4
    public function findLikeAction($searchString = null, $limit = null, $offset = null)
50
    {
51 4
        $eventRepository = $this->get('rockparade.event_repository');
52 4
        $events = $eventRepository->findLike($searchString);
53 4
        $total = $events->count();
54
55 4
        $limit = (int) filter_var($limit, FILTER_VALIDATE_INT);
56 4
        $offset = (int) filter_var($offset, FILTER_VALIDATE_INT);
57
58 4
        if ($limit || $offset) {
59 2
            $events = $events->slice($offset, $limit ?: null);
60
        }
61
62 4
        $response = new CollectionApiResponse(
63
            $events,
64 4
            Response::HTTP_OK,
65
            $total,
66
            $limit,
67
            $offset
68
        );
69
70 4
        return $this->respond($response);
71
    }
72
73
    /**
74
     * List all events
75
     * @Route("s/{limit}/{offset}", name="events_list")
76
     * @Method("GET")
77
     * @ApiDoc(
78
     *     section="Event",
79
     *     statusCodes={
80
     *         200="OK",
81
     *     }
82
     * )
83
     * @param int $limit Limit results. Default is 50
84
     * @param int $offset Starting serial number of result collection. Default is 0
85
     */
86 1
    public function listAction($limit = null, $offset = null): Response
87
    {
88 1
        return $this->respond(
89 1
            $this->createCollectionResponse(
90 1
                $this->get('rockparade.event_repository'),
91
                $limit,
92
                $offset
93
            )
94
        );
95
    }
96
97
    /**
98
     * View event by id
99
     * @Route("/{eventId}", name="event_view")
100
     * @Method("GET")
101
     * @ApiDoc(
102
     *     section="Event",
103
     *     statusCodes={
104
     *         200="Event was found",
105
     *         404="Event with given id was not found",
106
     *     }
107
     * )
108
     * @param string $eventId event id
109
     */
110 5 View Code Duplication
    public function viewAction(string $eventId): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
111
    {
112
        /** @var EventRepository $eventRepository */
113 5
        $eventRepository = $this->get('rockparade.event_repository');
114 5
        $event = $eventRepository->findOneById($eventId);
115
116 5
        if ($event) {
117 4
            $response = new ApiResponse($event, Response::HTTP_OK);
118
        } else {
119 1
            $eventService = $this->get('rockparade.event');
120 1
            $response = $eventService->createEventNotFoundErrorResult($eventId);
121
        }
122
123 5
        return $this->respond($response);
124
    }
125
126
    /**
127
     * Create new event
128
     * @Route("")
129
     * @Method("POST")
130
     * @Security("has_role('ROLE_USER')")
131
     * @ApiDoc(
132
     *     section="Event",
133
     *     requirements={
134
     *         {
135
     *             "name"="name",
136
     *             "dataType"="string",
137
     *             "requirement"="true",
138
     *             "description"="event name"
139
     *         },
140
     *         {
141
     *             "name"="date",
142
     *             "dataType"="date (dd-MM-yyyy HH:mm)",
143
     *             "requirement"="true",
144
     *             "description"="event date"
145
     *         },
146
     *         {
147
     *             "name"="description",
148
     *             "dataType"="text",
149
     *             "requirement"="true",
150
     *             "description"="event description"
151
     *         },
152
     *     },
153
     *     statusCodes={
154
     *         201="New event was created. Link to new resource in header 'Location'",
155
     *         400="Validation error",
156
     *     }
157
     * )
158
     */
159 2
    public function createAction(Request $request): Response
160
    {
161 2
        $response = $this->createOrUpdateEvent($request);
162
163 2
        return $this->respond($response);
164
    }
165
166
    /**
167
     * Edit event
168
     * @Route("/{eventId}", name="event_edit")
169
     * @Method("PUT")
170
     * @Security("has_role('ROLE_USER')")
171
     * @ApiDoc(
172
     *     section="Event",
173
     *     requirements={
174
     *         {
175
     *             "name"="name",
176
     *             "dataType"="string",
177
     *             "requirement"="true",
178
     *             "description"="event name"
179
     *         },
180
     *         {
181
     *             "name"="date",
182
     *             "dataType"="date (dd-MM-yyyy HH:mm)",
183
     *             "requirement"="true",
184
     *             "description"="event date"
185
     *         },
186
     *         {
187
     *             "name"="description",
188
     *             "dataType"="string",
189
     *             "requirement"="true",
190
     *             "description"="event description"
191
     *         },
192
     *     },
193
     *     statusCodes={
194
     *         204="Event was edited with new data",
195
     *         400="Validation error",
196
     *         404="Event with given id was not found",
197
     *     }
198
     * )
199
     * @param string $eventId event id
200
     */
201 2
    public function editAction(Request $request, string $eventId): Response
202
    {
203 2
        $response = $this->createOrUpdateEvent($request, $eventId);
204
205 2
        return $this->respond($response);
206
    }
207
208
    /**
209
     * Delete event
210
     * @Route("/{eventId}", name="event_delete")
211
     * @Method("DELETE")
212
     * @Security("has_role('ROLE_USER')")
213
     * @ApiDoc(
214
     *     section="Event",
215
     *     statusCodes={
216
     *         204="Event was deleted",
217
     *         404="Event with given id was not found",
218
     *     }
219
     * )
220
     * @param string $eventId event id
221
     */
222 1 View Code Duplication
    public function deleteEvent(string $eventId): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
223
    {
224
        /** @var EventRepository $eventRepository */
225 1
        $eventRepository = $this->get('rockparade.event_repository');
226 1
        $event = $eventRepository->findOneById($eventId);
227
228 1
        if ($event) {
229 1
            $eventRepository->remove($event);
230 1
            $eventRepository->flush();
231
232 1
            $response = new EmptyApiResponse(Response::HTTP_NO_CONTENT);
233
        } else {
234
            $eventService = $this->get('rockparade.event');
235
            $response = $eventService->createEventNotFoundErrorResult($eventId);
236
        }
237
238 1
        return $this->respond($response);
239
    }
240
241
    /**
242
     * Add image to event
243
     * @Route("/{eventId}/image", name="event_image_add")
244
     * @Method("POST")
245
     * @Security("has_role('ROLE_USER')")
246
     * @ApiDoc(
247
     *     section="Event",
248
     *     statusCodes={
249
     *         403="Only event creator can add images",
250
     *         404="Event with given id was not found",
251
     *     }
252
     * )
253
     * @param string $eventId event id
254
     */
255 4
    public function addImageAction(Request $request, string $eventId): Response
256
    {
257 4
        $eventService = $this->get('rockparade.event');
258 4
        $response = $eventService->addImageToEvent($eventId, $this->getUser(), $request->get('image'));
259
260 4
        return $this->respond($response);
261
    }
262
263
    /**
264
     * Get event image
265
     * @Route("/{eventId}/image/{imageName}", name="event_image_view")
266
     * @Method("GET")
267
     * @ApiDoc(
268
     *     section="Event",
269
     *     statusCodes={
270
     *         404="Event with given id was not found",
271
     *         404="Image with given name was not found",
272
     *     }
273
     * )
274
     * @param string $eventId event id
275
     * @param string $imageName image name
276
     */
277 1
    public function viewImageAction(string $eventId, string $imageName): Response
278
    {
279
        /** @var EventRepository $eventRepository */
280 1
        $eventRepository = $this->get('rockparade.event_repository');
281 1
        $event = $eventRepository->findOneById($eventId);
282
283 1
        if ($event) {
284 1
            $image = $event->getImageWithName($imageName);
285 1
            $apiResponseFactory = $this->get('rockparade.api_response_factory');
286
287 1
            if ($image) {
288 1
                $response = $apiResponseFactory->createResponse($image);
289
            } else {
290 1
                $response = $apiResponseFactory->createNotFoundResponse();
291
            }
292
        } else {
293
            $eventService = $this->get('rockparade.event');
294
            $response = $eventService->createEventNotFoundErrorResult($eventId);
295
        }
296
297 1
        return $this->respond($response);
298
    }
299
300
    /**
301
     * Delete event image
302
     * @Route("/{eventId}/image/{imageId}", name="event_image_delete")
303
     * @Method("DELETE")
304
     * @Security("has_role('ROLE_USER')")
305
     * @ApiDoc(
306
     *     section="Event",
307
     *     statusCodes={
308
     *         403="Only event creator can delete images",
309
     *         404="Event with given id was not found",
310
     *         404="Image with given id was not found",
311
     *     }
312
     * )
313
     * @param string $eventId event id
314
     * @param string $imageId image id
315
     */
316 2
    public function deleteImageAction(string $eventId, string $imageId)
317
    {
318
        /** @var EventRepository $eventRepository */
319 2
        $eventRepository = $this->get('rockparade.event_repository');
320
        /** @var ImageRepository $imageRepository */
321 2
        $imageRepository = $this->get('rockparade.image_repository');
322 2
        $event = $eventRepository->findOneById($eventId);
323
324 2
        if ($event) {
325 2
            if ($this->getUser()->getLogin() !== $event->getCreator()->getLogin()) {
326 1
                $response = new ApiError('Only event creator can delete images.', Response::HTTP_FORBIDDEN);
327
            } else {
328 1
                $image = $imageRepository->findOneById($imageId);
329
330 1
                if ($image) {
331 1
                    $event->removeImage($image);
332 1
                    $eventRepository->flush();
333 1
                    $response = new EmptyApiResponse(Response::HTTP_OK);
334
                } else {
335
                    $apiResponseFactory = $this->get('rockparade.api_response_factory');
336 2
                    $response = $apiResponseFactory->createNotFoundResponse();
337
                }
338
            }
339
        } else {
340
            $eventService = $this->get('rockparade.event');
341
            $response = $eventService->createEventNotFoundErrorResult($eventId);
342
        }
343
344 2
        return $this->respond($response);
345
    }
346
347
    /**
348
     * Add links to event
349
     * @Route("/{eventId}/links", name="event_links_add")
350
     * @Method("POST")
351
     * @Security("has_role('ROLE_USER')")
352
     * @ApiDoc(
353
     *     section="Event",
354
     *     requirements={
355
     *         {
356
     *             "name"="links",
357
     *             "dataType"="array",
358
     *             "requirement"="true",
359
     *             "description"="list of links"
360
     *         },
361
     *         {
362
     *             "name"="links[0][url]",
363
     *             "dataType"="string",
364
     *             "requirement"="true",
365
     *             "description"="link url"
366
     *         },
367
     *         {
368
     *             "name"="links[0][description]",
369
     *             "dataType"="string",
370
     *             "requirement"="false",
371
     *             "description"="link description"
372
     *         },
373
     *     },
374
     *     statusCodes={
375
     *         403="Only event creator can add links",
376
     *         404="Event with given id was not found",
377
     *     }
378
     * )
379
     * @param string $eventId event id
380
     */
381 3
    public function addLinksAction(Request $request, string $eventId): Response
382
    {
383 3
        $eventService = $this->get('rockparade.event');
384
385 3
        $form = $this->createForm(LinksCollectionType::class);
386 3
        $this->processForm($request, $form);
387
388 3
        $response = $eventService->addLinksToEvent($eventId, $this->getUser(), $form);
389
390 3
        return $this->respond($response);
391
    }
392
393 4
    private function createEventCreationForm(): FormInterface
394
    {
395
        /** @var FormBuilder $formBuilder */
396 4
        $formBuilder = $this->createFormBuilder(new CreateEventDTO());
397 4
        $formBuilder->add('name', TextType::class);
398 4
        $formBuilder->add(
399 4
            'date',
400 4
            DateType::class,
401
            [
402 4
                'widget' => 'single_text',
403
                'format' => 'yyyy-MM-dd HH:mm',
404
            ]
405
        );
406 4
        $formBuilder->add('description', TextareaType::class);
407
408 4
        return $formBuilder->getForm();
409
    }
410
411 4
    private function createOrUpdateEvent(Request $request, string $eventId = null): AbstractApiResponse
412
    {
413 4
        $form = $this->createEventCreationForm();
414 4
        $this->processForm($request, $form);
415
416 4
        if ($form->isValid()) {
417 2
            $eventService = $this->get('rockparade.event');
418 2
            $eventId = (string) $eventId;
419
420 2
            if ($eventId) {
421 1
                $response = $eventService->editEventByForm($form, $eventId);
422
            } else {
423 2
                $response = $eventService->createEventByForm($form, $this->getUser());
424
            }
425
        } else {
426 2
            $response = new ApiValidationError($form);
427
        }
428
429 4
        return $response;
430
    }
431
}
432