src/Controller/AuthController.php line 110

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\DTO\UserDTO;
  4. use App\Entity\ActiviteUser;
  5. use App\Entity\Diplome;
  6. use App\Entity\Enum\EnglishLevel;
  7. use App\Entity\Enum\SkillLevel;
  8. use App\Entity\Experience;
  9. use App\Entity\Skill;
  10. use App\Entity\Society;
  11. use App\Entity\User;
  12. use App\Form\FreelanceRegisterFormType;
  13. use App\Form\RegistrationFormType;
  14. use App\Form\ResetPasswordRequestFormType;
  15. use App\Form\SocietyRegisterFormType;
  16. use App\Security\AppAuthenticator;
  17. use App\Security\EmailVerifier;
  18. use App\Service\Upload\AvatarUploader;
  19. use App\Service\Upload\PDFUploader;
  20. use DateTime;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Exception;
  23. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  24. use Proxies\__CG__\App\Entity\Diplome as AppEntityDiplome;
  25. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  28. use Symfony\Component\Serializer\SerializerInterface;
  29. use Symfony\Component\Validator\Validator\ValidatorInterface;
  30. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  31. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  32. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  33. use Symfony\Component\Form\FormError;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\HttpFoundation\Response;
  36. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  37. use Symfony\Component\Mime\Address;
  38. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. use Symfony\Component\Security\Core\User\UserInterface;
  41. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  42. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  43. class AuthController extends AbstractController
  44. {
  45.     /**
  46.      * @var EmailVerifier
  47.      */
  48.     private $emailVerifier;
  49.     public function __construct(
  50.         EmailVerifier $emailVerifier
  51.     ) {
  52.         $this->emailVerifier $emailVerifier;
  53.     }
  54.     /**
  55.      * @Route("/api/user", name="api_user", methods={"GET"})
  56.      * @IsGranted("ROLE_USER")
  57.      */
  58.     public function getUserInfo(): JsonResponse
  59.     {
  60.         $user $this->getUser();
  61.         dd($user);
  62.         return $this->json([
  63.             'id' => $user->getId(),
  64.             'email' => $user->getEmail(),
  65.         ]);
  66.     }
  67.     /**
  68.      * @Route("/inscription", name="register_freelance")
  69.      * @param Request $request
  70.      * @param UserPasswordHasherInterface $userPasswordHasher
  71.      * @param EntityManagerInterface $entityManager
  72.      * @param UserAuthenticatorInterface $authenticator
  73.      * @param AppAuthenticator $formAuthenticator
  74.      * @return Response|null
  75.      * @throws Exception
  76.      */
  77.     public function registerFreelance(
  78.         Request                     $request,
  79.         UserPasswordHasherInterface $userPasswordHasher,
  80.         EntityManagerInterface      $entityManager,
  81.         UserAuthenticatorInterface  $authenticator,
  82.         AppAuthenticator            $formAuthenticator
  83.     ): ?Response {
  84.         $user = new User();
  85.         $user->setCreatedAt(new DateTime());
  86.         $user->setRoles(['ROLE_FREELANCE']);
  87.         $user->setType('freelance');
  88.         $user->setPhone('');
  89.         $user->setFirstname('');
  90.         $user->setLastname('');
  91.         $form $this->createForm(FreelanceRegisterFormType::class, $user);
  92.         $form->handleRequest($request);
  93.         $isErrorEmail false;
  94.         if ($form->isSubmitted() && $form->isValid()) {
  95.             // $recaptchaToken = $form->get('recaptchaToken')->getData();
  96.             // if (!$this->verifyRecaptcha($recaptchaToken)) {
  97.             //     $this->addFlash('error', 'reCAPTCHA a détecté une activité suspecte.');
  98.             //     return $this->redirectToRoute('register_freelance');
  99.             // }
  100.             $user->setPassword($userPasswordHasher->hashPassword(
  101.                 $user,
  102.                 $form->get('plainPassword')->getData()
  103.             ));
  104.             $entityManager->persist($user);
  105.             $entityManager->flush();
  106.             $activiteUser = new ActiviteUser(
  107.                 "Inscription par mail",
  108.                 $user
  109.             );
  110.             $entityManager->persist($activiteUser);
  111.             $entityManager->flush();
  112.             try {
  113.                 $this->sendConfirmation($user);
  114.                 $this->addFlash('email_validation_send'true);
  115.                 return $authenticator->authenticateUser($user$formAuthenticator$request);
  116.             } catch (Exception $e) {
  117.                 return $authenticator->authenticateUser($user$formAuthenticator$request);
  118.             }
  119.         }
  120.         return $this->render('auth/register_freelance_new.html.twig', [
  121.             'form' => $form->createView(),
  122.             'is_error_mail' => $isErrorEmail
  123.         ]);
  124.     }
  125.     private function verifyRecaptcha(string $recaptchaToken): bool
  126.     {
  127.         $secretKey $this->getParameter('google_recaptcha_secret_key');
  128.         $response file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' $secretKey '&response=' $recaptchaToken);
  129.         $data json_decode($responsetrue);
  130.         return $data['success'] && $data['score'] > 0.5;
  131.     }
  132.     /**
  133.      * @Route("/inscription", name="register")
  134.      */
  135.     public function register(
  136.         Request                     $request,
  137.         UserPasswordHasherInterface $userPasswordHasher,
  138.         EntityManagerInterface      $entityManager,
  139.         UserAuthenticatorInterface  $authenticator,
  140.         AppAuthenticator            $formAuthenticator
  141.     ): ?Response {
  142.         if ($this->getUser()) {
  143.             $user $this->getUser();
  144.             $route $user->isAdmin() ? 'admin_dashboard' 'homepage';
  145.             return $this->redirectToRoute($route);
  146.         }
  147.         $user = new User();
  148.         $user->setCreatedAt(new DateTime());
  149.         $form $this->createForm(RegistrationFormType::class, $user);
  150.         $form->handleRequest($request);
  151.         if ($form->isSubmitted() && $form->isValid()) {
  152.             $form['email']->addError(new FormError('Veuillez saisir un email valide'));
  153.             $user->setPassword($userPasswordHasher->hashPassword(
  154.                 $user,
  155.                 $form->get('plainPassword')->getData()
  156.             ));
  157.             $role $user->isFreelance() ? "ROLE_FREELANCE" "ROLE_SOCIETY";
  158.             $user->setRoles(["ROLE_USER"$role]);
  159.             $entityManager->persist($user);
  160.             $entityManager->flush();
  161.             $this->sendConfirmation($user);
  162.             $this->addFlash('email_validation_send'true);
  163.             return $authenticator->authenticateUser($user$formAuthenticator$request);
  164.         }
  165.         return $this->render('auth/register.html.twig', ['registrationForm' => $form->createView()]);
  166.     }
  167.     /**
  168.      * @Route("/inscription-entreprise", name="register_society")
  169.      */
  170.     public function registerSociety(
  171.         Request                     $request,
  172.         UserPasswordHasherInterface $userPasswordHasher,
  173.         EntityManagerInterface      $entityManager,
  174.         UserAuthenticatorInterface  $authenticator,
  175.         AppAuthenticator            $formAuthenticator
  176.     ): ?Response {
  177.         $user = new User();
  178.         $form $this->createForm(SocietyRegisterFormType::class, $user);
  179.         $form->handleRequest($request);
  180.         if ($form->isSubmitted() && $form->isValid()) {
  181.             $user->setCreatedAt(new DateTime());
  182.             $user->setRoles(['ROLE_SOCIETY']);
  183.             $user->setType('society');
  184.             $user->setPhone($form->get('phone')->getData());
  185.             $user->setPassword($userPasswordHasher->hashPassword(
  186.                 $user,
  187.                 $form->get('plainPassword')->getData()
  188.             ));
  189.             $society = new Society();
  190.             $society->setName($form->get('name')->getData());
  191.             $society->setType($form->get('typeSociete')->getData());
  192.             $society->setCa(0);
  193.             $society->setAdress('');
  194.             $society->setVille('');
  195.             $society->setDescription('');
  196.             $society->setPhone('');
  197.             $society->setNbMission($form->get('nb_mission')->getData());
  198.             $society->setPostIntercontrat($form->get('post_intercontrat')->getData());
  199.             $user->setPhone($form->get('phone')->getData());
  200.             $society->setUser($user);
  201.             $entityManager->persist($user);
  202.             $entityManager->persist($society);
  203.             $entityManager->flush();
  204.             $society->updateSlug();
  205.             $entityManager->persist($society);
  206.             $entityManager->flush();
  207.             //            $this->sendConfirmation($user);
  208.             //            $this->addFlash('email_validation_send', true);
  209.             /* @changeLog 2022-11-03 [FIX] (Anthony) Mise en place d'une redirection après inscription compte entreprise */
  210.             $this->addFlash('success''Votre compte entreprise a été créé avec succès, notre équipe va vous contacter rapidement pour la validation de votre compte.');
  211.             return $this->redirectToRoute('login');
  212.         }
  213.         return $this->render('auth/register_society_new.html.twig', [
  214.             'form' => $form->createView(),
  215.         ]);
  216.     }
  217.     /**
  218.      * @Route("/verify/resend", name="resend_verification")
  219.      */
  220.     public function resendVerificationEmail(Request $request): Response
  221.     {
  222.         if ($this->getUser()) {
  223.             $this->sendConfirmation($this->getUser());
  224.             return $this->redirectToRoute('dashboard');
  225.         }
  226.         return $this->redirectToRoute('homepage');
  227.     }
  228.     private function sendConfirmation(UserInterface $user)
  229.     {
  230.         $this->emailVerifier->sendEmailConfirmation(
  231.             'verify_email',
  232.             $user,
  233.             (new TemplatedEmail())
  234.                 ->from(new Address('ne-pas-repondre@workdispo.com''workdispo.com'))
  235.                 ->to($user->getEmail())->subject('Veuillez confirmer votre email')
  236.                 ->htmlTemplate('emails/confirmation_email.html.twig')
  237.         );
  238.     }
  239.     /**
  240.      * @Route("/verify/email", name="verify_email")
  241.      */
  242.     public function verifyUserEmail(Request $request): Response
  243.     {
  244.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  245.         // validate email confirmation link, sets User::isVerified=true and persists
  246.         try {
  247.             $this->emailVerifier->handleEmailConfirmation($request$this->getUser());
  248.         } catch (VerifyEmailExceptionInterface $exception) {
  249.             $this->addFlash('verify_email_error'$exception->getReason());
  250.             return $this->redirectToRoute('register');
  251.         }
  252.         // return $this->redirectToRoute('dashboard');
  253.         return $this->redirectToRoute('dashboard');
  254.     }
  255.     /**
  256.      * @Route("/connexion", name="login")
  257.      */
  258.     public function login(AuthenticationUtils $authenticationUtils): Response
  259.     {
  260.         if ($this->getUser()) {
  261.             /** @var User $user */
  262.             $user $this->getUser();
  263.             $route $user->isAdmin() ? 'admin_dashboard' 'homepage';
  264.             return $this->redirectToRoute($route);
  265.         }
  266.         $resetForm $this->createForm(ResetPasswordRequestFormType::class);
  267.         // get the login error if there is one
  268.         $error $authenticationUtils->getLastAuthenticationError();
  269.         // last username entered by the user
  270.         $lastUsername $authenticationUtils->getLastUsername();
  271.         return $this->render('auth/login.html.twig', [
  272.             'last_username' => $lastUsername,
  273.             'error' => $error,
  274.             'resetForm' => $resetForm->createView(),
  275.         ]);
  276.     }
  277.     /**
  278.      * @Route("/deconnexion", name="logout")
  279.      */
  280.     public function logout(): Response
  281.     {
  282.         return $this->redirectToRoute('homepage');
  283.     }
  284.     /**
  285.      * @Route("/api/register", name="api_register", methods={"POST"})
  286.      */
  287.     public function apiRegister(
  288.         Request                     $request,
  289.         UserPasswordHasherInterface $passwordHasher,
  290.         EntityManagerInterface      $entityManager,
  291.         SerializerInterface         $serializer,
  292.         ValidatorInterface          $validator,
  293.         JWTTokenManagerInterface    $jwtManager
  294.     ): JsonResponse {
  295.         $data $request->getContent();
  296.         // Désérialiser les données JSON en DTO
  297.         $userDTO $serializer->deserialize($dataUserDTO::class, 'json');
  298.         // Valider les données du DTO
  299.         $errors $validator->validate($userDTO);
  300.         $errorMessages = [];
  301.         if (count($errors) > 0) {
  302.             foreach ($errors as $error) {
  303.                 $errorMessages[] = $error->getMessage();
  304.             }
  305.         }
  306.         // Vérifier si l'email existe déjà
  307.         if ($entityManager->getRepository(User::class)->findOneBy(['email' => $userDTO->email])) {
  308.             $errorMessages[] = 'Cet email est déjà utilisé.';
  309.         }
  310.         // S'il y a des erreurs, on les retourne sous forme d'un tableau
  311.         if (!empty($errorMessages)) {
  312.             return new JsonResponse(['errors' => $errorMessages], Response::HTTP_BAD_REQUEST);
  313.         }
  314.         // Création de l'utilisateur
  315.         $user = new User();
  316.         $user->setCreatedAt(new DateTime());
  317.         $user->setRoles(['ROLE_FREELANCE']);
  318.         $user->setType('freelance');
  319.         $user->setPhone('');
  320.         $user->setFirstname('');
  321.         $user->setLastname('');
  322.         $user->setEmail($userDTO->email);
  323.         $user->setPassword($passwordHasher->hashPassword($user$userDTO->password));
  324.         $entityManager->persist($user);
  325.         $entityManager->flush();
  326.         // Génération du token JWT
  327.         $token $jwtManager->create($user);
  328.         return new JsonResponse([
  329.             'message' => 'Inscription réussie.',
  330.             'token'   => $token
  331.         ], Response::HTTP_CREATED);
  332.     }
  333.     /**
  334.      * @Route("/api/checkProfile", name="api_check_profile", methods={"GET"})
  335.      * @IsGranted("ROLE_FREELANCE")
  336.      */
  337.     public function checkProfile(Request $request): JsonResponse
  338.     {
  339.         $user $this->getUser();
  340.         $profile $user->hasProfile();
  341.         if (!$profile) {
  342.             return new JsonResponse(['message' => 'Profil non renseigné.'], Response::HTTP_BAD_REQUEST);
  343.         }
  344.         return new JsonResponse(['message' => 'Profil renseigné.'], Response::HTTP_OK);
  345.     }
  346.     /**
  347.      * @Route("/api/checkProfileFinished", name="api_check_profile_finished", methods={"GET"})
  348.      * @IsGranted("ROLE_FREELANCE")
  349.      */
  350.     public function checkProfileFinished(Request $request): JsonResponse
  351.     {
  352.         $user $this->getUser();
  353.         $profile $user->hasProfile();  
  354.               
  355.         if (!$profile) {
  356.             return new JsonResponse(['message' => 'Profil non renseigné.'], Response::HTTP_BAD_REQUEST);
  357.         }
  358.         $finished $user->getUniqueProfile()->getFinished();
  359.         if ($finished === || $finished === false) {
  360.             return new JsonResponse(['message' => 'Profil non terminé.'], Response::HTTP_BAD_REQUEST);
  361.         }
  362.         return new JsonResponse(['message' => 'Profil terminé.'], Response::HTTP_OK);
  363.     }
  364.     /**
  365.      * @Route("/api/complete_before", name="complete_resume_profile_before_api", methods={"POST"})
  366.      * @IsGranted("ROLE_FREELANCE")
  367.      */
  368.     public function completeResumeBeforeApi(
  369.         Request                $request,
  370.         EntityManagerInterface $entityManager,
  371.         PDFUploader            $pdfUploader,
  372.         AvatarUploader         $avatarUploader,
  373.         SessionInterface       $session
  374.     ): Response {
  375.         /* @var User $user */
  376.         $user $this->getUser();
  377.         $profile $user->getUniqueProfile();
  378.         // REDIRECT IF COMPLETE
  379.         if ($profile->getTitle()) {
  380.             return $this->json(['message' => 'Profil déjà renseigné.'], Response::HTTP_BAD_REQUEST);
  381.         }
  382.         $profile->setContrats(null);
  383.         $profile->setIsVisible(true);
  384.         $isNew false;
  385.         if (!$profile->getId()) {
  386.             $isNew true;
  387.             $profile->setUrl($profile->getName());
  388.         }
  389.         $jsonData $session->get('generated_content'null);
  390.         $cvFile $session->get('cv_file');
  391.         $profile->setCvname($cvFile);
  392.         $profile->setCvFile($cvFile);
  393.         $profile->setCdi('Non');
  394.         $profile->setDisponibility('Immédiate');
  395.         $data json_decode($jsonDatatrue);
  396.         // dd($data['Compétences']);
  397.         if (!empty($data['Compétences'])) {
  398.             foreach ($data['Compétences'] as $competence => $levelName) {
  399.                 $newCompetence = new Skill();
  400.                 $newCompetence->setName($competence);
  401.                 // Utilisation de SkillLevel::LIST pour convertir le nom du niveau en entier
  402.                 $level is_string($levelName) && isset(SkillLevel::LIST[$levelName])
  403.                     ? SkillLevel::LIST[$levelName]
  404.                     : SkillLevel::BEGINNER;
  405.                 // Par défaut 'Débutant' si le niveau n'est pas trouvé
  406.                 $newCompetence->setLevel($level);
  407.                 $profile->addSkill($newCompetence);
  408.             }
  409.         }
  410.         (!empty($data['tjm']) && $data['tjm'] != '') ? $profile->setCost((int)$data['tjm']) : $profile->setCost(0);
  411.         (!empty($data['region']) && $data['region'] != '') ? $profile->setMobility([$data['region']]) : $profile->setMobility(["Toute la France"]);
  412.         (!empty($data['anglais'])) ? $profile->setEnglishLevel($data['anglais']) : $profile->setEnglishLevel(EnglishLevel::NOTION);
  413.         // !empty($data['legalStatus']) ? $profile->setLegalStatus($data['legalStatus']) : $profile->setLegalStatus(LegalStatus::RELFEXION);
  414.         !empty($data['legalStatus']) && $data['legalStatus'] !== "En réflexion" $profile->setLegalStatus($data['legalStatus']) : $profile->setLegalStatus('');
  415.         (!empty($data['année_experience'])) ? $profile->setExperienceNumber($data['année_experience']) : $profile->setExperienceNumber('N/A');
  416.         (!empty($data['cp_ville'])) ? $profile->setLocation($data['cp_ville']) : $profile->setLocation('N/A');
  417.         (!empty($data['Poste'])) ? $profile->setTitle($data['Poste']) : $profile->setTitle('N/A');
  418.         (!empty($data['nom'])) ? $profile->setName($data['nom']) : $profile->setName('Anonyme');
  419.         (!empty($data['prenom'])) ? $profile->setFirstname($data['prenom']) : $profile->setFirstname('Anonyme');
  420.         if (isset($data['diplômes'])) {
  421.             $diplomeData $data['diplômes'];
  422.         } else {
  423.             $diplomeData null// Ou définir une valeur par défaut appropriée
  424.         }
  425.         // dd($diplomeData);
  426.         if (!empty($diplomeData)) {
  427.             $newDiplome = new Diplome();
  428.             if (array_values($diplomeData) !== $diplomeData) {
  429.                 $newDiplome->setTitle($diplomeData['title'])
  430.                     ->setUniversity($diplomeData['university'] ?? '')
  431.                     ->setLevel($diplomeData['level'] ?? '');
  432.                 if (isset($diplomeData['obtentionYear']) && is_numeric($diplomeData['obtentionYear'])) {
  433.                     $obtentionYear = (int)$diplomeData['obtentionYear'];
  434.                     error_log('Obtention Year: ' $obtentionYear);
  435.                     $newDiplome->setObtentionYear($obtentionYear);
  436.                 }
  437.                 $profile->addDiplome($newDiplome);
  438.             } else {
  439.                 foreach ($diplomeData as $diplome) {
  440.                     $newDiplome->setTitle($diplome['title'])
  441.                         ->setUniversity($diplome['university'] ?? '')
  442.                         ->setLevel($diplome['level'] ?? '');
  443.                     if (isset($diplome['obtentionYear']) && is_numeric($diplome['obtentionYear'])) {
  444.                         $obtentionYear = (int)$diplome['obtentionYear'];
  445.                         error_log('Obtention Year: ' $obtentionYear);
  446.                         $newDiplome->setObtentionYear($obtentionYear);
  447.                     }
  448.                     $profile->addDiplome($newDiplome);
  449.                 }
  450.             }
  451.         }
  452.         $profile->setPhone(empty(json_decode($jsonDatatrue)['telephone'] ?? 'N/A') ?? $profile->setPhone('Non spécifié'));
  453.         if (isset($data['experience'])) {
  454.             $experienceData $data['experience'];
  455.         } else {
  456.             $experienceData null// Ou définir une valeur par défaut appropriée
  457.         }
  458.         if (!empty($experienceData)) {
  459.             if (isset($experienceData['title'])) {
  460.                 // Single $experienceDataapeta object, handle it directly
  461.                 $experienceData = [$experienceData];
  462.             }
  463.             // Process the JSON data and add experiences to the profile
  464.             foreach ($experienceData as $experience) {
  465.                 $newExperience = new Experience();
  466.                 $newExperience->setEmployer($experience['employer'] ?? '');
  467.                 // Set end_at to the last day of the current year if empty
  468.                 if (empty($experience['end_at'])) {
  469.                     $currentYear date('Y');
  470.                     $endAt = new \DateTime("$currentYear-12-31");
  471.                 } else {
  472.                     try {
  473.                         $endAt = new \DateTime($experience['end_at']);
  474.                     } catch (\Exception $e) {
  475.                         // Handle invalid date format by setting a default date
  476.                         $endAt = new \DateTime("$currentYear-12-31");
  477.                     }
  478.                 }
  479.                 $newExperience->setEndAt($endAt);
  480.                 if (isset($experience['environment_tech'])) {
  481.                     if (is_array($experience['environment_tech'])) {
  482.                         $environmentTech implode(', '$experience['environment_tech']);
  483.                     } else {
  484.                         $environmentTech $experience['environment_tech'];
  485.                     }
  486.                 } else {
  487.                     $environmentTech ''// Valeur par défaut si 'environment_tech' n'existe pas
  488.                 }
  489.                 if (isset($experience['missions'])) {
  490.                     if (is_array($experience['missions'])) {
  491.                         // Convertir le tableau en chaîne de caractères avec des sauts de ligne
  492.                         $missions implode("\n"$experience['missions']);
  493.                     } else {
  494.                         // Vérifier si 'missions' est déjà une chaîne de caractères
  495.                         $missions $experience['missions'];
  496.                     }
  497.                 } else {
  498.                     // Définir une valeur par défaut si 'missions' n'existe pas
  499.                     $missions '';
  500.                 }
  501.                 try {
  502.                     $startAt = isset($experience['start_at']) ? new \DateTime($experience['start_at']) : new \DateTime();
  503.                 } catch (\Exception $e) {
  504.                     // Utiliser une date par défaut ou gérer l'erreur
  505.                     $startAt = new \DateTime(); // Date actuelle ou une autre valeur par défaut
  506.                 }
  507.                 $newExperience->setEnvironment($environmentTech)
  508.                     ->setMissions($missions)
  509.                     ->setStartAt($startAt);
  510.                 // Assurez-vous que 'title' est toujours une chaîne de caractères
  511.                 $title $experience['title'] ?? '';
  512.                 if (!is_string($title)) {
  513.                     $title '';
  514.                 }
  515.                 $newExperience->setTitle($title);
  516.                 $profile->addExperience($newExperience);
  517.             }
  518.         }
  519.         // Vérifier si la clé 'certifications' existe
  520.         if (isset($data['certifications'])) {
  521.             $certificationData $data['certifications'];
  522.         } else {
  523.             $certificationData null// Ou définir une valeur par défaut appropriée
  524.         }
  525.         if (isset($data['anglais'])) {
  526.             $anglais $data['anglais'];
  527.             // Mapper des valeurs possibles aux niveaux de la classe
  528.             $levelMapping = [
  529.                 'notions' => EnglishLevel::NOTION,
  530.                 'technique' => EnglishLevel::TECHNIQUE,
  531.                 'courant' => EnglishLevel::COURANT,
  532.             ];
  533.             $englishLevel $levelMapping[strtolower($anglais)] ?? EnglishLevel::NOTION;  // Niveau par défaut
  534.             // dd($englishLevel);
  535.             $profile->setEnglishLevel($englishLevel);
  536.         }
  537.         if (!empty($certificationData)) {
  538.             foreach ($certificationData as $certification) {
  539.                 $newCertification = new Certification();
  540.                 $newCertification->setTitle($certification['title'] ?? '')
  541.                     ->setEtablissement($certification['etablissement'] ?? '');
  542.                 // Vérification et conversion de l'année d'obtention
  543.                 if (isset($certification['obtention_year']) && is_numeric($certification['obtention_year'])) {
  544.                     $obtentionYear = (int)$certification['obtention_year'];
  545.                     error_log('Obtention Year: ' $obtentionYear);
  546.                     $newCertification->setObtentionYear($obtentionYear);
  547.                 } else {
  548.                     // Définir une valeur par défaut appropriée ou gérer l'erreur
  549.                     error_log('Invalid Obtention Year: ' . (isset($certification['obtention_year']) ? $certification['obtention_year'] : 'not set'));
  550.                     $newCertification->setObtentionYear(0);
  551.                 }
  552.                 $profile->addCertification($newCertification);
  553.             }
  554.         }
  555.         // Vérifier si la clé 'certifications' existe
  556.         if (isset($data['présentation'])) {
  557.             $presentationData $data['présentation'];
  558.         } else {
  559.             $presentationData null// Ou définir une valeur par défaut appropriée
  560.         }
  561.         if (!empty($presentationData)) {
  562.             $profile->setAbout($presentationData);
  563.         }
  564.         if (isset($data['url_Linkedin'])) {
  565.             $linkedInData $data['url_Linkedin'];
  566.         } else {
  567.             $linkedInData null// Ou définir une valeur par défaut appropriée
  568.         }
  569.         if (!empty($linkedInData)) {
  570.             $profile->setLinkedin($linkedInData);
  571.         }
  572.         $profile->setFinished(false);
  573.         $profile->setProfileType(0);
  574.         // dump($jsonData);
  575.         // dd($profile);
  576.         $entityManager->flush();
  577.         if (empty($user->getFirstname())) {
  578.             $user->setFirstname($profile->getFirstname());
  579.             $entityManager->persist($user);
  580.         }
  581.         if (empty($user->getLastname())) {
  582.             $user->setLastname($profile->getName());
  583.             $entityManager->persist($user);
  584.         }
  585.         $profile->updateSlug();
  586.         $entityManager->persist($profile);
  587.         $entityManager->flush();
  588.         return $this->json(['message' => 'Profile updated successfully']);
  589.     }
  590.     /**
  591.      * @Route("/api/getProfile", name="api_get_profile", methods={"GET"})
  592.      * @IsGranted("ROLE_FREELANCE")
  593.      */
  594.     public function getProfile(Request $requestEntityManagerInterface $entityManager): JsonResponse
  595.     {
  596.         $user $this->getUser();
  597.         $profile $user->getUniqueProfile();
  598.         if (!$profile) {
  599.             return new JsonResponse(['message' => 'Profil non renseigné.'], Response::HTTP_BAD_REQUEST);
  600.         }
  601.         $serializer $this->container->get('serializer');
  602.         $data $serializer->serialize($profile'json', [
  603.             'circular_reference_handler' => function ($object) {
  604.                 return $object->getId(); // ou retourne une propriété unique de ton objet
  605.             },
  606.         ]);
  607.         return new JsonResponse(['data' => json_decode($data)], Response::HTTP_OK);
  608.     }
  609. }