<?php
namespace App\Controller;
use App\Entity\Customer;
use App\Form\RegistrationFormType;
use App\Security\AppAuthenticator;
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 Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use App\Repository\CustomerRepository;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="app_register")
*/
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, AppAuthenticator $authenticator, EntityManagerInterface $entityManager, ManagerRegistry $registry): Response
{
$user = new Customer();
$customer_repository = new CustomerRepository($registry);
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$this->setCustomerNumber($user,$customer_repository);
$this->setCreatedAt($user);
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $userAuthenticator->authenticateUser(
$user,
$authenticator,
$request
);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
public function setCreatedAt($entity)
{
if (property_exists($entity, "createdAt")) {
$now = new \DateTime("now");
$entity->setCreatedAt($now);
}
}
public function setCustomerNumber($entity, $customer_repository)
{
if (!$entity instanceof Customer) {
return;
}
$customer_number = '';
for ($i = 0; $i < 12; $i++) {
$customer_number .= mt_rand(0, 9);
}
$customer_number = implode('-', str_split($customer_number, 3));
$customer = $customer_repository->findOneByCustomerNumber($customer_number);
if ($customer) {
return $this->setCustomerNumber($entity,$customer_repository);
} else {
$entity->setCustomerNumber($customer_number);
}
}
}