Completed
Push — dev ( 920bbd...e84340 )
by nonanerz
04:49 queued 04:45
created

DefaultController::newsAction()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 32
Code Lines 23

Duplication

Lines 12
Ratio 37.5 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 12
loc 32
ccs 0
cts 23
cp 0
rs 8.439
cc 5
eloc 23
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
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 = $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