<?php
namespace App\Controller\Front;
use App\Entity\{Client, User};
use App\Form\ClientType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Service\AccessClientService;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class RegisterController extends AbstractController
{
private $tokenStorage;
public function __construct(
TokenStorageInterface $tokenStorage
)
{
$this->tokenStorage = $tokenStorage;
}
/**
* @Route("/client/register", name="app_front_register")
*/
public function register(AccessClientService $accessClientService, Request $request, EntityManagerInterface $entityManager, UserPasswordEncoderInterface $passwordEncoder): Response
{
$accessClientService->handleAccessControl();
$slug = $request->getSession()->get('register_info_slug');
$user = new User();
$client = new Client();
$form = $this->createForm(ClientType::class, $client);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$civility = $form->get('user')->get('civility')->getData();
$lastname = $form->get('user')->get('lastname')->getData();
$firstname = $form->get('user')->get('firstname')->getData();
$email = $form->get('user')->get('email')->getData();
$mobilePhone = $form->get('mobilePhone')->getData();
$plainPassword = $form->get('user')->get('password')->getData();
$agreeTerms = $form->get('agreeTerms')->getData();
$user->setCivility($civility);
if ($civility === 'Monsieur' || $civility === 'Madame') {
$client->setEntrepriseName(null);
$client->setSiret(null);
}
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
$user->setRoles(['ROLE_CLIENT']);
$encodedPassword = $passwordEncoder->encodePassword($user, $plainPassword);
$user->setPassword($encodedPassword);
$user->setStatus(User::ACTIVE);
$user->setCreatedAtValue();
$user->preUpdate();
$client->setUser($user);
$client->setMobilePhone($mobilePhone);
$client->setAgreeTerms($agreeTerms);
$entityManager->persist($user);
$entityManager->persist($client);
$entityManager->flush();
if ($slug) {
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
return $this->redirectToRoute('app_client_service_login_info', ['slug' => $slug]);
} else {
$this->addFlash('success', 'Succès ! Votre compte client a été bien créé.');
return $this->redirectToRoute('app_front_login');
}
}
return $this->render('front/register/client.html.twig', [
'form' => $form->createView(),
]);
}
}