Files
BookNest/src/Controller/RegistrationController.php

78 lines
2.9 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RegistrationController extends AbstractController
{
private $entityManager;
private $passwordHasher;
private $validator;
public function __construct(EntityManagerInterface $entityManager, UserPasswordHasherInterface $passwordHasher, ValidatorInterface $validator)
{
$this->entityManager = $entityManager;
$this->passwordHasher = $passwordHasher;
$this->validator = $validator;
}
#[Route('/registration', name: 'app_registration')]
public function register(Request $request): Response
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$existingEmail = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $user->getEmail()]);
$existingPseudo = $this->entityManager->getRepository(User::class)->findOneBy(['pseudo' => $user->getPseudo()]);
if ($existingEmail) {
$form->get('email')->addError(new \Symfony\Component\Form\FormError('Cet email est déjà utilisé.'));
}
if ($existingPseudo) {
$form->get('pseudo')->addError(new \Symfony\Component\Form\FormError('Ce pseudo est déjà pris.'));
}
$plainPassword = $user->getPassword();
$confirmPassword = $form->get('confirmPassword')->getData();
if ($plainPassword !== $confirmPassword) {
$this->addFlash('error', 'Les mots de passe ne correspondent pas.');
return $this->redirectToRoute('app_registration');
}
$errors = $this->validator->validate($user);
if (count($errors) > 0) {
foreach ($errors as $error) {
$form->addError(new \Symfony\Component\Form\FormError($error->getMessage()));
}
}
if ($form->isValid()) {
$hashedPassword = $this->passwordHasher->hashPassword($user, $plainPassword);
$user->setPassword($hashedPassword);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('success', 'Votre compte a été créé avec succès !');
return $this->redirectToRoute('home');
}
}
return $this->render('registration/index.html.twig', [
'form' => $form->createView(),
]);
}
}