1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Controller; |
6
|
|
|
|
7
|
|
|
use App\Factory\UserFactoryInterface; |
8
|
|
|
use App\Form\ErrorHandler; |
9
|
|
|
use App\Form\RegisterUserType; |
10
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
11
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
12
|
|
|
use Symfony\Component\Form\FormFactoryInterface; |
13
|
|
|
use Symfony\Component\HttpFoundation\Request; |
14
|
|
|
use Symfony\Component\HttpFoundation\Response; |
15
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
16
|
|
|
|
17
|
|
|
final class ApiUsersController extends AbstractController |
18
|
|
|
{ |
19
|
|
|
protected $serializer; |
20
|
|
|
|
21
|
|
|
private $userFactory; |
22
|
|
|
|
23
|
|
|
public function __construct(SerializerInterface $serializer, UserFactoryInterface $userFactory) |
24
|
|
|
{ |
25
|
|
|
$this->serializer = $serializer; |
26
|
|
|
$this->userFactory = $userFactory; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function getCurrentUser(): Response |
30
|
|
|
{ |
31
|
|
|
return new Response($this->serializer->serialize($this->getUser(), 'json', [ |
32
|
|
|
'groups' => [ |
33
|
|
|
'user_details', |
34
|
|
|
'course_details', |
35
|
|
|
], |
36
|
|
|
])); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function registerUser( |
40
|
|
|
Request $request, |
41
|
|
|
FormFactoryInterface $formFactory, |
42
|
|
|
EntityManagerInterface $entityManager |
43
|
|
|
): Response { |
44
|
|
|
$user = $this->userFactory->create(); |
45
|
|
|
$form = $formFactory->create(RegisterUserType::class, $user); |
46
|
|
|
$form->handleRequest($request); |
47
|
|
|
if ($form->isSubmitted() && $form->isValid()) { |
48
|
|
|
$entityManager->persist($user); |
49
|
|
|
$entityManager->flush(); |
50
|
|
|
|
51
|
|
|
return new Response($this->serializer->serialize($user, 'json', ['groups' => ['user_details']]), Response::HTTP_CREATED); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return new Response($this->serializer->serialize(ErrorHandler::getErrorsFromForm($form), 'json'), Response::HTTP_BAD_REQUEST); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|