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 {
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function __construct(
|
|
|
|
private readonly MailerInterface $mailer,
|
|
|
|
) {
|
2017-04-21 04:11:43 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
abstract public function getSubject(): string;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return array|string
|
|
|
|
* @throws InvalidConfigException
|
|
|
|
*/
|
2024-12-02 15:40:55 +05:30
|
|
|
public function getFrom(): array|string {
|
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'];
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
/**
|
|
|
|
* @return array<string, mixed>
|
|
|
|
*/
|
2017-04-21 04:11:43 +05:30
|
|
|
public function getParams(): array {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2019-06-17 02:29:19 +05:30
|
|
|
/**
|
2024-12-02 15:40:55 +05:30
|
|
|
* @param array|string $to see \yii\mail\MessageInterface::setTo to know the format.
|
2019-06-17 02:29:19 +05:30
|
|
|
*
|
|
|
|
* @throws \common\emails\exceptions\CannotSendEmailException
|
|
|
|
*/
|
2024-12-02 15:40:55 +05:30
|
|
|
public function send(array|string $to): void {
|
2019-06-17 02:29:19 +05:30
|
|
|
if (!$this->createMessage($to)->send()) {
|
|
|
|
throw new exceptions\CannotSendEmailException();
|
2017-04-21 04:11:43 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-12-02 15:40:55 +05:30
|
|
|
* @return string|array{
|
|
|
|
* html?: string,
|
|
|
|
* text?: string,
|
|
|
|
* }
|
2017-04-21 04:11:43 +05:30
|
|
|
*/
|
2024-12-02 15:40:55 +05:30
|
|
|
abstract protected function getView(): string|array;
|
2017-04-21 04:11:43 +05:30
|
|
|
|
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());
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|