src/Controller/RegistrationController.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Security\AppCustomAuthenticator;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. class RegistrationController extends AbstractController
  15. {
  16.     /**
  17.      * @Route("/register", name="app_register")
  18.      */
  19.     public function register(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppCustomAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  20.     {
  21.         // Bloquer l'inscription sur flexenergie.pro
  22.         if ($request->getHost() === 'flexenergie.pro') {
  23.             return $this->redirectToRoute('pro_login');
  24.         }
  25.         $user = new User();
  26.         // Récupérer le domaine actuel
  27.         $currentDomain $request->getHost();
  28.         
  29.         $form $this->createForm(RegistrationFormType::class, $user, [
  30.             'current_domain' => $currentDomain
  31.         ]);
  32.         $form->handleRequest($request);
  33.         if ($form->isSubmitted() && $form->isValid()) {
  34.             // encode the plain password
  35.             $user->setPassword(
  36.             $userPasswordHasher->hashPassword(
  37.                     $user,
  38.                     $form->get('plainPassword')->getData()
  39.                 )
  40.             );
  41.             $user->setRoles(['ROLE_USER']);
  42.             $entityManager->persist($user);
  43.             $entityManager->flush();
  44.             // do anything else you need here, like send an email
  45.             try {
  46.                 return $userAuthenticator->authenticateUser(
  47.                     $user,
  48.                     $authenticator,
  49.                     $request
  50.                 );
  51.             } catch (\Exception $e) {
  52.                 // Log the error
  53.                 $this->addFlash('error''An error occurred during registration. Please try again.');
  54.                 return $this->redirectToRoute('app_register');
  55.             }
  56.         }
  57.         return $this->render('registration/register.html.twig', [
  58.             'registrationForm' => $form->createView(),
  59.         ]);
  60.     }
  61. }