sermon-notes/src/Controller/RegistrationController.php

50 lines
1.5 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
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\Attribute\Route;
class RegistrationController extends AbstractController
{
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
$role = ['ROLE_USER'];
if ($entityManager->getRepository(User::class)->getUserCount() == 0) {
$role = ['ROLE_ADMIN'];
}
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$user->setRoles($role);
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('app_home');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form,
]);
}
}