<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\UserImage;
use App\Form\RegistrationType;
use App\Form\RecruiterFormType;
use App\Repository\UserRepository;
use App\Service\Mailer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class RegistrationController extends AbstractController
{
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
/**
* @var Mailer
*/
private $mailer;
/**
* @var UserRepository
*/
private $userRepository;
public function __construct(UserPasswordEncoderInterface $passwordEncoder, Mailer $mailer, UserRepository $userRepository)
{
$this->passwordEncoder = $passwordEncoder;
$this->mailer = $mailer;
$this->userRepository = $userRepository;
}
/**
* @Route("/inscription", name="register")
* @param Request $request
* @return Response
*/
public function register(Request $request, SluggerInterface $slugger, ValidatorInterface $validator): Response
{
$userimage = new UserImage();
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
$errors = $validator->validate($user);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword(
$this->passwordEncoder->encodePassword($user, $form->get("password")->getData())
);
/** @var UploadedFile $cv */
$cvFile = $form->get('cv')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($cvFile) {
$originalFilename = pathinfo($cvFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $cvFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$cvFile->move(
$this->getParameter('cvs_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'cv' property to store the PDF file name
// instead of its contents
$user->setCv($newFilename);
}
$user->setToken($this->generateToken());
$user->setRoles(['ROLE_EMPLOYEE']);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$uploadedFile = $form->get('userImage')->getData();
if($uploadedFile) {
$destination = $this->getParameter('kernel.project_dir') . '/public/uploads/images_users/imageprofil';
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = time() . $originalFilename . uniqid() . '.' . $uploadedFile->guessExtension();
$uploadedFile->move(
$destination,
$newFilename
);
$userimage = $em->getRepository(UserImage::class)->findOneByUserImages($user);
if (!$userimage) {
$userimage = new UserImage();
}
$userimage->setImageName($newFilename);
$userimage->setUpdatedAt(new \DateTime());
$em->persist($userimage);
$em->flush();
$user->setUserImage($userimage);
$em->persist($user);
$em->flush();
}
$this->mailer->sendEmail($user->getEmail(), $user->getToken());
$this->addFlash("success-registration", "Inscription réussie !");
return $this->redirectToRoute("msgverif", ['id' => $user->getId()]);
}
return $this->render('registration/register1.html.twig', [
'form' => $form->createView(),
'controller_name' => 'Inscrivez-Vous',
'errors' => $errors
]);
}
/**
* @Route("/confirmer-mon-compte/{token}", name="confirm_account")
* @param string $token
*/
public function confirmAccount(string $token)
{
$user = $this->userRepository->findOneBy(["token" => $token]);
if ($user) {
$user->setToken(null);
$user->setEnabled(true);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash("success-activation", "Compte actif !");
return $this->redirectToRoute("app_login");
} else {
$this->addFlash("error", "Ce compte n'exsite pas !");
return $this->redirectToRoute('register');
}
}
/**
* @return string
* @throws \Exception
*/
private function generateToken()
{
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}
/**
* @Route("/inscription/recruiter", name="recruiter_register")
* @param Request $request
* @return Response
*/
public function registerRecruiter(Request $request, SluggerInterface $slugger, ValidatorInterface $validator): Response
{
$userimage = new UserImage();
$user = new User();
$form = $this->createForm(RecruiterFormType::class, $user);
$form->handleRequest($request);
$errors = $validator->validate($user);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword(
$this->passwordEncoder->encodePassword($user, $form->get("password")->getData())
);
$roles = ['ROLE_RECRUITER'];
/** @var UploadedFile $cv */
$logoFile = $form->get('logo')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($logoFile) {
$originalFilename = pathinfo($logoFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $logoFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$logoFile->move(
$this->getParameter('logos_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'cv' property to store the PDF file name
// instead of its contents
$user->setLogo($newFilename);
}
$user->setRoles($roles);
$user->setToken($this->generateToken());
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->mailer->sendEmail($user->getEmail(), $user->getToken());
$this->addFlash("success-registration", "Inscription réussie !");
return $this->redirectToRoute("msgverif", ['id' => $user->getId()]);
}
return $this->render('registration/register_rec.html.twig', [
'form' => $form->createView(),
'errors' => $errors,
'controller_name' => 'Inscrivez-Vous'
]);
}
/**
* @Route("/download/{id}/{cv}",name="pdf_download")
*/
public function downloadAction($cv, $id = null)
{
$cvv = $this->userRepository->find($id);
// dd($cvv);
$downloadedFile = $cvv->getCv();
// dd($downloadedFile);
$response = new Response();
// $response = new Response();
$response->headers->set('Content-type', 'application/octet-stream');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $downloadedFile));
$response->setContent($downloadedFile);
$response->setStatusCode(200);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
return $response;
}
}