Completed
Pull Request — master (#30)
by nonanerz
18:57
created

CalendarController   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 173
Duplicated Lines 3.47 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 5
Bugs 1 Features 2
Metric Value
wmc 23
c 5
b 1
f 2
lcom 1
cbo 7
dl 6
loc 173
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A eventsListAction() 0 11 2
A singleEventAction() 0 16 2
A userEventsAction() 0 21 4
A removeEventAction() 0 12 1
B editEventAction() 3 24 6
C newEventAction() 3 41 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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