2017-04-21 04:11:43 +05:30
|
|
|
<?php
|
2019-06-07 04:46:13 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2017-04-24 21:52:24 +05:30
|
|
|
namespace common\emails;
|
2017-04-21 04:11:43 +05:30
|
|
|
|
|
|
|
use Yii;
|
|
|
|
use yii\base\InvalidConfigException;
|
|
|
|
use yii\mail\MailerInterface;
|
|
|
|
use yii\mail\MessageInterface;
|
|
|
|
|
|
|
|
abstract class Template {
|
|
|
|
|
|
|
|
/**
|
2019-06-17 02:29:19 +05:30
|
|
|
* @var MailerInterface
|
2017-04-21 04:11:43 +05:30
|
|
|
*/
|
|
|
|
private $mailer;
|
|
|
|
|
2019-06-17 02:29:19 +05:30
|
|
|
public function __construct(MailerInterface $mailer) {
|
|
|
|
$this->mailer = $mailer;
|
2017-04-21 04:11:43 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
abstract public function getSubject(): string;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return array|string
|
|
|
|
* @throws InvalidConfigException
|
|
|
|
*/
|
|
|
|
public function getFrom() {
|
2019-06-17 02:29:19 +05:30
|
|
|
$fromEmail = Yii::$app->params['fromEmail'] ?? '';
|
2017-04-21 04:11:43 +05:30
|
|
|
if (!$fromEmail) {
|
|
|
|
throw new InvalidConfigException('Please specify fromEmail app in app params');
|
|
|
|
}
|
|
|
|
|
|
|
|
return [$fromEmail => 'Ely.by Accounts'];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getParams(): array {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2019-06-17 02:29:19 +05:30
|
|
|
/**
|
|
|
|
* @param string|array $to see \yii\mail\MessageInterface::setTo to know the format.
|
|
|
|
*
|
|
|
|
* @throws \common\emails\exceptions\CannotSendEmailException
|
|
|
|
*/
|
|
|
|
public function send($to): void {
|
|
|
|
if (!$this->createMessage($to)->send()) {
|
|
|
|
throw new exceptions\CannotSendEmailException();
|
2017-04-21 04:11:43 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return string|array
|
|
|
|
*/
|
|
|
|
abstract protected function getView();
|
|
|
|
|
2019-06-17 02:29:19 +05:30
|
|
|
final protected function getMailer(): MailerInterface {
|
|
|
|
return $this->mailer;
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function createMessage($for): MessageInterface {
|
2017-04-21 04:11:43 +05:30
|
|
|
return $this->getMailer()
|
|
|
|
->compose($this->getView(), $this->getParams())
|
2019-06-17 02:29:19 +05:30
|
|
|
->setTo($for)
|
2017-04-21 04:11:43 +05:30
|
|
|
->setFrom($this->getFrom())
|
|
|
|
->setSubject($this->getSubject());
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|