<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Security\AppCustomAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
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 Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="app_register")
*/
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, AppCustomAuthenticator $authenticator, EntityManagerInterface $entityManager): Response
{
// Bloquer l'inscription sur flexenergie.pro
if ($request->getHost() === 'flexenergie.pro') {
return $this->redirectToRoute('pro_login');
}
$user = new User();
// Récupérer le domaine actuel
$currentDomain = $request->getHost();
$form = $this->createForm(RegistrationFormType::class, $user, [
'current_domain' => $currentDomain
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$user->setRoles(['ROLE_USER']);
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
try {
return $userAuthenticator->authenticateUser(
$user,
$authenticator,
$request
);
} catch (\Exception $e) {
// Log the error
$this->addFlash('error', 'An error occurred during registration. Please try again.');
return $this->redirectToRoute('app_register');
}
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
}