Completed
Pull Request — master (#30)
by nonanerz
04:38
created

CalendarController::singleEventAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 16
rs 9.4285
c 2
b 0
f 0
cc 2
eloc 11
nc 2
nop 1
1
<?php
2
3
namespace AppBundle\Controller;
4
5
use AppBundle\Entity\DTO\DtoEvent;
6
use AppBundle\Entity\Event;
7
use AppBundle\Entity\User;
8
use AppBundle\Exception\JsonHttpException;
9
use AppBundle\Form\EventType;
10
use Mcfedr\JsonFormBundle\Controller\JsonController;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\Routing\Annotation\Route;
15
16
/**
17
 * @Route("/schedule/events")
18
 */
19
class CalendarController extends JsonController
20
{
21
    /**
22
     * @Route("/")
23
     * @Method("GET")
24
     *
25
     * @return JsonResponse
26
     */
27
    public function eventsListAction(Request $request)
28
    {
29
        $googleEvents = $this->get('app.google_calendar')
30
            ->getEventList($request->query->all());
31
        $events = [];
32
        foreach ($googleEvents['events'] as $event) {
33
            $events[] = new DtoEvent($event);
34
        }
35
36
        return $this->json(['pageToken' => $googleEvents['pageToken'], 'events' => $events]);
37
    }
38
39
    /**
40
     * @param Request $request
41
     * @Route("")
42
     * @Method("POST")
43
     *
44
     * @return JsonResponse
45
     */
46
    public function newEventAction(Request $request)
47
    {
48
        $data = json_decode($request->getContent(), true);
49
50 View Code Duplication
        if (!$data['event']['start'] || !$data['event']['end'] || !$data['event']['user']) {
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...
51
            throw new JsonHttpException(400, 'Bad request.');
52
        }
53
54
        $dtoEvent = new DtoEvent();
55
        $form = $this->createForm(EventType::class, $dtoEvent);
56
        $this->handleJsonForm($form, $request);
57
        $result = $this->get('app.google_calendar')
58
            ->createEvent($dtoEvent, $request->query->all());
59
        if (!$result) {
60
            throw new JsonHttpException(412, 'Event has not been created');
61
        }
62
        $em = $this->getDoctrine()->getManager();
63
        /** @var User $user */
64
        $user = $em->getRepository('AppBundle:User')
65
            ->find($dtoEvent->getUser());
66
67
        if (!$user) {
68
            throw new JsonHttpException(404, 'User not found.');
69
        }
70
        $event = new Event();
71
        $event->setGoogleId($result->id);
72
        $event->addUser($user);
73
        $user->setEvent($event);
74
75
        $em->persist($user);
76
        $em->flush();
77
78
        return $this->json(['success' => 'Event Created']);
79
    }
80
81
    /**
82
     * @param $id
83
     * @Route("/{id}")
84
     * @Method("GET")
85
     *
86
     * @return JsonResponse
87
     */
88
    public function singleEventAction($id)
89
    {
90
        /** @var Event $event */
91
        $event = $this->getDoctrine()->getRepository('AppBundle:Event')
92
            ->findByGoogleId($id);
93
        $user = $event->getUsers()->first();
0 ignored issues
show
Bug introduced by
The method first cannot be called on $event->getUsers() (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
94
        if (!$user) {
95
            throw new JsonHttpException(404, 'User not found.');
96
        }
97
        $googleEvent = $this->get('app.google_calendar')
98
            ->getEventById($id);
99
        $event = new DtoEvent($googleEvent);
100
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
101
102
        return new JsonResponse(['user' => $user, 'event' => $event]);
103
    }
104
105
    /**
106
     * @Route("/user/{id}")
107
     * @Method("GET")
108
     *
109
     * @return JsonResponse
110
     */
111
    public function userEventsAction($id)
112
    {
113
        $user = $this->getDoctrine()->getRepository('AppBundle:User')->find($id);
114
        $events = $user->getEvents();
115
        $calendar = $this->get('app.google_calendar');
116
        $googleEvents = [];
117
        foreach ($events as $event) {
118
            $googleEvents[] = $calendar
119
                ->getEventById($event->getGoogleId());
120
        }
121
        $events = [];
122
        foreach ($googleEvents as $event) {
123
            if ($event) {
124
                $events[] = new DtoEvent($event);
125
            }
126
        }
127
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
128
129
        return new JsonResponse(['user' => $user, 'events' => $events]);
130
    }
131
132
    /**
133
     * @param $id
134
     * @Route("/{id}")
135
     * @Method("DELETE")
136
     *
137
     * @return JsonResponse
138
     */
139
    public function removeEventAction($id)
140
    {
141
        $this->get('app.google_calendar')
142
            ->deleteEvent($id);
143
        $em = $this->getDoctrine()->getManager();
144
        /** @var Event $event */
145
        $event = $em->getRepository('AppBundle:Event')->findByGoogleId($id);
146
        $em->remove($event);
147
        $em->flush();
148
149
        return $this->json(['success' => 'Event was removed']);
150
    }
151
152
    /**
153
     * @param Request $request
154
     * @Method("PATCH")
155
     * @Route("/{id}")
156
     *
157
     * @return JsonResponse
158
     */
159
    public function editEventAction(Request $request, $id)
160
    {
161
        $data = json_decode($request->getContent(), true);
162
163 View Code Duplication
        if (!$data['event']['start'] || !$data['event']['end'] || !$data['event']['user']) {
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...
164
            throw new JsonHttpException(400, 'Bad request.');
165
        }
166
167
        $dtoEvent = new DtoEvent();
168
        $form = $this->createForm(EventType::class, $dtoEvent);
169
        $this->handleJsonForm($form, $request);
170
        $this->get('app.google_calendar')
171
            ->editEvent($dtoEvent, $id, $request->query->all());
172
173
        return $this->json(['success' => 'Event edited']);
174
    }
175
176
    /**
177
     * FOR DEV ONLY.
178
     *
179
     * @Method("PUT")
180
     * @Route("/clear")
181
     */
182
    public function clearAction()
183
    {
184
        $result = $this->get('app.google_calendar')->clear();
185
186
        return $this->json($result);
187
    }
188
}
189