浏览代码

final feature

Vincent GUFFON 3 年之前
父节点
当前提交
bb6d86f826

文件差异内容过多而无法显示
+ 176 - 177
composer.lock


+ 43 - 0
src/Controller/MailerController.php

@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Controller;
+
+use App\Entity\Access\Access;
+use App\Entity\Organization\Parameters;
+use App\Message\Command\MailerCommand;
+use App\Service\Mailer\Model\TestModel;
+use DH\Auditor\Provider\Doctrine\DoctrineProvider;
+use DH\Auditor\Provider\Doctrine\Persistence\Reader\Filter\SimpleFilter;
+use DH\Auditor\Provider\Doctrine\Persistence\Reader\Query;
+use DH\Auditor\Provider\Doctrine\Persistence\Reader\Reader;
+use Doctrine\ORM\EntityManagerInterface;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Messenger\MessageBusInterface;
+use Symfony\Component\Routing\Annotation\Route;
+use DH\Auditor\Provider\Doctrine\Persistence\Reader\Filter\FilterInterface;
+
+class MailerController extends AbstractController
+{
+    #[Route('/mailer', name: 'app_mailer')]
+    public function index(MessageBusInterface $messageBus, EntityManagerInterface $entityManager, DoctrineProvider $doctrineProvider): Response
+    {
+//        $reader = new Reader($doctrineProvider);
+//        $query = $reader
+//            ->createQuery(Parameters::class)
+//            ->addFilter(new SimpleFilter('object_id', 5755));
+//
+//        dd($query->execute());
+//        return new Response('ok');
+//
+//
+//
+        $mailerModel = new TestModel(15, 498);
+        $mailerModel->setSenderId(15);
+
+        $messageBus->dispatch(
+            new MailerCommand($mailerModel)
+        );
+        return new Response('ok');
+    }
+}

+ 14 - 0
src/Enum/Utils/EnvironnementVarEnum.php

@@ -0,0 +1,14 @@
+<?php
+declare(strict_types=1);
+
+namespace App\Enum\Utils;
+
+use MyCLabs\Enum\Enum;
+
+/**
+ * @method static APP_ENV()
+ */
+class EnvironnementVarEnum extends Enum
+{
+    private const APP_ENV = 'APP_ENV';
+}

+ 21 - 12
src/Message/Handler/MailerHandler.php

@@ -3,28 +3,37 @@
 declare(strict_types=1);
 
 namespace App\Message\Handler;
+
 use App\Message\Command\MailerCommand;
-use App\Service\Mailer\EmailInterface;
+use App\Repository\Access\AccessRepository;
+use App\Service\Mailer\Email;
 use App\Service\Mailer\Mailer;
+use App\Service\Notifier;
 use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
 
 class MailerHandler implements MessageHandlerInterface
 {
     public function __construct(
-        private Mailer $mailer
-    ) {}
+        private Mailer           $mailer,
+        private Notifier         $notifier,
+        private AccessRepository $accessRepository
+    )
+    {
+    }
 
     public function __invoke(MailerCommand $mailerCommand)
     {
-       $this->mailer->main($mailerCommand->getMailerModel());
-
-//        $this->mercureHub->publishUpdate($exportRequest->getRequesterId(), $file);
-//
-//        $this->notifier->notifyExport(
-//            $this->accessRepository->find($exportRequest->getRequesterId()),
-//            $file
-//        );
-    }
+        $mailerModel = $mailerCommand->getMailerModel();
+        $emails = $this->mailer->main($mailerModel);
 
+        if ($mailerModel->getNotify()) {
+            /** @var Email $email */
+            $email = $emails->first();
 
+            $this->notifier->notifyMessage(
+                $this->accessRepository->find($mailerCommand->getMailerModel()->getSenderId()),
+                ['about' => $email->getEmailEntity()->getAbout()]
+            );
+        }
+    }
 }

+ 59 - 19
src/Service/Mailer/Mailer.php

@@ -6,8 +6,10 @@ namespace App\Service\Mailer;
 use App\Entity\Message\ReportEmail;
 use App\Enum\Core\EmailSendingTypeEnum;
 use App\Enum\Message\MessageStatusEnum;
+use App\Enum\Utils\EnvironnementVarEnum;
 use App\Service\Mailer\Model\MailerModelInterface;
 use App\Service\ServiceIterator\Mailer\BuilderIterator;
+use App\Service\Utils\Environnement;
 use App\Service\Utils\StringsUtils;
 use App\Enum\Message\ReportMessageSatusEnum;
 use Doctrine\Common\Collections\ArrayCollection;
@@ -28,7 +30,8 @@ class Mailer
         private string $opentalentNoReplyEmailAddress,
         private BuilderIterator $builderIterator,
         private StringsUtils $stringsUtils,
-        private EntityManagerInterface $entityManager
+        private EntityManagerInterface $entityManager,
+        private Environnement $environnement
     )
     {
     }
@@ -42,22 +45,33 @@ class Mailer
      * @param MailerModelInterface $mailerModel
      * @throws \Exception
      */
-    public function main(MailerModelInterface $mailerModel): void{
+    public function main(MailerModelInterface $mailerModel): ArrayCollection{
         $builderService = $this->builderIterator->getBuilderFor($mailerModel);
         $emailsCollection = $builderService->build($mailerModel);
 
-        // @todo
-        //$emailsCollection = $this->reduceEmailsCollectionInPreproduction($emailsCollection);
+        $emailsCollection = $this->reduceEmailsCollectionInPreproduction($emailsCollection);
 
+        /** @var Email $email */
         foreach ($emailsCollection as $email){
+            //si l'email n'a pas de destinataire, on ne l'envoi pas...
+            if(empty($email->getEmailRecipients())){
+                $email->getEmailEntity()->setStatus(MessageStatusEnum::FAILED()->getValue());
+                continue;
+            }
+
+            //Envoi du mail
             $this->send($email);
 
+            //Persistance de l'entité Email
             $this->persistEmailEntity($email);
         }
 
+        //Envoi du rapport
         $this->report($emailsCollection);
 
         $this->entityManager->flush();
+
+        return $emailsCollection;
     }
 
     /**
@@ -70,11 +84,14 @@ class Mailer
 
         $this->addRecipients($symfonyMail, $email);
 
+        $this->setAntiSpam($email, $symfonyMail->getTo());
+
         $this->addHeaders($symfonyMail, $email);
 
         // @todo
         //$this->addAttachments();
 
+
         //On tente d'envoyer
         try {
             $this->symfonyMailer->send($symfonyMail);
@@ -152,7 +169,7 @@ class Mailer
      * @param ArrayCollection $emailsCollection
      */
     public function reduceEmailsCollectionInPreproduction(ArrayCollection $emailsCollection): ArrayCollection {
-        if($_ENV['env'] === 'prod') return $emailsCollection;
+        if($this->environnement->get(EnvironnementVarEnum::APP_ENV()->getValue()) === 'prod') return $emailsCollection;
 
         $startEmails = $emailsCollection->slice(0, 10);
         $endEmails = $emailsCollection->slice($emailsCollection->count() - 11, 10);
@@ -165,11 +182,24 @@ class Mailer
      * @param Email $email
      */
     public function addHeaders(SymfonyEmail $symfonyMail, Email $email){
-       // $symfonyMail->getHeaders()->addTextHeader('List-Unsubscribe','mailto:'.$email->getOriginator().'?subject=désabonnement');
-
+        $symfonyMail->getHeaders()->addTextHeader('List-Unsubscribe','mailto:'.$email->getFrom().'?subject=désabonnement');
         $symfonyMail->getHeaders()->addTextHeader('X-ID-OT', $email->getEmailEntity()->getUniqueSendId());
     }
 
+    /**
+     * On change le #__#ANTISPAM_PERSON_EMAIL#__# par la liste des emails afin d'éviter le spamming sur l'envoi en masse
+     * @param Email $email
+     * @param array $to
+     */
+    public function setAntiSpam(Email $email, array $addresses){
+        // map des Address pour ne conserver qu'un tableau d'email
+        $to = array_map(function(Address $address){
+            return $address->getAddress();
+        }, $addresses);
+
+        $email->setContent(str_replace('#__#ANTISPAM_PERSON_EMAIL#__#', implode(',', $to), $email->getContent()));
+    }
+
 
     /**
      * Création du Mail qui sera envoyé via le Mailer de Symfony
@@ -177,8 +207,12 @@ class Mailer
      * @return SymfonyEmail
      */
     public function createSymfonyEmail(Email $email): SymfonyEmail{
+        $addressMailFrom = new Address($email->getFrom(), $email->getEmailEntity()->getAuthor()->getPerson()->getFullName());
+
         return (new SymfonyEmail())
-            ->from($email->getFrom())
+            ->from($addressMailFrom)
+            ->replyTo($addressMailFrom)
+            ->returnPath(Address::create("mail.report@opentalent.fr"))
             ->subject($email->getEmailEntity()->getAbout())
             ->html($email->getContent())
             ->text($this->stringsUtils->convertHtmlToText($email->getContent()))
@@ -191,19 +225,25 @@ class Mailer
      * @param Address $addressesMail
      */
     public function addRecipients(SymfonyEmail $symfonyMail, Email $email): void{
+        $allReadySend = [];
+
         foreach ($email->getEmailRecipients() as $emailRecipient){
             $addressMail = new Address($emailRecipient->getEmailAddress(), $emailRecipient->getName());
-
-            switch($emailRecipient->getSendType()){
-                case EmailSendingTypeEnum::TO()->getValue():
-                    $symfonyMail->addTo($addressMail);
-                    break;
-                case EmailSendingTypeEnum::BBC()->getValue():
-                    $symfonyMail->addBcc($addressMail);
-                    break;
-                case EmailSendingTypeEnum::CC()->getValue():
-                    $symfonyMail->addCc($addressMail);
-                    break;
+            //On envoi pas en double
+            if(!in_array($addressMail, $allReadySend)){
+                $allReadySend[] = $addressMail;
+
+                switch($emailRecipient->getSendType()){
+                    case EmailSendingTypeEnum::TO()->getValue():
+                        $symfonyMail->addTo($addressMail);
+                        break;
+                    case EmailSendingTypeEnum::BBC()->getValue():
+                        $symfonyMail->addBcc($addressMail);
+                        break;
+                    case EmailSendingTypeEnum::CC()->getValue():
+                        $symfonyMail->addCc($addressMail);
+                        break;
+                }
             }
         }
     }

+ 28 - 0
src/Service/Mailer/Model/AbstractMailerModel.php

@@ -0,0 +1,28 @@
+<?php
+declare(strict_types=1);
+
+namespace App\Service\Mailer\Model;
+
+abstract  class AbstractMailerModel
+{
+    protected int $senderId;
+    protected bool $notify = true;
+
+    public function setSenderId(int $accessId) : self{
+        $this->senderId = $accessId;
+        return $this;
+    }
+
+    public function getSenderId(): int {
+        return $this->senderId;
+    }
+
+    public function setNotify(bool $notify) : self{
+        $this->notify = $notify;
+        return $this;
+    }
+
+    public function getNotify(): bool {
+        return $this->notify;
+    }
+}

+ 6 - 1
src/Service/Mailer/Model/MailerModelInterface.php

@@ -3,4 +3,9 @@ declare(strict_types=1);
 
 namespace App\Service\Mailer\Model;
 
-interface MailerModelInterface {}
+interface MailerModelInterface {
+    public function setSenderId(int $accessId);
+    public function getSenderId();
+    public function setNotify(bool $notify);
+    public function getNotify();
+}

+ 1 - 1
src/Service/Mailer/Model/TestModel.php

@@ -6,7 +6,7 @@ namespace App\Service\Mailer\Model;
 /**
  * Classe ... qui ...
  */
-class TestModel implements MailerModelInterface
+class TestModel extends AbstractMailerModel implements MailerModelInterface
 {
     public function __construct(
         private int $accessId,

+ 19 - 0
src/Service/Utils/Environnement.php

@@ -0,0 +1,19 @@
+<?php
+declare(strict_types=1);
+
+namespace App\Service\Utils;
+
+use App\Enum\Utils\EnvironnementVarEnum;
+
+/**
+ * Classe Environnement qui permet de récupérer des variables d'environnement
+ */
+class Environnement
+{
+    public function get(string $name): string{
+        if(in_array($name, EnvironnementVarEnum::toArray(), true)){
+            return $_ENV[$name];
+        }
+        throw new \RuntimeException('not supported', 500);
+    }
+}

部分文件因为文件数量过多而无法显示