Completed
Push — dev ( f2abe4...3f06d3 )
by nonanerz
05:36 queued 05:30
created

DefaultController::dashboardAction()   C

Complexity

Conditions 8
Paths 54

Size

Total Lines 44
Code Lines 32

Duplication

Lines 12
Ratio 27.27 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 12
loc 44
ccs 0
cts 0
cp 0
rs 5.3846
c 3
b 0
f 0
cc 8
eloc 32
nc 54
nop 0
crap 72
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 1
     * @Route("/login", name="api_login")
25
     * @Method("POST")
26 1
     *
27
     * @return JsonResponse
28 1
     */
29
    public function loginAction(Request $request)
30 1
    {
31
        $userCredentials = new DtoUser();
32 1
33 1
        $form = $this->createForm(LoginType::class, $userCredentials);
34
35 1
        $this->handleJsonForm($form, $request);
36
37
        $user = $this->getDoctrine()->getRepository('AppBundle:User')
38
            ->findOneBy(['email' => $userCredentials->getEmail()]);
39 1
40 1
        if (!$user) {
41 1
            throw new JsonHttpException(400, 'Bad credentials');
42 1
        }
43
44
        $result = $this->get('security.encoder_factory')
45
            ->getEncoder($user)
46 1
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
47
        if (!$result) {
48 1
            throw new JsonHttpException(400, 'Bad credentials');
49 1
        }
50 1
51
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
52 1
53
        $em = $this->getDoctrine()
54 1
            ->getManager();
55
        $user->setApiToken($token);
56 1
57 1
        $em->persist($user);
58
59 1
        $em->flush();
60 1
61
        $serializer = $this->get('serializer');
62
        $json = $serializer->normalize(
63 1
            $user,
64 1
            null,
65
            array('groups' => array('Short'))
66
        );
67
68
        return $this->json(
69
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
70
        );
71
    }
72 1
73
    /**
74 1
     * @Route("/dashboard")
75
     * @Method({"GET"})
76
     *
77
     * @return JsonResponse
78
     */
79
    public function dashboardAction()
80
    {
81
        $user = $this->getUser();
82
        $events = $this->getDoctrine()->getRepository(Event::class)
83
            ->selectNotExpiredByUser($this->getUser());
84
        $requests = $user->getFormRequests();
85
        $surveys = $user->getSurveys();
86
        $surveys = $surveys->matching(Criteria::create()->where(Criteria::expr()->eq('status', 'current')));
87
        $array = new ArrayCollection(
88
            array_merge($events->toArray(), $requests->toArray(), $surveys->toArray())
89
        );
90
        $news = $array->matching(Criteria::create()->orderBy(array('updatedAt' => Criteria::DESC))->setFirstResult(0)
91
            ->setMaxResults(3));
92
        $sortNews = array_fill_keys(['events', 'surveys', 'requests'], false);
93
        $calendar = $this->get('app.google_calendar');
94 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...
95
            if ($new instanceof Event) {
96
                $sortNews['events'][] = new DtoEvent($calendar
97
                    ->getEventById($new->getGoogleId()));
98
            }
99
            if ($new instanceof Survey) {
100
                $sortNews['surveys'][] = $new;
101
            }
102
            if ($new instanceof FormRequest) {
103
                $sortNews['requests'][] = $new;
104
            }
105
        }
106
        $events = $events->matching(Criteria::create()->setFirstResult(0)->setMaxResults(2));
107
        $googleEvents = [];
108
        foreach ($events as $event) {
109
            $googleEvents[] = $calendar
110
                ->getEventById($event->getGoogleId());
111
        }
112
        $events = [];
113
        foreach ($googleEvents as $event) {
114
            if ($event) {
115
                $events[] = new DtoEvent($event);
116
            }
117
        }
118
119
        return $this->json(
120
            ['news' => $sortNews, 'events' => $events, 'surveys' => $surveys]
121
        );
122
    }
123
124
    /**
125
     * @Route("/news")
126
     * @Method({"GET"})
127
     *
128
     * @return JsonResponse
129
     */
130
    public function newsAction()
131
    {
132
        $user = $this->getUser();
133
        $events = $this->getDoctrine()->getRepository(Event::class)
134
            ->selectNotExpiredByUser($this->getUser());
135
        $requests = $user->getFormRequests();
136
        $surveys = $user->getSurveys();
137
        $surveys = $surveys->matching(Criteria::create()->where(Criteria::expr()->eq('status', 'current')));
138
        $array = new ArrayCollection(
139
            array_merge($events->toArray(), $requests->toArray(), $surveys->toArray())
140
        );
141
        $news = $array->matching(Criteria::create()->orderBy(array('updatedAt' => Criteria::DESC))->setFirstResult(0)
142
            ->setMaxResults(3));
143
        $sortNews = array_fill_keys(['events', 'surveys', 'requests'], false);
144
        $calendar = $this->get('app.google_calendar');
145 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...
146
            if ($new instanceof Event) {
147
                $sortNews['events'][] = new DtoEvent($calendar
148
                    ->getEventById($new->getGoogleId()));
149
            }
150
            if ($new instanceof Survey) {
151
                $sortNews['surveys'][] = $new;
152
            }
153
            if ($new instanceof FormRequest) {
154
                $sortNews['requests'][] = $new;
155
            }
156
        }
157
158
        return $this->json(
159
            ['news' => $sortNews]
160
        );
161
    }
162
}
163