Commit e3d4278a authored by Jean-Philippe Metivier's avatar Jean-Philippe Metivier
Browse files

Adaptation de la fonction transform

parent 40a4af9b
Loading
Loading
Loading
Loading
Loading
+52 −111
Original line number Diff line number Diff line
@@ -8,17 +8,16 @@ use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\QueryBuilder;
use DoctrineModule\Persistence\ProvidesObjectManager;
use Exception;
use RuntimeException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use UnicaenMail\Entity\Db\Mail;
use Laminas\Mail\Message;
use Laminas\Mime\Message as MimeMessage;
use Laminas\Mime\Mime;
use Laminas\Mime\Part;
use Laminas\Mvc\Controller\AbstractActionController;
use RuntimeException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
use UnicaenMail\Entity\Db\Mail;
use UnicaenMail\Exception\NotFoundConfigException;

class MailService
@@ -48,26 +47,22 @@ EOS;
    private ?Mailer $mailer;



    public function getMailer(): ?Mailer
    {
        return $this->mailer;
    }



    public function setMailer(?Mailer $mailer): void
    {
        $this->mailer = $mailer;
    }



    private ?string $entityClass = null;
    private array $config = [];



    /**
     * @param string $entityClass
     * @return MailService
@@ -79,14 +74,12 @@ EOS;
    }



    public function setConfig(array $config): void
    {
        $this->config = $config;
    }



    public function createMailEntity(): object
    {
        $entity = new $this->entityClass();
@@ -94,7 +87,6 @@ EOS;
    }



    /** GESTION DES ENTITES *******************************************************************************************/

    public function create(Mail $mail): Mail
@@ -105,7 +97,6 @@ EOS;
    }



    public function update(Mail $mail): Mail
    {
        $this->objectManager->flush($mail);
@@ -113,7 +104,6 @@ EOS;
    }



    public function delete(Mail $mail): Mail
    {
        $this->objectManager->remove($mail);
@@ -122,7 +112,6 @@ EOS;
    }



    /** REQUETAGE *****************************************************************************************************/

    public function createQueryBuilder(): QueryBuilder
@@ -132,7 +121,6 @@ EOS;
    }



    /**
     * @param string $champ
     * @param string $ordre
@@ -148,7 +136,6 @@ EOS;
    }



    public function getMailsByMotClef(string $motClef, string $champ = 'dateEnvoi', string $ordre = 'DESC'): array
    {
        // todo ici un fix sal au probleme de MotClef1 === MotClef123 avec MotClef1 inclu dans MotClef123
@@ -162,7 +149,6 @@ EOS;
    }



    public function getMail(?int $id): ?Mail
    {
        $qb = $this->createQueryBuilder()
@@ -177,7 +163,6 @@ EOS;
    }



    public function getRequestedMail(AbstractActionController $controller, string $param = 'mail'): ?Mail
    {
        $id = $controller->params()->fromRoute($param);
@@ -204,114 +189,76 @@ EOS;
    }



    /** Transforme un mail Unicaen en Mail Symfony */
    public function transform(Mail $mail, ?string $module = null): Email
    {
        try {
            $fromEmail = $this->fetchValueFromConfig('from_email', $module);
            $fromName = $this->fetchValueFromConfig('from_name', $module);
            $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module);
            $redirect = $this->fetchValueFromConfig('redirect', $module);
            $redirectTo    = $this->fetchValueFromConfig('redirect_to', $module);
        } catch (NotFoundConfigException $e) {
            throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e);
        }

        $to    = (is_string($mail->getDestinataires())) ? explode(',', $mail->getDestinataires()) : [];
        $co    = (is_string($mail->getCopies())) ? explode(',', $mail->getCopies()) : [];
        $sujet = "[" . $subjectPrefix . "] " . $mail->getSujet();
        $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application " . $subjectPrefix . ". </i></p>" . $mail->getCorps();

        if ($redirect) {
            $to = $redirectTo;

            $sujet .= " {REDIR}";

            $corps .= "<br/><br/><hr/><br/>";
            $corps .= "Initialement envoyé à :";
            $corps .= "<ul>";
            foreach (explode(",", $mail->getDestinatairesInitials()) as $t) $corps .= "<li>" . $t . "</li>";
            $corps .= "</ul>";
            if ($mail->getCopies() !== null && !empty($co)) {
                $corps .= "Copie à :";
                $corps .= "<ul>";
                foreach ($co as $e) $corps .= "<li>" . $e . "</li>";
                $corps .= "</ul>";
            }
        $mailSymfony = new Email();
        $mailSymfony->from("'\"" . $fromName . "\" <" . $fromEmail . ">'");
        $adresseToArray = $redirect ? explode(',', $mail->getDestinatairesInitials()) : (explode(',', $mail->getDestinataires()));
        $mailSymfony->to(...$adresseToArray);
        if ($mail->getCopies() !== null) {
            $adresseCcArray = explode(',', $mail->getCopies());
            $mailSymfony->cc(...$adresseCcArray);
        }
        $mailSymfony->subject($mail->getSujet());
        $mailSymfony->html($mail->getCorps());
        $mailSymfony->text(strip_tags($mail->getCorps()));

        $message = (new Email())
            ->from("'\"" . $fromName . "\" <" . $fromEmail . ">'")
            ->subject($sujet)
            ->text(strip_tags($corps))
            ->html($corps);
        $message->to(...$to);


        $attachments = ($mail->getAttachmentPaths()) ? explode("#<>#", $mail->getAttachmentPaths()) : [];
        foreach ($attachments as $path) {
            $basename  = basename($path);
            $extension = (explode('.', $basename)[1]) ?? 'bin';
            $message->attachFromPath($path, $basename, 'application/' . $extension);
        }

        if (!$redirect) {
            if ($co !== null and !empty($co) and $co !== ['']) $message->cc(...$co);
        return $mailSymfony;
    }

        //if ($mail->getCopies()) $message = $message->bcc($mail->getCopies());
        return $message;
    }



    public function sendMail($to, $subject, $texte, ?string $module = null, $attachement_path = null, $copie = null): ?Mail
    {
        try {
            $doNotSend = $this->fetchValueFromConfig('do_not_send', $module);
            $redirect = $this->fetchValueFromConfig('redirect', $module);
            $redirectTo = $this->fetchValueFromConfig('redirect_to', $module);
            $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module);
        } catch (NotFoundConfigException $e) {
            throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e);
        }

        if ($to=== null OR $to === "" OR $to === []) {
        if ($to === null or $to === "" or $to === []) {
            return null;
        }

        
        if (is_string($to)) $to=explode(',', $to);
        if (!is_array($to)) $to = [$to];
        if (is_string($copie)) $copie=explode(',', $copie);
        if (!is_array($copie)) $copie = [$copie];

        /** @var Mail $mail */
        $mail = $this->createMailEntity();
        $mail->setDateEnvoi(new DateTime());
        $mail->setStatusEnvoi(Mail::PENDING);
        $mail->setDestinataires(is_array($to) ? implode(",", $to) : $to);
        if ($redirect) {
            $mail->setDestinatairesInitials(implode(",",$to));
            $mail->setDestinataires(implode(",", $redirectTo));
            $mail->setDestinatairesInitials($to);
            $mail->setDestinataires(implode(',',$redirectTo));
        } else {
            $mail->setDestinataires(implode(",",$to));
            $mail->setDestinataires($to);
        }
        if ($copie !== null and !empty($copie)) $mail->setCopies(implode(",", $copie));
        $mail->setSujet($subject);
        $mail->setCorps($texte);
        if ($copie !== null and !empty($copie)) $mail->setCopies($copie);

        $sujet = "[" . $subjectPrefix . "] " . $subject;
        $mail->setSujet($sujet);
        $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application " . $subjectPrefix . ". </i></p>" . $texte;
        $mail->setCorps($corps);
        if ($attachement_path !== null) {
            $attachement_path = (is_string($attachement_path)) ? $attachement_path : implode("#<>#", $attachement_path);
            $mail->setAttachmentPaths($attachement_path);
        }
        $this->create($mail);

        if ($doNotSend !== true)
        {
        if ($doNotSend !== true) {
            try {
                $email = $this->transform($mail, $module);
                $adresses = $email->getTo();
                $adresse = $email->getFrom();
                $this->getMailer()->send($email);
                $mailSymfony = $this->transform($mail, $module);
                if ($redirect === true) {
                    $mailSymfony = $this->prepareMessageForRedirection($mailSymfony, $module);
                }
                $this->getMailer()->send($mailSymfony, $module);
            } catch (TransportExceptionInterface $e) {
                throw new RuntimeException("Échec de l'envoi du message", 0, $e);
            }
@@ -320,12 +267,9 @@ EOS;
            $mail->setStatusEnvoi(Mail::NOTSENT);
        }
        $this->update($mail);

        return $mail;
    }



    public function send(Email $mail, ?string $module = null): void
    {
        $doNotSend = $this->fetchValueFromConfig('do_not_send', $module);
@@ -347,7 +291,6 @@ EOS;
    }



    protected function prepareMessageForRedirection(Email $mail, ?string $module = null): Email
    {
        // On crée un clone
@@ -396,7 +339,6 @@ EOS;
    }



    /** TODO : Le reenvoi ne tient pas compte du module ... */
    public function reenvoi(Mail $mail): Mail
    {
@@ -412,7 +354,6 @@ EOS;
    }



    /** @return Mail[] */
    public function getMailsWithFiltre(array $filtres): array
    {