Completed
Pull Request — master (#30)
by
unknown
04:28
created

DefaultController::newsAction()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 31
Code Lines 22

Duplication

Lines 12
Ratio 38.71 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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