Completed
Push — master ( f446cd...59ed7d )
by Valentyn
13:46 queued 11:33
created

UserController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 21

Test Coverage

Coverage 98.39%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 21
dl 0
loc 166
ccs 61
cts 62
cp 0.9839
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A postUsers() 0 24 4
A postConfirmEmail() 0 20 2
A getUsers() 0 18 2
A putUsers() 0 23 3
A getAll() 0 14 1
A getMe() 0 8 1
1
<?php
2
3
namespace App\Users\Controller;
4
5
use App\Controller\BaseController;
6
use App\Users\Entity\User;
7
use App\Users\Entity\UserRoles;
8
use App\Users\Event\UserRegisteredEvent;
9
use App\Users\Repository\ConfirmationTokenRepository;
10
use App\Users\Repository\UserRepository;
11
use App\Users\Request\ConfirmEmailRequest;
12
use App\Users\Request\RegisterUserRequest;
13
use App\Users\Request\UpdateUserRequest;
14
use App\Users\Service\RegisterService;
15
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
18
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19
use Symfony\Component\Routing\Annotation\Route;
20
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
21
use Symfony\Component\Translation\TranslatorInterface;
22
use Symfony\Component\Validator\Validator\ValidatorInterface;
23
24
class UserController extends BaseController
25
{
26
    /**
27
     * Registration.
28
     *
29
     * @Route("/api/users", methods={"POST"})
30
     *
31
     * @param RegisterUserRequest      $request
32
     * @param RegisterService          $registerService
33
     * @param EventDispatcherInterface $dispatcher
34
     * @param ValidatorInterface       $validator
35
     *
36
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
37
     */
38 3
    public function postUsers(RegisterUserRequest $request, RegisterService $registerService, EventDispatcherInterface $dispatcher, ValidatorInterface $validator)
39
    {
40 3
        if ($this->getUser() !== null) {
41
            throw new AccessDeniedHttpException();
42
        }
43
44 3
        $registeredUser = $registerService->registerByRequest($request);
45 3
        $errors = $validator->validate($registeredUser);
46
47 3
        if ($errors && $errors->count() !== 0) {
48 1
            return $request->getErrorResponse($errors);
49
        }
50
51 2
        $em = $this->getDoctrine()->getManager();
52 2
        $em->persist($registeredUser);
53 2
        $em->flush();
54
55 2
        $userRegisteredEvent = new UserRegisteredEvent($registeredUser);
56 2
        $dispatcher->dispatch(UserRegisteredEvent::NAME, $userRegisteredEvent);
57
58 2
        return $this->response($registeredUser, 200, [], [
59 2
            'groups' => ['view'],
60
        ]);
61
    }
62
63
    /**
64
     * Confirm email.
65
     *
66
     * @Route("/api/confirmEmail", methods={"POST"})
67
     *
68
     * @param ConfirmEmailRequest         $request
69
     * @param ConfirmationTokenRepository $confirmationTokenRepository
70
     * @param TranslatorInterface         $translator
71
     *
72
     * @return JsonResponse
73
     */
74 2
    public function postConfirmEmail(ConfirmEmailRequest $request, ConfirmationTokenRepository $confirmationTokenRepository, TranslatorInterface $translator)
75
    {
76 2
        $token = $request->get('token');
77
78 2
        if (null === $confirmationToken = $confirmationTokenRepository->findByToken($token)) {
79 1
            throw new BadCredentialsException($translator->trans('bad_email_confirmation_token', [
80 1
                'token' => $token,
81 1
            ], 'users'));
82
        }
83
84 1
        $user = $confirmationToken->getUser();
85 1
        $user->confirmEmail();
86
87 1
        $entityManager = $this->getDoctrine()->getManager();
88 1
        $entityManager->persist($user);
89 1
        $entityManager->remove($confirmationToken);
90 1
        $entityManager->flush();
91
92 1
        return new JsonResponse(null, 202);
93
    }
94
95
    /**
96
     * Get single user.
97
     *
98
     * @Route("/api/users/{id}", methods={"GET"}, requirements={"id"="\d+"})
99
     *
100
     * @param $id
101
     * @param TranslatorInterface $translator
102
     *
103
     * @return JsonResponse
104
     */
105 3
    public function getUsers($id, TranslatorInterface $translator)
106
    {
107 3
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
108
109
        /** @var $userRepository \App\Users\Repository\UserRepository */
110 2
        $userRepository = $this->getDoctrine()->getRepository(User::class);
111 2
        $user = $userRepository->find($id);
112
113 2
        if ($user === null) {
114 1
            throw new NotFoundHttpException($translator->trans('not_found_by_id', [
115 1
                'user_id' => $id,
116 1
            ], 'users'));
117
        }
118
119 1
        return $this->response($user, 200, [], [
120 1
            'groups' => ['view'],
121
        ]);
122
    }
123
124
    /**
125
     * @Route("/api/users/{id}", methods={"POST", "PUT", "PATCH"}, requirements={"id"="\d+"})
126
     *
127
     * @param User              $user
128
     * @param UpdateUserRequest $request
129
     *
130
     * @throws \Exception
131
     *
132
     * @return JsonResponse
133
     */
134 4
    public function putUsers(User $user, UpdateUserRequest $request)
135
    {
136 4
        $currentUser = $this->getUser();
137 4
        if ($currentUser === null) {
138 1
            $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
139
        }
140
141
        /** @var $currentUser User */
142 3
        if ($currentUser->getId() !== $user->getId()) {
143 2
            $this->denyAccessUnlessGranted(UserRoles::ROLE_ADMIN);
144
        }
145
146 2
        $profile = $user->getProfile();
147 2
        $profileData = $request->get('profile');
148 2
        $profile->setFirstName($profileData['first_name']);
149 2
        $profile->setLastName($profileData['last_name']);
150 2
        $profile->setBirthDate(new \DateTimeImmutable($profileData['birth_date']));
151 2
        $profile->setAbout($profileData['about']);
152 2
        $profile->setPublicEmail($profileData['public_email']);
153 2
        $this->getDoctrine()->getManager()->flush();
154
155 2
        return new JsonResponse(null, 202);
156
    }
157
158
    /**
159
     * Get all users.
160
     *
161
     * @Route("/api/users", methods={"GET"})
162
     */
163 3
    public function getAll()
164
    {
165 3
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
166
167
        /**
168
         * @var UserRepository
169
         */
170 2
        $userRepository = $this->getDoctrine()->getRepository(User::class);
171 2
        $users = $userRepository->findAll();
172
173 2
        return $this->response($users, 200, [], [
174 2
            'groups' => ['list'],
175
        ]);
176
    }
177
178
    /**
179
     * @Route("/api/users/me", methods={"GET"})
180
     */
181 5
    public function getMe()
182
    {
183 5
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
184
185 5
        return $this->response($this->getUser(), 200, [], [
186 5
            'groups' => ['view'],
187
        ]);
188
    }
189
}
190