Passed
Push — master ( 60c6b0...f5065c )
by Petr
03:15
created

EventController::createAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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