Passed
Push — master ( 143906...fd728f )
by Petr
03:28 queued 11s
created

EventController   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 346
Duplicated Lines 9.54 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 11
dl 33
loc 346
ccs 82
cts 82
cp 1
rs 10
c 0
b 0
f 0

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

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
365 1
                $response = $eventService->editEventByForm($form, $eventId);
366
            } else {
367 2
                $response = $eventService->createEventByForm($form, $this->getUser());
368
            }
369
        } else {
370 2
            $response = new ApiError($this->getFormErrors($form), Response::HTTP_BAD_REQUEST);
371
        }
372
373 4
        return $response;
374
    }
375
}
376