src/EventSubscriber/EasyAdminSubscriber.php line 295

Open in your IDE?
  1. <?php
  2. # src/EventSubscriber/EasyAdminSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Entity\User;
  5. use App\Entity\Action;
  6. use App\Entity\Societe;
  7. use App\Entity\TextLoi;
  8. use App\Entity\BlogPost;
  9. use App\Entity\TextSociete;
  10. use Symfony\Component\Mime\Email;
  11. use App\Repository\SocieteRepository;
  12. use App\Repository\TextLoiRepository;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use App\Repository\TextSocieteRepository;
  15. use App\Service\Message\SendEmailMessage;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\Security\Core\Security;
  18. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  19. use Symfony\Component\HttpFoundation\RequestStack;
  20. use Symfony\Component\Messenger\MessageBusInterface;
  21. use App\Service\Mailer\EmailFactory\AideEmailFactory;
  22. use Symfony\Component\Security\Core\User\UserInterface;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. use App\Service\Mailer\EmailFactory\NouveauTextLoiEmailFactory;
  25. use App\Service\Mailer\EmailFactory\NouvelleActionEmailFactory;
  26. use EasyCorp\Bundle\EasyAdminBundle\Config\Action as ActionAdm;
  27. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  28. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  29. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityBuiltEvent;
  30. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  31. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  32. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  33. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  34. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  35. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  36. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  37. class EasyAdminSubscriber implements EventSubscriberInterface
  38. {
  39.     private $passwordHasher;
  40.     private $entityManager;
  41.     private $textLoiRepository;
  42.     private $security;
  43.     private $societeRepository;
  44.     private $textSocieteRepository;
  45.     private $session;
  46.     private $mailer;
  47.     private $ancienStatut;
  48.     private $parameterBag;
  49.     private $nouvelleActionEmailFactory;
  50.     private $nouveauTextLoiEmailFactory;
  51.     private $messageBus
  52.     private $requestStack;
  53.     public function __construct(
  54.         UserPasswordHasherInterface $passwordHasher,
  55.         EntityManagerInterface $em,
  56.         TextLoiRepository $textLoiRepository,
  57.         SocieteRepository $societeRepository,
  58.         TextSocieteRepository $textSocieteRepository,
  59.         Security $security,
  60.         SessionInterface $session,
  61.         MailerInterface $mailer,
  62.         ParameterBagInterface $parameterBag,
  63.         NouvelleActionEmailFactory $nouvelleActionEmailFactory,
  64.         MessageBusInterface $messageBus,
  65.         NouveauTextLoiEmailFactory $nouveauTextLoiEmailFactory,
  66.         RequestStack $requestStack
  67.     ) {
  68.         $this->nouvelleActionEmailFactory $nouvelleActionEmailFactory;
  69.         $this->parameterBag $parameterBag;
  70.         $this->passwordHasher $passwordHasher;
  71.         $this->entityManager $em;
  72.         $this->textLoiRepository $textLoiRepository;
  73.         $this->societeRepository $societeRepository;
  74.         $this->textSocieteRepository $textSocieteRepository;
  75.         $this->security $security;
  76.         $this->session $session;
  77.         $this->mailer $mailer;
  78.         $this->messageBus $messageBus;
  79.         $this->requestStack $requestStack;
  80.         $this->nouveauTextLoiEmailFactory $nouveauTextLoiEmailFactory;
  81.     }
  82.     public static function getSubscribedEvents()
  83.     {
  84.         return [
  85.             BeforeEntityPersistedEvent::class => ['beforeEntityPersisted'],
  86.             AfterEntityPersistedEvent::class  => ['afterEntityPersisted'],
  87.             BeforeEntityUpdatedEvent::class   => ['beforeEntityUpdated'],
  88.             AfterEntityUpdatedEvent::class    => ['afterEntityUpdated'],
  89.             AfterCrudActionEvent::class       => ['afterCrudAction'],
  90.             BeforeCrudActionEvent::class      => ['beforeCrudAction'],
  91.             // AfterEntityBuiltEvent::class =>  ['test'],
  92.             //  AfterEntityBuiltEvent::class =>  ['test3'],
  93.             // AfterEntityBuiltEvent::class =>   ['testAfterEntityBuilt']
  94.         ];
  95.     }
  96.     /*  public  function test($event)
  97.     {
  98.         $entity = $event->getEntityInstance();
  99.         if ($entity instanceof Action) {
  100.         
  101.         dd($entity);
  102.         }
  103.     }*/
  104.     public function afficheFlashMessage(AfterEntityUpdatedEvent $event)
  105.     {
  106.         $entity $event->getEntityInstance();
  107.         dd($entity);
  108.         /*  $this->sessionInterface->getFlashBag()->add(
  109.             'warning',
  110.             'Your config file is writable, it should be set read-only'
  111.         );*/
  112.     }
  113.     /* public function affecterTextGenerale(BeforeEntityPersistedEvent $event){
  114.         $entity = $event->getEntityInstance();
  115.         if ($entity instanceof TextLoi) {
  116.             if(($action == Crud::PAGE_EDIT || $action == Crud::PAGE_INDEX)) ){
  117.             }
  118.         }
  119.     }*/
  120.     public function beforeEntityPersisted(BeforeEntityPersistedEvent $event)
  121.     {
  122.         $entity $event->getEntityInstance();
  123.         if ($entity instanceof User) {
  124.             $this->updatePassword($entity);
  125.         }
  126.         if ($entity instanceof Societe) {
  127.             $this->updatePassword($entity->getUser());
  128.         }
  129.     }
  130.     public function beforeEntityUpdated(BeforeEntityUpdatedEvent $event)
  131.     {
  132.         $entity $event->getEntityInstance();
  133.      /* cette instruction provoque le cryptage d'un mot de passe deja crypté 
  134.         if ($entity instanceof Societe) {
  135.             $this->updatePassword($entity->getUser());
  136.         }*
  137.         /*   if($entity instanceof TextSociete)
  138.         {
  139.             $id = $entity->getId();
  140.             $texts = $this->textSocieteRepository->find($id);
  141.             dd("Ancien :".$texts->getStatutConformite()."---Nouveau: ".$entity->getStatutConformite());
  142.             dd($event);
  143.             dd($entity);
  144.         }*/
  145.     }
  146.     public function updatePassword($user)
  147.     {
  148.         $user->setPassword($this->passwordHasher->hashPassword($user$user->getPassword()));
  149.     }
  150.     public function beforeCrudAction(BeforeCrudActionEvent $event)
  151.     {
  152.         $context $event->getAdminContext();
  153.         //dd($context);
  154.         $entity $context->getEntity()->getName();
  155.         // dd($entity);
  156.         $action $context->getCrud()->getCurrentAction();
  157.         if ($entity == 'TextSociete' && $action == 'edit') {
  158.             $instance $entity $context->getEntity()->getInstance();
  159.             $statut $instance->getStatutConformite();
  160.             $this->ancienStatut $statut;
  161.             // dd($statut);
  162.            // dd($instance);
  163.         }
  164.         //dd($action);
  165.         //dd($entity);
  166.         /*  $currentSociete = $context->getUser()->getSociete();
  167.         //dd($action);
  168.         //dd($entity);
  169.         if ($entity == "TextLoi" && ($action == Crud::PAGE_EDIT || $action == Crud::PAGE_INDEX)) {
  170.             $entities = $this->textLoiRepository->findAll();
  171.             //dd($entities);
  172.             $liste = $this->textLoiRepository->listeTextLois($currentSociete);
  173.             foreach ($entities as $i => $text) {
  174.                 //  $textSoc = $this->entityManager->getRepository(TextSociete::class)->findOneBy(['societe' => $currentSociete, 'textLoi' => $text]);
  175.                 if ($liste[$i]['id2'] !== null) {
  176.                     $text->setAffected(true);
  177.                 } else {
  178.                     $text->setAffected(false);
  179.                 }*/
  180.         //dd($textSoc);
  181.         /*   if ($textSoc) {
  182.                     $textSoc->getSociete();
  183.                     $text->setSociete($textSoc->getSociete());
  184.                     // dd($text);
  185.                 } 
  186.                 else
  187.                 {
  188.                     $text->setSociete(null);
  189.                 }*/
  190.         /*     }
  191.        }*/
  192.     }
  193.     public function afterCrudAction(AfterCrudActionEvent $event)
  194.     {
  195.         //dd($event->getAdminContext()->getRequest()->query->get('crudControllerFqcn'));
  196.         $entities $event->getResponseParameters('entities')->get('entities');
  197.         // $entities->offsetUnset(159);
  198.         //  dd($entities);
  199.         // dd($event->getResponseParameters('entities')->get('entities'));//->get(159));
  200.         $context $event->getAdminContext();
  201.         $entityName $context->getEntity()->getName();
  202.         $user $context->getUser();
  203.         $currentSociete = ($user instanceof \App\Entity\User) ? $user->getSociete() : null;
  204.         $roles $user $user->getRoles() : [];
  205.         // $entity = $event->getEntityInstance();
  206.         //$CrudControllers = $context->getCrudControllers();
  207.         $CrudControllerFqcn $event->getAdminContext()->getRequest()->query->get('crudControllerFqcn');
  208.         $action $context->getCrud()->getCurrentAction();
  209.         // dd($action);
  210.         if ($action == ActionAdm::INDEX && $CrudControllerFqcn == "App\Controller\User\TextSocieteEvalueCandidatConformeCrudController") {
  211.             $keys = [];
  212.             foreach ($entities as $key => $entity) {
  213.                 foreach ($entity->getFields() as $field) {
  214.                     if ($field->getProperty() == "candidatConforme" && $field->getValue() == false) {
  215.                         // $entities->offsetUnset($key);
  216.                         $keys[] = $key;
  217.                         // dd();
  218.                     }
  219.                 }
  220.             }
  221.             foreach ($keys as $key) {
  222.                 $entities->offsetUnset($key);
  223.             }
  224.             // dd($keys);
  225.             // dd($entities);
  226.         }
  227.         /* if ($entity == "TextLoi" && $action == Crud::PAGE_INDEX) {
  228.             //  $entities = $this->entityManager->getRepository(TextLoi::class)->listeTextLois($currentSociete);
  229.             $entities = $this->textLoiRepository->listeTextLois($currentSociete);
  230.             // dd($entities);
  231.             // Evoi du tableau $entities au template
  232.             $event->addResponseParameters(['liste' => $entities]);
  233.         }*/
  234.         if ($entityName == "TextLoi") {
  235.             switch ($action) {
  236.                 case Crud::PAGE_DETAIL:
  237.                     //dd($context->getCrud());
  238.                     //dd($context->getEntity()->getInstance());
  239.                     if (!in_array("ROLE_SUPER_ADMIN"$roles)) {
  240.                         // dd("ici".$CrudControllers);
  241.                         $textLoi $context->getEntity()->getInstance();
  242.                         // dd($textLoi->isViewedBySociete($currentSociete));
  243.                         $textLoi->addVueParSociete($currentSociete);
  244.                         $this->entityManager->flush();
  245.                     }
  246.                     break;
  247.                 default:
  248.                     # code...
  249.                     break;
  250.             }
  251.         }
  252.     }
  253.     private function notifierSocietesNewTextLoi(TextLoi $textLoi)
  254.     {
  255.         // Add logic to notify societies about the new TextLoi
  256.         // Example: Log the notification or send an email
  257.        // $currentDate = new \DateTime();
  258.         $societes $this->societeRepository->SocietesAvecAbonnementValide();
  259.        //$societes[0] = $this->societeRepository->find(1);
  260.         foreach ($societes as $societe) {
  261.            if ($this->parameterBag->get('app.mailing_activeted')) {
  262.             $email $this->nouveauTextLoiEmailFactory->create($textLoi,$societe);
  263.             $this->messageBus->dispatch(
  264.                 new SendEmailMessage($email) );
  265.            $this->requestStack->getSession()->getFlashBag()->add('success''Un email est envoyé au responsable de l\'action...');
  266.            }
  267.             else
  268.             {
  269.                 $this->session->get('flashes')->add('warning'"L'envoi des messages est désactivé.");
  270.             }
  271.         }
  272.     }
  273.     public function afterEntityPersisted(AfterEntityPersistedEvent $event)
  274.     {
  275.         $entity $event->getEntityInstance();
  276.         if ($entity instanceof TextLoi) {
  277.             $this->affectTextLoiAuxSocietes($entity);
  278.             $this->notifierSocietesNewTextLoi($entity);
  279.             
  280.         }
  281.         if ($entity instanceof Action) {
  282.             $this->sendMailToResponsable($entity'Nouvelle Action à réaliser');
  283.         }
  284.         if ($entity instanceof Societe) {
  285.             $this->initMaBaseWithGeneralTextes($entity);
  286.         }
  287.     }
  288.     /*
  289.     * Ajouter les textes généreaux à la base de la societé récement créée
  290.     * Créer le dossier des pièces justificatifs (realisee et efficace)
  291.     */
  292.     private function initMaBaseWithGeneralTextes(Societe $societe)
  293.     {
  294.         //Affecter les textes généraux à la société
  295.         $generals_texts $this->textLoiRepository->findBy(['generale' => true]);
  296.         //$socId = $entity->getId();
  297.         //dd($generals_texts);
  298.         foreach ($generals_texts as $textLoi) {
  299.             $textSociete = new TextSociete();
  300.             $textSociete->setSociete($societe);
  301.             $textSociete->setTextLoi($textLoi);
  302.             $textSociete->setStatutConformite(TextSociete::CONFORMITE_NON_EVALUE);
  303.             //$textSociete->setDateConformite(null);
  304.             $textSociete->setCreatedAt(new \DateTime());
  305.             $textSociete->setApplicabilite(TextSociete::APPLICABILITE_APPLICATION);
  306.             $textLoi->addVueParSociete($societe);
  307.             $this->entityManager->persist($textSociete);
  308.         }
  309.         $this->entityManager->flush();
  310.         $this->session->get('flashes')->add(
  311.             'success',
  312.             'La base de la société '.$societe->getName().' à été initialisée avec tous les textes généraux'
  313.         );
  314.         // Creation du dossier pj/idsoc/realisee et pj/idsoc/efficace
  315.         $id $societe->getId();
  316.         if(!file_exists('pj/'.$id)){
  317.            mkdir('pj/'.$id,0777,true);
  318.            mkdir('pj/'.$id.'/efficace',0777,true);
  319.            mkdir('pj/'.$id.'/realisee',0777,true);
  320.         }
  321.         
  322.     }
  323.     private function sendMailToResponsable(Action $action$subject)
  324.     {
  325.         if ($this->parameterBag->get('app.mailing_activeted')) {
  326.             $email $this->nouvelleActionEmailFactory->create($action);
  327.             $this->messageBus->dispatch(
  328.                 new SendEmailMessage($email) );
  329.            // $this->session->get('flashes')->add('success', 'Votre Message a été envoyé avec succès');
  330.            // $this->addFlash('success', 'Enregistrement effectué avec succès');
  331.            $this->requestStack->getSession()->getFlashBag()->add('success''Un email est envoyé au responsable de l\'action...');
  332.            }
  333.         else
  334.         {
  335.             $this->session->get('flashes')->add('warning'"L'envoi des messages est désactivé.");
  336.         }
  337.         /*$email = (new Email())
  338.             ->from('khediril@gmail.com')
  339.             ->to($action->getEmailResponsable())
  340.             //->cc('cc@example.com')
  341.             //->bcc('bcc@example.com')
  342.             //->replyTo('fabien@example.com')
  343.             ->priority(Email::PRIORITY_HIGH)
  344.             ->subject($subject)
  345.             //  ->text($message)
  346.             ->html($message);*/
  347.         //dd($this->mailer);
  348.         /* TODO: Activé pour envoi email en csa de modification email */
  349.         ///// réactiver pour envoi de mail
  350.         //   $this->mailer->send($email);
  351.         //     $this->session->getFlashBag()->add(
  352.         //    'success',
  353.         //    'Un Message a été envoyé au responsable de l\'action avec succés...'
  354.         //);
  355.     }
  356.     public function afterEntityUpdated(AfterEntityUpdatedEvent $event)
  357.     {
  358.         $entity $event->getEntityInstance();
  359.         if ($entity instanceof TextLoi) {
  360.             $this->affectTextLoiAuxSocietes($entity);
  361.             $this->session->get('flashes')->add(
  362.                 'success',
  363.                 'Le text de loi de Id = ' $entity->getId() . ' a été modifié avec succés...!'
  364.             );
  365.         }
  366.         if ($entity instanceof Action) {
  367.             $this->sendMailToResponsable($entity'Action modifiée');
  368.         }
  369.         if ($entity instanceof TextSociete) {
  370.             $nouvStatut $entity->getStatutConformite();
  371.             //dd("ancien : ".$this->ancienStatut." Nouveau :".$entity->getStatutConformite());
  372.             /*   if($nouvStatut == $this->ancienStatut && $this->ancienStatut == TextSociete::CONFORMITE_NON_EVALUE){
  373.                 $entity->setAnalyseAt(new \DateTime());
  374.                
  375.              }*/
  376.             if (/*$nouvStatut == TextSociete::CONFORMITE_CONFORME &&*/$nouvStatut != $this->ancienStatut) {
  377.                 $entity->setConformeAt(new \DateTime());
  378.             }
  379.             $this->entityManager->persist($entity);
  380.             $this->entityManager->flush();
  381.         }
  382.     }
  383.     public  function affectTextLoiAuxSocietes($entity)
  384.     {
  385.         if ($entity->getGenerale()) {
  386.             $societes $this->societeRepository->societeQuiNepossedePas($entity);
  387.             foreach ($societes as $soc) {
  388.                 if ($soc->getUser()->getUsername() != "admin") {
  389.                     $textSociete = new TextSociete();
  390.                     $textSociete->setSociete($soc);
  391.                     $textSociete->setTextLoi($entity);
  392.                     $textSociete->setStatutConformite(TextSociete::CONFORMITE_NON_EVALUE);
  393.                     $textSociete->setCreatedAt(new \DateTime());
  394.                     $textSociete->setApplicabilite(TextSociete::APPLICABILITE_AVERIFIER);
  395.                     $textSociete->setAddedBy($this->security->getUser());
  396.                     $this->entityManager->persist($textSociete);
  397.                 }
  398.             }
  399.         }
  400.         $this->entityManager->flush();
  401.     }
  402. }