src/Controller/RegistrationController.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\UserType;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. class RegistrationController extends AbstractController
  11. {
  12. private $passwordHasher;
  13. public function __construct(UserPasswordHasherInterface $passwordHasher)
  14. {
  15. $this->passwordHasher = $passwordHasher;
  16. }
  17. /**
  18. * @Route("/registration", name="registration")
  19. */
  20. public function index(Request $request, ManagerRegistry $doctrine)
  21. {
  22. $user = new User();
  23. $form = $this->createForm(UserType::class, $user);
  24. $form->handleRequest($request);
  25. if ($form->isSubmitted() && $form->isValid()) {
  26. // hash the password (based on the security.yaml config for the $user class)
  27. $hashedPassword = $this->passwordHasher->hashPassword(
  28. $user,
  29. $user->getPassword()
  30. );
  31. $user->setPassword($hashedPassword);
  32. // Set their role
  33. $user->setRoles(['ROLE_USER']);
  34. $em = $doctrine->getManager();
  35. $em->persist($user);
  36. $em->flush();
  37. return $this->redirectToRoute('app_login');
  38. }
  39. return $this->render('registration/index.html.twig', [
  40. 'form' => $form->createView(),
  41. ]);
  42. }
  43. }