Completed
Push — dev ( d41943...faf05c )
by
unknown
08:20 queued 05:32
created

CalendarController::newEventAction()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 42
Code Lines 28

Duplication

Lines 3
Ratio 7.14 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 3
loc 42
rs 5.3846
cc 8
eloc 28
nc 7
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("/", name="events-list", options={"expose"=true})
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("", name="new-event", options={"expose"=true})
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
64
        $users = [];
65
        foreach ($dtoEvent->getUser() as $user => $id) {
0 ignored issues
show
Bug introduced by
The expression $dtoEvent->getUser() of type object<AppBundle\Entity\User> is not traversable.
Loading history...
66
            $user = $em->getRepository('AppBundle:User')
67
                ->find($id);
68
            if (!$user) {
69
                throw new JsonHttpException(404, "User with id $id not found.");
70
            }
71
            $users[] = $user;
72
        }
73
74
        $event = new Event();
75
        $event->setGoogleId($result->id);
76
        foreach ($users as $user) {
77
            $event->addUser($user);
78
        }
79
        $event->setExpiredAt(new \DateTime($result->getEnd()->dateTime));
80
81
        $em->persist($event);
82
        $em->flush();
83
84
        $event = new DtoEvent($result);
85
86
        return $this->json(['event' => $event]);
87
    }
88
89
    /**
90
     * @param $id
91
     * @Route("/{id}", name="single-event", options={"expose"=true})
92
     * @Method("GET")
93
     *
94
     * @return JsonResponse
95
     */
96
    public function singleEventAction($id)
97
    {
98
        /** @var Event $event */
99
        $event = $this->getDoctrine()->getRepository('AppBundle:Event')
100
            ->findByGoogleId($id);
101
        $user = $event->getUser();
102
        if (!$user) {
103
            throw new JsonHttpException(404, 'User not found.');
104
        }
105
        $googleEvent = $this->get('app.google_calendar')
106
            ->getEventById($id);
107
        $event = new DtoEvent($googleEvent);
108
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
109
110
        return new JsonResponse(['user' => $user, 'event' => $event]);
111
    }
112
113
    /**
114
     * @Route("/user/{id}", name="user-events", options={"expose"=true})
115
     * @Method("GET")
116
     *
117
     * @return JsonResponse
118
     */
119
    public function userEventsAction($id)
120
    {
121
        $user = $this->getDoctrine()->getRepository('AppBundle:User')->find($id);
122
        $events = $this->getDoctrine()->getRepository(Event::class)
123
        ->selectNotExpiredByUser($user);
124
        $calendar = $this->get('app.google_calendar');
125
        $googleEvents = [];
126
        foreach ($events as $event) {
127
            $googleEvents[] = $calendar
128
                ->getEventById($event->getGoogleId());
129
        }
130
        $events = [];
131
        foreach ($googleEvents as $event) {
132
            if ($event) {
133
                $events[] = new DtoEvent($event);
134
            }
135
        }
136
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
137
138
        return new JsonResponse(['user' => $user, 'events' => $events]);
139
    }
140
141
    /**
142
     * @param $id
143
     * @Route("/{id}", name="remove-event", options={"expose"=true})
144
     * @Method("DELETE")
145
     *
146
     * @return JsonResponse
147
     */
148
    public function removeEventAction($id)
149
    {
150
        $this->get('app.google_calendar')
151
            ->deleteEvent($id);
152
        $em = $this->getDoctrine()->getManager();
153
        /** @var Event $event */
154
        $event = $em->getRepository('AppBundle:Event')->findByGoogleId($id);
155
        $em->remove($event);
156
        $em->flush();
157
158
        return $this->json(['success' => 'Event was removed']);
159
    }
160
161
    /**
162
     * @param Request $request
163
     * @Method("PATCH")
164
     * @Route("/{id}", name="edit-event", options={"expose"=true})
165
     *
166
     * @return JsonResponse
167
     */
168
    public function editEventAction(Request $request, $id)
169
    {
170
        $data = json_decode($request->getContent(), true);
171
172 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...
173
            throw new JsonHttpException(400, 'Bad request.');
174
        }
175
176
        $dtoEvent = new DtoEvent();
177
        $form = $this->createForm(EventType::class, $dtoEvent);
178
        $this->handleJsonForm($form, $request);
179
        $result = $this->get('app.google_calendar')
180
            ->editEvent($dtoEvent, $id, $request->query->all());
181
        $event = new DtoEvent($result);
182
183
        $em = $this->getDoctrine()->getManager();
184
        $user = $em->getRepository(User::class)->find($dtoEvent->getUser());
185
        /** @var Event $ev */
186
        $ev = $this->getDoctrine()->getRepository(Event::class)->findByGoogleId($id);
187
        $ev->setUser($user);
0 ignored issues
show
Bug introduced by
The method setUser() does not seem to exist on object<AppBundle\Entity\Event>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
188
        $em->flush();
189
190
        return $this->json(['event' => $event]);
191
    }
192
}
193