1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silverback\ApiComponentBundle\Controller; |
4
|
|
|
|
5
|
|
|
use Silverback\ApiComponentBundle\Repository\User\UserRepository; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
use Silverback\ApiComponentBundle\Exception\InvalidEntityException; |
8
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
9
|
|
|
use Symfony\Component\HttpFoundation\Request; |
10
|
|
|
use Symfony\Component\HttpFoundation\Response; |
11
|
|
|
use Symfony\Component\Routing\Annotation\Route; |
12
|
|
|
use Symfony\Component\Validator\ConstraintViolationInterface; |
13
|
|
|
|
14
|
|
|
class UpdateUsernameAction |
15
|
|
|
{ |
16
|
|
|
private $userRepository; |
17
|
|
|
private $entityManager; |
18
|
|
|
|
19
|
|
|
public function __construct( |
20
|
|
|
UserRepository $userRepository, |
21
|
|
|
EntityManagerInterface $entityManager |
22
|
|
|
) { |
23
|
|
|
$this->userRepository = $userRepository; |
24
|
|
|
$this->entityManager = $entityManager; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @Route("/update_username", name="update_username", methods={"post"}) |
29
|
|
|
* @param Request $request |
30
|
|
|
* @return JsonResponse |
31
|
|
|
*/ |
32
|
|
|
public function __invoke(Request $request): JsonResponse |
33
|
|
|
{ |
34
|
|
|
$data = \json_decode($request->getContent(), true); |
35
|
|
|
$username = $data['username']; |
36
|
|
|
$token = $data['token']; |
37
|
|
|
$user = $this->userRepository->findOneBy([ |
38
|
|
|
'newUsername' => $username, |
39
|
|
|
'newUsernameConfirmationToken' => $token |
40
|
|
|
]); |
41
|
|
|
if (null === $user) { |
42
|
|
|
$currentUser = $this->userRepository->findOneBy([ |
43
|
|
|
'username' => $username |
44
|
|
|
]); |
45
|
|
|
if ($currentUser) { |
46
|
|
|
return new JsonResponse([], Response::HTTP_OK); |
47
|
|
|
} |
48
|
|
|
return new JsonResponse([], Response::HTTP_NOT_FOUND); |
49
|
|
|
} |
50
|
|
|
try { |
51
|
|
|
$user |
52
|
|
|
->setUsername($user->getNewUsername()) |
53
|
|
|
->setNewUsername(null) |
54
|
|
|
->setUsernameConfirmationToken(null) |
55
|
|
|
; |
56
|
|
|
$this->entityManager->flush(); |
57
|
|
|
return new JsonResponse([], Response::HTTP_OK); |
58
|
|
|
} catch (InvalidEntityException $exception) { |
59
|
|
|
$errors = []; |
60
|
|
|
/** @var ConstraintViolationInterface $error */ |
61
|
|
|
foreach ($exception->getErrors() as $error) { |
62
|
|
|
$errors[] = $error->getMessage(); |
63
|
|
|
} |
64
|
|
|
return new JsonResponse($errors, Response::HTTP_BAD_REQUEST); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|