Completed
Push — master ( d41a9c...8343ec )
by Valentyn
04:11
created

UserController::getMe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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