Completed
Pull Request — master (#30)
by Yuriy
37:30 queued 22:07
created

DefaultController   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 141
Duplicated Lines 17.02 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 29.49%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 16
c 4
b 1
f 0
lcom 1
cbo 8
dl 24
loc 141
ccs 23
cts 78
cp 0.2949
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B loginAction() 0 43 3
C dashboardAction() 12 43 8
B newsAction() 12 31 5

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\Api;
4
5
use AppBundle\Entity\DTO\DtoUser;
6
use AppBundle\Entity\DTO\DtoEvent;
7
use AppBundle\Entity\Event;
8
use AppBundle\Entity\FormRequest;
9
use AppBundle\Entity\Survey\Survey;
10
use AppBundle\Exception\JsonHttpException;
11
use AppBundle\Form\LoginType;
12
use Mcfedr\JsonFormBundle\Controller\JsonController;
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\Routing\Annotation\Route;
17
use Doctrine\Common\Collections\Criteria;
18
use Doctrine\Common\Collections\ArrayCollection;
19
20
class DefaultController extends JsonController
21
{
22
    /**
23
     * @param Request $request
24
     * @Route("/login", name="api_login")
25
     * @Method("POST")
26
     *
27
     * @return JsonResponse
28
     */
29 1
    public function loginAction(Request $request)
30
    {
31 1
        $userCredentials = new DtoUser();
32
33 1
        $form = $this->createForm(LoginType::class, $userCredentials);
34
35 1
        $this->handleJsonForm($form, $request);
36
37 1
        $user = $this->getDoctrine()->getRepository('AppBundle:User')
38 1
            ->findOneBy(['email' => $userCredentials->getEmail()]);
39
40 1
        if (!$user) {
41
            throw new JsonHttpException(400, 'Bad credentials');
42
        }
43
44 1
        $result = $this->get('security.encoder_factory')
45 1
            ->getEncoder($user)
46 1
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
47 1
        if (!$result) {
48
            throw new JsonHttpException(400, 'Bad credentials');
49
        }
50
51 1
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
52
53 1
        $em = $this->getDoctrine()
54 1
            ->getManager();
55 1
        $user->setApiToken($token);
56
57 1
        $em->persist($user);
58
59 1
        $em->flush();
60
61 1
        $serializer = $this->get('serializer');
62 1
        $json = $serializer->normalize(
63
            $user,
64 1
            null,
65 1
            array('groups' => array('Short'))
66
        );
67
68 1
        return $this->json(
69 1
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
70
        );
71
    }
72
73
    /**
74
     * @Route("/dashboard")
75
     * @Method({"GET"})
76
     *
77
     * @return JsonResponse
78
     */
79
    public function dashboardAction()
80
    {
81
        $user = $this->getUser();
82
        $events = $user->getEvents();
83
        $requests = $user->getFormRequests();
84
        $surveys = $user->getSurveys();
85
        $surveys = $surveys->matching(Criteria::create()->where(Criteria::expr()->eq('status', 'current')));
86
        $array = new ArrayCollection(
87
            array_merge($events->toArray(), $requests->toArray(), $surveys->toArray())
88
        );
89
        $news = $array->matching(Criteria::create()->orderBy(array('updatedAt' => Criteria::DESC))->setFirstResult(0)
90
            ->setMaxResults(3));
91
        $sortNews = array_fill_keys(['events', 'surveys', 'requests'], []);
92
        $calendar = $this->get('app.google_calendar');
93 View Code Duplication
        foreach ($news as $new) {
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...
94
            if ($new instanceof Event) {
95
                $sortNews['events'][] = new DtoEvent($calendar
96
                    ->getEventById($new->getGoogleId()));
97
            }
98
            if ($new instanceof Survey) {
99
                $sortNews['surveys'][] = $new;
100
            }
101
            if ($new instanceof FormRequest) {
102
                $sortNews['requests'][] = $new;
103
            }
104
        }
105
        $events = $events->matching(Criteria::create()->setFirstResult(0)->setMaxResults(2));
106
        $googleEvents = [];
107
        foreach ($events as $event) {
108
            $googleEvents[] = $calendar
109
                ->getEventById($event->getGoogleId());
110
        }
111
        $events = [];
112
        foreach ($googleEvents as $event) {
113
            if ($event) {
114
                $events[] = new DtoEvent($event);
115
            }
116
        }
117
118
        return $this->json(
119
            ['news' => $sortNews, 'events' => $events, 'surveys' => $surveys]
120
        );
121
    }
122
123
    /**
124
     * @Route("/news")
125
     * @Method({"GET"})
126
     *
127
     * @return JsonResponse
128
     */
129
    public function newsAction()
130
    {
131
        $user = $this->getUser();
132
        $events = $user->getEvents();
133
        $requests = $user->getFormRequests();
134
        $surveys = $user->getSurveys();
135
        $surveys = $surveys->matching(Criteria::create()->where(Criteria::expr()->eq('status', 'current')));
136
        $array = new ArrayCollection(
137
            array_merge($events->toArray(), $requests->toArray(), $surveys->toArray())
138
        );
139
        $news = $array->matching(Criteria::create()->orderBy(array('updatedAt' => Criteria::DESC))->setFirstResult(0)
140
            ->setMaxResults(3));
141
        $sortNews = array_fill_keys(['events', 'surveys', 'requests'], []);
142
        $calendar = $this->get('app.google_calendar');
143 View Code Duplication
        foreach ($news as $new) {
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...
144
            if ($new instanceof Event) {
145
                $sortNews['events'][] = new DtoEvent($calendar
146
                    ->getEventById($new->getGoogleId()));
147
            }
148
            if ($new instanceof Survey) {
149
                $sortNews['surveys'][] = $new;
150
            }
151
            if ($new instanceof FormRequest) {
152
                $sortNews['requests'][] = $new;
153
            }
154
        }
155
156
        return $this->json(
157
            ['news' => $sortNews]
158
        );
159
    }
160
}
161