Passed
Push — master ( 921011...5d9034 )
by Petr
04:49
created

EventController   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 425
Duplicated Lines 7.76 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 12
dl 33
loc 425
ccs 95
cts 95
cp 1
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
B findLikeAction() 0 23 4
A listAction() 0 10 1
A viewAction() 15 15 2
A createAction() 0 6 1
A editAction() 0 6 1
A deleteEvent() 18 18 2
A addImageAction() 0 7 1
A viewImageAction() 0 22 3
B deleteImageAction() 0 30 4
A addLinksAction() 0 11 1
A deleteLinkAction() 0 7 1
A createEventCreationForm() 0 17 1
A createOrUpdateEvent() 0 20 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 6 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 6
        $eventRepository = $this->get('rockparade.event_repository');
114 6
        $event = $eventRepository->findOneById($eventId);
115
116 6
        if ($event) {
117 5
            $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 6
        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
     *         400="Links must have unique url",
376
     *         403="Only event creator can add links",
377
     *         404="Event with given id was not found",
378
     *     }
379
     * )
380
     * @param string $eventId event id
381
     */
382 3
    public function addLinksAction(Request $request, string $eventId): Response
383
    {
384 3
        $eventService = $this->get('rockparade.event');
385
386 3
        $form = $this->createForm(LinksCollectionType::class);
387 3
        $this->processForm($request, $form);
388
389 3
        $response = $eventService->addLinksToEvent($eventId, $this->getUser(), $form);
390
391 3
        return $this->respond($response);
392
    }
393
394
    /**
395
     * Delete link from event
396
     * @Route("/{eventId}/link/{linkId}", name="event_link_delete")
397
     * @Method("DELETE")
398
     * @Security("has_role('ROLE_USER')")
399
     * @ApiDoc(
400
     *     section="Event",
401
     *     statusCodes={
402
     *         403="Only event creator can delete links",
403
     *         404="Event with given id was not found",
404
     *         404="Link with given id was not found",
405
     *     }
406
     * )
407
     * @param string $eventId event id
408
     * @param string $linkId link id
409
     */
410 2
    public function deleteLinkAction(string $eventId, string $linkId)
411
    {
412 2
        $eventService = $this->get('rockparade.event');
413 2
        $response = $eventService->removeLinksFromEvent($eventId, $linkId, $this->getUser());
414
415 2
        return $this->respond($response);
416
    }
417
418 4
    private function createEventCreationForm(): FormInterface
419
    {
420
        /** @var FormBuilder $formBuilder */
421 4
        $formBuilder = $this->createFormBuilder(new CreateEventDTO());
422 4
        $formBuilder->add('name', TextType::class);
423 4
        $formBuilder->add(
424 4
            'date',
425 4
            DateType::class,
426
            [
427 4
                'widget' => 'single_text',
428
                'format' => 'yyyy-MM-dd HH:mm',
429
            ]
430
        );
431 4
        $formBuilder->add('description', TextareaType::class);
432
433 4
        return $formBuilder->getForm();
434
    }
435
436 4
    private function createOrUpdateEvent(Request $request, string $eventId = null): AbstractApiResponse
437
    {
438 4
        $form = $this->createEventCreationForm();
439 4
        $this->processForm($request, $form);
440
441 4
        if ($form->isValid()) {
442 2
            $eventService = $this->get('rockparade.event');
443 2
            $eventId = (string) $eventId;
444
445 2
            if ($eventId) {
446 1
                $response = $eventService->editEventByForm($form, $eventId);
447
            } else {
448 2
                $response = $eventService->createEventByForm($form, $this->getUser());
449
            }
450
        } else {
451 2
            $response = new ApiValidationError($form);
452
        }
453
454 4
        return $response;
455
    }
456
}
457