Completed
Pull Request — dev (#53)
by nonanerz
03:33
created

CalendarController::eventsListAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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