Completed
Pull Request — master (#30)
by
unknown
03:46
created

CalendarController::userEventsAction()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 25
rs 8.439
cc 5
eloc 16
nc 8
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
        return $this->json(['pageToken'=> $googleEvents['pageToken'], 'events' => $events]);
36
    }
37
38
    /**
39
     * @param Request $request
40
     * @Route("")
41
     * @Method("POST")
42
     *
43
     * @return JsonResponse
44
     */
45
    public function newEventAction(Request $request)
46
    {
47
        $data = json_decode($request->getContent(), true);
48
49 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...
50
            throw new JsonHttpException(400, 'Bad request.');
51
        }
52
53
        $dtoEvent = new DtoEvent();
54
        $form = $this->createForm(EventType::class, $dtoEvent);
55
        $this->handleJsonForm($form, $request);
56
        $result = $this->get('app.google_calendar')
57
            ->createEvent($dtoEvent, $request->query->all());
58
        if (!$result) {
59
            throw new JsonHttpException(412, 'Event has not been created');
60
        }
61
        $em = $this->getDoctrine()->getManager();
62
        /** @var User $user */
63
        $user = $em->getRepository('AppBundle:User')
64
            ->find($dtoEvent->getUser());
65
66
        if (!$user) {
67
            throw new JsonHttpException(404, 'User not found.');
68
        }
69
        $event = new Event();
70
        $event->setGoogleId($result->id);
71
        $event->addUser($user);
72
        $user->setEvent($event);
73
74
        $em->persist($user);
75
        $em->flush();
76
77
        return $this->json(['success' => 'Event Created']);
78
    }
79
80
    /**
81
     * @param $id
82
     * @Route("/{id}")
83
     * @Method("GET")
84
     *
85
     * @return JsonResponse
86
     */
87
    public function singleEventAction($id)
88
    {
89
        /** @var Event $event */
90
        $event = $this->getDoctrine()->getRepository('AppBundle:Event')
91
            ->findByGoogleId($id);
92
        $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...
93
        if (!$user) {
94
            throw new JsonHttpException(404, 'User not found.');
95
        }
96
        $googleEvent = $this->get('app.google_calendar')
97
            ->getEventById($id);
98
        if (!$googleEvent) {
99
            throw new JsonHttpException(404, 'Event not found');
100
        }
101
        $event = new DtoEvent($googleEvent);
102
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
103
        return new JsonResponse(['user' => $user, 'event' => $event]);
104
    }
105
106
    /**
107
     * @Route("/user/{id}")
108
     * @Method("GET")
109
     *
110
     * @return JsonResponse
111
     */
112
    public function userEventsAction($id)
113
    {
114
        $user = $this->getDoctrine()->getRepository('AppBundle:User')->find($id);
115
        $events = $user->getEvents();
116
        $calendar = $this->get('app.google_calendar');
117
        $googleEvents = [];
118
        foreach ($events as $event) {
119
            $googleEvents[] = $calendar
120
                ->getEventById($event->getGoogleId());
121
        }
122
        if (!$googleEvents) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $googleEvents of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
123
            throw new JsonHttpException(404, 'Events not found');
124
        }
125
126
127
        $events = [];
128
        foreach ($googleEvents as $event) {
129
            if ($event) {
130
                $events[] = new DtoEvent($event);
131
            }
132
        }
133
        $user = $this->get('serializer')->normalize($user, null, ['groups' => ['Short']]);
134
135
        return new JsonResponse(['user' => $user, 'events' => $events]);
136
    }
137
138
    /**
139
     * @param $id
140
     * @Route("/{id}")
141
     * @Method("DELETE")
142
     * @return JsonResponse
143
     */
144
    public function removeEventAction($id)
145
    {
146
        $this->get('app.google_calendar')
147
            ->deleteEvent($id);
148
        $em = $this->getDoctrine()->getManager();
149
        /** @var Event $event */
150
        $event = $em->getRepository('AppBundle:Event')->findByGoogleId($id);
151
        $em->remove($event);
152
        $em->flush();
153
154
        return $this->json(['success' => 'Event was removed']);
155
    }
156
157
    /**
158
     * @param Request $request
159
     * @Method("PATCH")
160
     * @Route("/{id}")
161
     *
162
     * @return JsonResponse
163
     */
164
    public function editEventAction(Request $request, $id)
165
    {
166
        $data = json_decode($request->getContent(), true);
167
168 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...
169
            throw new JsonHttpException(400, 'Bad request.');
170
        }
171
172
        $dtoEvent = new DtoEvent();
173
        $form = $this->createForm(EventType::class, $dtoEvent);
174
        $this->handleJsonForm($form, $request);
175
        $this->get('app.google_calendar')
176
            ->editEvent($dtoEvent, $id, $request->query->all());
177
178
        return $this->json(['success' => 'Event edited']);
179
    }
180
181
    /**
182
     * FOR DEV ONLY.
183
     * @Method("PUT")
184
     * @Route("/clear")
185
     */
186
    public function clearAction()
187
    {
188
        $result = $this->get('app.google_calendar')->clear();
189
190
        return $this->json($result);
191
    }
192
}
193