<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ProfilType;
use App\Security\EmailVerifier;
use App\Form\RegistrationFormType;
use App\Repository\UserRepository;
use App\Service\NotificationManager;
use Symfony\Component\Mime\Address;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class RegistrationController extends BaseController
{
private EmailVerifier $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
#[Route('/register', name: 'app_register')]
public function register(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
UserRepository $userRepository,
NotificationManager $notificationManager,
): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($userRepository->findOneBy(['email' => $form->get('email')->getData()])) {
$this->addFlash('ErreurRegistration', 'Email existe déjà !');
}else {
$majuscule = preg_match('@[A-Z]@', $form->get('plainPassword')->getData());
$minuscule = preg_match('@[a-z]@', $form->get('plainPassword')->getData());
$chiffre = preg_match('@[0-9]@', $form->get('plainPassword')->getData());
$number = strlen($form->get('plainPassword')->getData()) < 8;
if (!$majuscule || !$minuscule || !$chiffre || $number) {
$this->addFlash('ErreurRegistration', 'Le mot de passe doit comporter au moins 8 caractères : une lettre majuscule, une minuscule et un chiffre !');
}else {
if (strcmp($form->get('plainPassword')->getData(), $form->get('confirmpassword')->getData()) == 0) {
$user->setRoles(['ROLE_USER']);
$user->setPassword($form->get('plainPassword')->getData());
$entityManager->persist($user);
$entityManager->flush();
// Email de notification Utilisateur
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address($this->getParameter('EmailAdmin'), 'IGPPP'))
->to($user->getEmail())
->subject('Email de confirmation du compte IGPPP')
->htmlTemplate('email/email_confirmation_inscription.html.twig')
);
///Email de Notification
$edit_demande_url = $this->generateUrl('app_redirect_email', array( 'id' => $user->getId(), 'type' => 'demandeur' ), UrlGenerator::ABSOLUTE_URL );
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address($this->getParameter('EmailAdmin'), 'IGPPP'))
->to($this->getParameter('EmailNotification'))
->subject('Un nouveau compte a été crée !')
->htmlTemplate('email/email_notification_inscription.html.twig')
->context([
'User' => $user->getEmail(),
'demande_url' => $edit_demande_url
])
);
$admins = $entityManager->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach ( $admins as $admin){
$notification_message = 'Un nouveau compte a été crée !';
$notificationManager->pushMessage('Un nouveau compte a été crée !', $notification_message, $admin, $edit_demande_url);
}
return $this->redirectToRoute('login');
}else {
$this->addFlash('ErreurRegistration', 'Les mots de passe ne sont pas identiques !');
}
}
}
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
#[Route('/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
{
$id = $request->get('id');
if (null === $id) {
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
// @TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Votre email a bien été vérifié.');
return $this->redirectToRoute('login');
}
#[Route('/profil', name: 'app_profil')]
public function app_profil(Request $request, SluggerInterface $slugger, EntityManagerInterface $entityManager): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('login');
}
if (!$this->getUser()->isVerified()){
$this->addFlash('VerifAccount', 'Vous devez vérifier votre compte !');
return $this->redirectToRoute('app_logout');
}
if (!$this->getUser()->getCompleted()){
$this->addFlash('VerifAccount', 'Vous devez completer votre compte !');
}
$form = $this->createForm(ProfilType::class, $this->getUser());
$form->handleRequest($request);
if ($form->isSubmitted()) {
$this->getUser()->setCompleted(true);
$entityManager->persist($this->getUser());
$entityManager->flush();
return $this->redirectToRoute('front');
}
return $this->render('registration/profil.html.twig', [
'profilForm' => $form->createView(),
]);
}
#[Route('/save/profile/picture', name: 'app_save_profile_picture')]
public function saveProfilePicture(Request $request, EntityManagerInterface $entityManager): Response
{
$photo = $request->request->get('imgResult');
if ($photo) {
$fileName = 'photo' . '-' . uniqid() . '.png';
try {
if (!file_exists($this->getParameter('PhotoUsers'))) {
mkdir($this->getParameter('PhotoUsers'), 0777, true);
}
copy($photo,$this->getParameter('PhotoUsers').$fileName);
$this->getUser()->setPhoto($fileName);
$entityManager->flush();
} catch (FileException $e) {
dd('a',$e);
}
}
return new Response('ok');
}
}