|
- <?php
-
- namespace common\components;
-
- use common\logic\Producer\Producer\Model\Producer;
- use yii\mail\MessageInterface;
-
- class MailerService
- {
- public function sendFromProducer(string $subject, string $view, array $params, string $toEmail, Producer $producer)
- {
- $message = $this->composeBase($toEmail, $view, $params);
- $this->initMessageFromProducer($message, $subject, $producer);
- return $message->send();
- }
-
- public function sendFromSite(string $subject, string $view, array $params, string $toEmail)
- {
- $message = $this->composeBase($toEmail, $view, $params);
- $this->initMessageFromSite($message, $subject);
- return $message->send();
- }
-
- public function sendProducer(Producer $producer, string $subject, string $view, array $params = [], string $replyTo = null)
- {
- $message = $this->composeBase($producer->contact_email, $view, $params);
- if($replyTo) {
- $message->setReplyTo($replyTo);
- }
- $this->initMessageFromSite($message, $subject);
- return $message->send();
- }
-
- public function sendAdmin(string $subject, string $view, array $params = [], string $replyTo = null)
- {
- $message = $this->composeBase(\Yii::$app->parameterBag->get('adminEmail'), $view, $params);
- if($replyTo) {
- $message->setReplyTo($replyTo);
- }
- $this->initMessageFromSite($message, $subject);
- return $message->send();
- }
-
- private function composeBase(string $toEmail, string $view, array $params = [])
- {
- return \Yii::$app->mailer
- ->compose([
- 'html' => '@common/mail/'.$view.'-html.php',
- 'text' => '@common/mail/'.$view.'-text.php'
- ], $params)
- ->setTo($toEmail);
- }
-
- private function initMessageFromSite(MessageInterface $message, string $subject)
- {
- $message->setFrom([\Yii::$app->parameterBag->get('adminEmail') => \Yii::$app->parameterBag->get('siteName')]);
- $message->setSubject($this->buildSubject(\Yii::$app->parameterBag->get('siteName'), $subject));
- return $message;
- }
-
- private function initMessageFromProducer(MessageInterface $message, string $subject, Producer $producer)
- {
- $message->setFrom([$this->getEmailOpendistrib($producer) => $producer->name]);
- $message->setSubject($this->buildSubject($producer->name, $subject));
- return $message;
- }
-
- private function getEmailOpendistrib(Producer $producer): string
- {
- return $producer->slug . '@opendistrib.net';
- }
-
- private function buildSubject(string $prefix, string $subject)
- {
- return '['.$prefix.'] '.$subject;
- }
- }
|