You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.7KB

  1. <?php
  2. namespace common\components;
  3. use common\logic\Producer\Producer\Model\Producer;
  4. use yii\mail\MessageInterface;
  5. class MailerService
  6. {
  7. public function sendFromProducer(string $subject, string $view, array $params, string $toEmail, Producer $producer)
  8. {
  9. $message = $this->composeBase($toEmail, $view, $params);
  10. $this->initMessageFromProducer($message, $subject, $producer);
  11. return $message->send();
  12. }
  13. public function sendFromSite(string $subject, string $view, array $params, string $toEmail)
  14. {
  15. $message = $this->composeBase($toEmail, $view, $params);
  16. $this->initMessageFromSite($message, $subject);
  17. return $message->send();
  18. }
  19. public function sendProducer(Producer $producer, string $subject, string $view, array $params = [], string $replyTo = null)
  20. {
  21. $message = $this->composeBase($producer->contact_email, $view, $params);
  22. if($replyTo) {
  23. $message->setReplyTo($replyTo);
  24. }
  25. $this->initMessageFromSite($message, $subject);
  26. return $message->send();
  27. }
  28. public function sendAdmin(string $subject, string $view, array $params = [], string $replyTo = null)
  29. {
  30. $message = $this->composeBase(\Yii::$app->parameterBag->get('adminEmail'), $view, $params);
  31. if($replyTo) {
  32. $message->setReplyTo($replyTo);
  33. }
  34. $this->initMessageFromSite($message, $subject);
  35. return $message->send();
  36. }
  37. private function composeBase(string $toEmail, string $view, array $params = [])
  38. {
  39. return \Yii::$app->mailer
  40. ->compose([
  41. 'html' => '@common/mail/'.$view.'-html.php',
  42. 'text' => '@common/mail/'.$view.'-text.php'
  43. ], $params)
  44. ->setTo($toEmail);
  45. }
  46. private function initMessageFromSite(MessageInterface $message, string $subject)
  47. {
  48. $message->setFrom([\Yii::$app->parameterBag->get('adminEmail') => \Yii::$app->parameterBag->get('siteName')]);
  49. $message->setSubject($this->buildSubject(\Yii::$app->parameterBag->get('siteName'), $subject));
  50. return $message;
  51. }
  52. private function initMessageFromProducer(MessageInterface $message, string $subject, Producer $producer)
  53. {
  54. $message->setFrom([$this->getEmailOpendistrib($producer) => $producer->name]);
  55. $message->setSubject($this->buildSubject($producer->name, $subject));
  56. return $message;
  57. }
  58. private function getEmailOpendistrib(Producer $producer): string
  59. {
  60. return $producer->slug . '@opendistrib.net';
  61. }
  62. private function buildSubject(string $prefix, string $subject)
  63. {
  64. return '['.$prefix.'] '.$subject;
  65. }
  66. }