src/Hitso/Bundle/CommonBundle/Helper/Mailer/MailerHelper.php line 101

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\CommonBundle\Helper\Mailer;
  4. use Hitso\Bundle\BlocksBundle\Block\Factory;
  5. use Hitso\Bundle\CommonBundle\Event\MailEvent;
  6. use Hitso\Bundle\CommonBundle\Helper\Templating\TemplatingHelperInterface;
  7. use Hitso\Bundle\CommonBundle\Service\System\Configurator\MailerConfigurator;
  8. use Swift_Mailer as Mailer;
  9. use Swift_Message as Message;
  10. use Swift_SmtpTransport;
  11. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  12. use Symfony\Component\OptionsResolver\Options;
  13. use Symfony\Component\OptionsResolver\OptionsResolver;
  14. use Symfony\Component\Validator\Validator\ValidatorInterface;
  15. class MailerHelper implements MailerHelperInterface
  16. {
  17.     /**
  18.      * @var MailerConfigurator
  19.      */
  20.     protected $configurator;
  21.     /**
  22.      * @var TemplatingHelperInterface
  23.      */
  24.     protected $templatingHelper;
  25.     /**
  26.      * @var ValidatorInterface
  27.      */
  28.     protected $validator;
  29.     /**
  30.      * @var array
  31.      */
  32.     protected $options = [];
  33.     /**
  34.      * @var EventDispatcherInterface
  35.      */
  36.     protected $eventDispatcher;
  37.     /**
  38.      * @var Factory
  39.      */
  40.     protected $blockFactory;
  41.     /**
  42.      * @var bool
  43.      */
  44.     protected $debug;
  45.     public function __construct(
  46.         MailerConfigurator $configurator,
  47.         TemplatingHelperInterface $templatingHelper,
  48.         ValidatorInterface $validator,
  49.         EventDispatcherInterface $eventDispatcher,
  50.         Factory $blockFactory,
  51.         bool $debug false
  52.     ) {
  53.         $this->configurator     $configurator;
  54.         $this->templatingHelper $templatingHelper;
  55.         $this->validator        $validator;
  56.         $this->eventDispatcher  $eventDispatcher;
  57.         $this->blockFactory     $blockFactory;
  58.         $this->debug            $debug;
  59.     }
  60.     public function sendEmail(array $options): int
  61.     {
  62.         $resolver = new OptionsResolver();
  63.         $this->configureOptions($resolver);
  64.         $this->options $resolver->resolve($options);
  65.         $mailer  $this->createMailer();
  66.         $message $this->createMessage();
  67.         $this->eventDispatcher->dispatch('mail.pre_send', new MailEvent($mailer$message0));
  68.         $status 0;
  69.         try {
  70.             $status $mailer->send($message);
  71.         } catch (\Exception $e) {
  72.             if ($this->debug) {
  73.                 throw $e;
  74.             }
  75.         }
  76.         $this->eventDispatcher->dispatch('mail.post_send', new MailEvent($mailer$message$status));
  77.         return $status;
  78.     }
  79.     private function createMessage(): Message
  80.     {
  81.         $message = new Message();
  82.         $message->setFrom($this->configurator->getParameter('from_email'));
  83.         $message->setTo($this->options['recipient']);
  84.         $message->setReplyTo($this->options['reply_to']);
  85.         if (!empty($this->options['bcc'])) {
  86.             $message->setBcc($this->options['bcc']);
  87.         }
  88.         $this->setBody($message$this->options['block'], $this->options['parameters']);
  89.         foreach ($this->options['attachments'] as $file) {
  90.             $message->attach($this->createAttachment($file));
  91.         }
  92.         foreach ($this->options['dynamic_attachments'] as $dynamicAttachment) {
  93.             $message->attach($this->createDynamicAttachment($dynamicAttachment));
  94.         }
  95.         return $message;
  96.     }
  97.     private function createDynamicAttachment(array $dynamicAttachment): \Swift_Mime_Attachment
  98.     {
  99.         return new \Swift_Attachment($dynamicAttachment['data'], $dynamicAttachment['name'], $dynamicAttachment['type']);
  100.     }
  101.     private function createAttachment(string $path): \Swift_Mime_Attachment
  102.     {
  103.         return \Swift_Attachment::fromPath($path);
  104.     }
  105.     private function setBody(Message $messagestring $blockName, array $parameters = [])
  106.     {
  107.         $parameters['message'] = $message;
  108.         $block                 $this->blockFactory->getBlock($blockName);
  109.         $subject               $block->getSubject();
  110.         $content               $this->templatingHelper->renderFromString($block->getContent(), $parameters);
  111.         $textContent           $this->templatingHelper->renderFromString($block->getTextContent(), $parameters);
  112.         $body $this->templatingHelper->render($this->options['template'], [
  113.             'content'    => $content,
  114.             'subject'    => $subject,
  115.             'parameters' => $parameters,
  116.         ]);
  117.         $message->setBody($body'text/html');
  118.         if (!empty($textContent)) {
  119.             $message->addPart($textContent'text/plain');
  120.         }
  121.         $message->setSubject($subject);
  122.     }
  123.     private function configureOptions(OptionsResolver $resolver)
  124.     {
  125.         $resolver->setRequired([
  126.             'recipient',
  127.             'bcc',
  128.             'reply_to',
  129.             'block',
  130.             'template',
  131.             'parameters',
  132.             'attachments',
  133.             'dynamic_attachments',
  134.         ]);
  135.         $resolver->setNormalizer('bcc', function (Options $options$value) {
  136.             if (empty($value)) {
  137.                 return $this->configurator->getParameter('bcc') ?? [];
  138.             }
  139.             return $value;
  140.         });
  141.         $resolver->setNormalizer('reply_to', function (Options $options$value) {
  142.             if (empty($value)) {
  143.                 return $this->configurator->getParameter('from_email') ?? [];
  144.             }
  145.             return $value;
  146.         });
  147.         $resolver->setDefault('bcc''');
  148.         $resolver->setDefault('reply_to''');
  149.         $resolver->setDefault('attachments', []);
  150.         $resolver->setDefault('dynamic_attachments', []);
  151.         $resolver->setAllowedTypes('recipient', ['string''array']);
  152.         $resolver->setAllowedTypes('bcc', ['string''array']);
  153.         $resolver->setAllowedTypes('reply_to', ['string''array']);
  154.         $resolver->setAllowedTypes('block', ['string']);
  155.         $resolver->setAllowedTypes('template', ['string']);
  156.         $resolver->setAllowedTypes('parameters', ['array']);
  157.         $resolver->setAllowedTypes('attachments', ['array']);
  158.         $resolver->setAllowedTypes('dynamic_attachments', ['array']);
  159.     }
  160.     private function createMailer(): Mailer
  161.     {
  162.         $configuration $this->configurator->getParameters();
  163.         $encryption    = empty($configuration['encryption']) ? false $configuration['encryption'];
  164.         $transport = new Swift_SmtpTransport(
  165.             $configuration['host'],
  166.             isset($configuration['port']) ? $configuration['port'] : 25,
  167.             $encryption
  168.         );
  169.         $transport->setUsername($configuration['user']);
  170.         $transport->setPassword($configuration['pass']);
  171.         $transport->setStreamOptions([
  172.             'ssl' => [
  173.                 'verify_peer'       => false,
  174.                 'verify_peer_name'  => false,
  175.                 'allow_self_signed' => true,
  176.             ],
  177.         ]);
  178.         $mailer = new Mailer($transport);
  179.         if (isset($configuration['debug']) && true === (bool)$configuration['debug']) {
  180.             $logger = new \Swift_Plugins_Loggers_EchoLogger();
  181.             $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
  182.         }
  183.         return $mailer;
  184.     }
  185. }