src/Controller/ContactController.php line 56

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. ini_set('memory_limit''2G');
  4. use App\Entity\Contact;
  5. use App\Entity\Pcode;
  6. use App\Entity\PcodeCategory;
  7. use App\Entity\Users;
  8. use App\Form\ContactType;
  9. use Doctrine\DBAL\Driver\PDOStatement;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3Validator;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use Symfony\Component\ErrorHandler\Debug;
  17. use Symfony\Component\ErrorHandler\ErrorHandler;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  21. use Symfony\Component\Mailer\MailerInterface;
  22. use Symfony\Component\Routing\Annotation\Route;
  23. use Symfony\Component\Uid\Uuid;
  24. Debug::enable();
  25. ErrorHandler::register();
  26. class ContactController extends AbstractController
  27. {
  28.     private LoggerInterface $logger;
  29.     private MailerInterface $mailer;
  30.     private ParameterBagInterface $bag;
  31.     private ManagerRegistry $managerRegistry;
  32.     /**
  33.      * @param LoggerInterface $logger
  34.      * @param MailerInterface $mailer
  35.      * @param ParameterBagInterface $bag
  36.      * @param ManagerRegistry $managerRegistry
  37.      */
  38.     public function __construct(LoggerInterface $loggerMailerInterface $mailerParameterBagInterface $bag, \Doctrine\Persistence\ManagerRegistry $managerRegistry)
  39.     {
  40.         $this->logger $logger;
  41.         $this->mailer $mailer;
  42.         $this->bag $bag;
  43.         $this->managerRegistry $managerRegistry;
  44.     }
  45.     /**
  46.      * @Route("/contact", name="app_contact")
  47.      */
  48.     public function index(Request $requestRecaptcha3Validator $recaptcha3Validator): Response
  49.     {
  50.         $mailFrom $this->bag->get('mailFrom');
  51.         $mailTo $this->bag->get('notificationMail');
  52.         $mailArray explode(','$mailTo);
  53.         $contact = new Contact();
  54.         $contact->setCreatedAt(new \DateTimeImmutable());
  55.         $contact->setIpAddress($request->getClientIp());
  56.         $contactForm $this->createForm(ContactType::class, $contact);
  57.         $contactForm->handleRequest($request);
  58.         if ($contactForm->isSubmitted() && $contactForm->isValid()) {
  59.             $score $recaptcha3Validator->getLastResponse()->getScore();
  60.             $contact $contactForm->getData();
  61.             $entityManager $this->managerRegistry->getManager();
  62.             $entityManager->persist($contact);
  63.             $entityManager->flush();
  64.             try {
  65.                 //Envoyer un mail de notification au service mokanda
  66.                 $notificationEmail = (new TemplatedEmail())
  67.                     ->from($mailFrom)
  68.                     ->to(...$mailArray)
  69.                     ->subject($contact->getSubject())
  70.                     ->text('Notification de l\'internaute')
  71.                     ->htmlTemplate('contact/sendNotificationMail.html.twig')
  72.                     ->context([
  73.                         'contact' => $contact
  74.                     ]);
  75.                 // Envoyer un mail de réponse à l'internaute
  76.                 $email = (new TemplatedEmail())
  77.                     ->from($this->getParameter('contactFrom'))
  78.                     ->to($contact->getEmail())
  79.                     ->subject($contact->getSubject())
  80.                     ->text('vôtre sujet a été pris en compte, vous serez recontacté très bientôt')
  81.                     ->htmlTemplate('contact/sendmail.html.twig')
  82.                     ->context([
  83.                         'name' => $contact->getName(),
  84.                     ]);
  85.                 $this->mailer->send($notificationEmail);
  86.                 $this->mailer->send($email);
  87.                 $this->addFlash('contact_notification_success''votre message a été envoyé avec succès !');
  88.                 return $this->redirectToRoute('app_contact');
  89.             } catch (TransportExceptionInterface $e) {
  90.                 $this->logger->info('In Exception transport', [$e->getMessage()]);
  91.                 $this->addFlash('contact_notification_error''échec d\'envoi ressayez plus tard ');
  92.                 return $this->redirectToRoute('app_contact');
  93.             }
  94.         }
  95.         return $this->render('contact/index.html.twig', [
  96.             'controller_name' => 'ContactController',
  97.             'contactForm' => $contactForm->createView()
  98.         ]);
  99.     }
  100.     /**
  101.      * @Route("/populate_pcode_db", name="app_contact_file")
  102.      * @throws \Throwable
  103.      */
  104.     public function populateCities(): Response
  105.     {
  106.         // Augmentation de la durée maximale d'exécution
  107.         set_time_limit(600); // 10 minutes
  108.         // Récupération de la catégorie de ville correspondant au niveau 4
  109.         $pcodeCatVille $this->managerRegistry->getRepository(PcodeCategory::class)->findOneBy([
  110.             'level' => 4
  111.         ]);
  112.         // Ouverture du fichier en lecture
  113.         $monFichier dirname(__DIR__) . '/fr.txt';
  114.         $file fopen($monFichier'r');
  115.         // Définition de la taille du lot
  116.         $batchSize 1000;
  117.         $count 0;
  118.         $conn $this->managerRegistry->getManager()->getConnection();
  119.         // Préparation de la requête d'insertion
  120.         $stmt $conn->prepare('INSERT INTO pcode (id, label, parent_id, pcode_category_id) VALUES (?, ?, ?, ?)');
  121.         // Début de la transaction
  122.         $conn->beginTransaction();
  123.         try {
  124.             $lineNumber 0;
  125.             $batch = [];
  126.             // Parcours du fichier ligne par ligne
  127.             while (($line fgets($file)) !== false) {
  128.                 $parts explode("\t"trim($line));
  129.                 // Récupération du code postal correspondant
  130.                 $pcode $this->managerRegistry->getRepository(Pcode::class)->findOneBy([
  131.                     'ccFIPS' => $parts[0]
  132.                 ]);
  133.                 if ($pcode) {
  134.                     // Récupération du nom de la ville
  135.                     $cityName mb_strtolower($parts[2]);
  136.                     // Vérification de l'existence de la ville
  137.                     $existCity $this->managerRegistry->getRepository(Pcode::class)->findOneBy([
  138.                         'pcodeCategory' => $pcodeCatVille,
  139.                         'label' => $cityName
  140.                     ]);
  141.                     if (!$existCity) {
  142.                         $batch[] = [
  143.                             'id' => 'V' uniqid(),
  144.                             'label' => $cityName,
  145.                             'parent_id' => $pcode->getId(),
  146.                             'pcode_category_id' => $pcodeCatVille->getId()
  147.                         ];
  148.                         $count++;
  149.                         if ($count $batchSize === 0) {
  150.                             // Insérer le lot dans la base de données
  151.                             $this->insertBatch($batch$stmt);
  152.                             // Réinitialiser le lot
  153.                             $batch = [];
  154.                             // Commit de la transaction
  155.                             $conn->commit();
  156.                             $conn->beginTransaction();
  157.                         }
  158.                     }
  159.                 }
  160.                 // Libérer la mémoire après chaque itération
  161.                 unset($line$parts$pcode$existCity);
  162.             }
  163.             // Insérer les lignes restantes
  164.             if (!empty($batch)) {
  165.                 $this->insertBatch($batch$stmt);
  166.             }
  167.             // Commit final de la transaction
  168.             $conn->commit();
  169.         } catch (\Throwable $e) {
  170.             // Rollback de la transaction en cas d'erreur
  171.             $conn->rollBack();
  172.             throw $e;
  173.         } finally {
  174.             // Fermeture du fichier
  175.             fclose($file);
  176.         }
  177.         return $this->render('contact/cities_file.html.twig', [
  178.             'controller_name' => 'ContactController',
  179.         ]);
  180.     }
  181.     private function insertBatch(array $batch, \PDOStatement $stmt)
  182.     {
  183.         foreach ($batch as $data) {
  184.             $stmt->bindValue(1$data['id']);
  185.             $stmt->bindValue(2$data['label']);
  186.             $stmt->bindValue(3$data['parent_id']);
  187.             $stmt->bindValue(4$data['pcode_category_id']);
  188.             $stmt->execute();
  189.         }
  190.     }
  191.     private function processBatch($batch$pcodeRepository$pcodeCategory$entityManager)
  192.     {
  193.         $ccFIPSList array_column($batch0);
  194.         $existingPcodes $pcodeRepository->findBy(['ccFIPS' => $ccFIPSList]);
  195.         $existingCities $pcodeRepository->createQueryBuilder('p')
  196.             ->select('p.ccFIPS, LOWER(p.label) AS label')
  197.             ->andWhere('p.pcodeCategory = :category')
  198.             ->andWhere('p.ccFIPS IN (:ccFIPSList)')
  199.             ->setParameter('category'$pcodeCategory)
  200.             ->setParameter('ccFIPSList'$ccFIPSList)
  201.             ->getQuery()
  202.             ->getResult();
  203.         $existingCitiesMap array_combine(array_column($existingCities'ccFIPS'), array_column($existingCities'label'));
  204.         foreach ($batch as [$ccFIPS$label]) {
  205.             $pcode $existingPcodes[array_search($ccFIPSarray_column($existingPcodes'ccFIPS'))] ?? null;
  206.             // Vérifier si le label n'est pas vide ou null
  207.             if (empty(trim($label))) {
  208.                 continue;
  209.             }
  210.             // Vérifier si le label ne contient pas d'espaces inutiles ou de caractères spéciaux
  211.             if (!preg_match('/^[a-zA-Z0-9\s]+$/'$label)) {
  212.                 continue;
  213.             }
  214.             if ($pcode && !isset($existingCitiesMap[$ccFIPS][$label])) {
  215.                 $ville = new Pcode();
  216.                 $ville->setId("V" uniqid());
  217.                 $ville->setLabel($label);
  218.                 $ville->setParent($pcode);
  219.                 $ville->setPcodeCategory($pcodeCategory);
  220.                 $entityManager->persist($ville);
  221.             }
  222.         }
  223.         $entityManager->flush();
  224.         $entityManager->clear();
  225.     }
  226.     /**
  227.      * @Route("/cgu-cgv", name="app_cgu_cgv")
  228.      */
  229.     public function cgu(): Response
  230.     {
  231.         return $this->render('contact/cgu.html.twig', [
  232.             'controller_name' => 'ContactController',
  233.             'is_home' => 'true'
  234.         ]);
  235.     }
  236.     /**
  237.      * @Route("/rgpd", name="app_rgpd")
  238.      */
  239.     public function generateUuid(): Response
  240.     {
  241.         $namespaces Uuid::NAMESPACE_OID;
  242.         $allUsers $this->managerRegistry->getRepository(Users::class)->findAll();
  243.         foreach ($allUsers as $user) {
  244.             $user->setUID(Uuid::v3(Uuid::fromString($namespaces), $user->getMail()??uniqid()));
  245.             $this->managerRegistry->getManager()->persist($user);
  246.         }
  247.         $this->managerRegistry->getManager()->flush();
  248.         return new Response('uuid généré avec succès');
  249.     }
  250. }