src/Controller/RegistrationController.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Repository\UserRepository;
  6. use App\Security\LoginFormAuthenticator;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  12. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  13. class RegistrationController extends AbstractController
  14. {
  15.     private UserRepository $userRepository;
  16.     public function __construct(
  17.         UserRepository $userRepository
  18.     ) {
  19.         $this->userRepository $userRepository;
  20.     }
  21.     /**
  22.      * @Route("/register", name="app_register")
  23.      */
  24.     public function register(Request $requestUserPasswordEncoderInterface $passwordEncoderGuardAuthenticatorHandler $guardHandlerLoginFormAuthenticator $authenticator): Response
  25.     {
  26.         if (null != $this->userRepository->hasUser()) {
  27.             return $this->redirectToRoute('app_login');
  28.         }
  29.         $user = new User();
  30.         $form $this->createForm(RegistrationFormType::class, $user);
  31.         $form->handleRequest($request);
  32.         if ($form->isSubmitted() && $form->isValid()) {
  33.             // encode the plain password
  34.             $user->setPassword(
  35.                 $passwordEncoder->encodePassword(
  36.                     $user,
  37.                     $form->get('plainPassword')->getData()
  38.                 )
  39.             );
  40.             $entityManager $this->getDoctrine()->getManager();
  41.             $entityManager->persist($user);
  42.             $entityManager->flush();
  43.             // do anything else you need here, like send an email
  44.             return $guardHandler->authenticateUserAndHandleSuccess(
  45.                 $user,
  46.                 $request,
  47.                 $authenticator,
  48.                 'main' // firewall name in security.yaml
  49.             );
  50.         }
  51.         return $this->render('registration/register.html.twig', [
  52.             'registrationForm' => $form->createView(),
  53.         ]);
  54.     }
  55. }