src/Controller/RegistrationController.php line 19

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. class RegistrationController extends AbstractController
  14. {
  15.     #[Route('/register'name'app_register')]
  16.     public function register(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppCustomAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  17.     {
  18.         if ($this->getUser()) {
  19.             return $this->redirectToRoute('dashboard');
  20.         }
  21.         
  22.         $user = new User();
  23.         $form $this->createForm(RegistrationFormType::class, $user);
  24.         $form->handleRequest($request);
  25.         if ($form->isSubmitted() && $form->isValid()) {
  26.             // encode the plain password
  27.             $user->setPassword(
  28.             $userPasswordHasher->hashPassword(
  29.                     $user,
  30.                     $form->get('plainPassword')->getData()
  31.                 )
  32.             );
  33.             $user->setRoles(["ROLE_ADMIN"]);
  34.             $entityManager->persist($user);
  35.             $entityManager->flush();
  36.             // do anything else you need here, like send an email
  37.             return $userAuthenticator->authenticateUser(
  38.                 $user,
  39.                 $authenticator,
  40.                 $request
  41.             );
  42.         }
  43.         return $this->render('registration/register.html.twig', [
  44.             'registrationForm' => $form->createView(),
  45.         ]);
  46.     }
  47. }