Все части, отвечающие за отправку E-mail вынесены в отдельный компонент

This commit is contained in:
ErickSkrauch 2017-04-21 01:41:43 +03:00
parent 0e2aff91d0
commit c0780736ca
17 changed files with 427 additions and 126 deletions

View File

@ -0,0 +1,56 @@
<?php
namespace api\emails;
use api\emails\templates\ChangeEmailConfirmCurrentEmail;
use api\emails\templates\ChangeEmailConfirmNewEmail;
use api\emails\templates\ForgotPasswordEmail;
use api\emails\templates\ForgotPasswordParams;
use api\emails\templates\RegistrationEmail;
use api\emails\templates\RegistrationEmailParams;
use common\models\Account;
use common\models\confirmations\CurrentEmailConfirmation;
use common\models\confirmations\ForgotPassword;
use common\models\confirmations\NewEmailConfirmation;
use common\models\confirmations\RegistrationConfirmation;
use Yii;
class EmailHelper {
public static function registration(RegistrationConfirmation $emailActivation): void {
$account = $emailActivation->account;
$locale = $account->lang;
$params = new RegistrationEmailParams(
$account->username,
$emailActivation->key,
Yii::$app->request->getHostInfo() . '/activation/' . $emailActivation->key
);
(new RegistrationEmail(self::buildTo($account), $locale, $params))->send();
}
public static function forgotPassword(ForgotPassword $emailActivation): void {
$account = $emailActivation->account;
$locale = $account->lang;
$params = new ForgotPasswordParams(
$account->username,
$emailActivation->key,
Yii::$app->request->getHostInfo() . '/recover-password/' . $emailActivation->key
);
(new ForgotPasswordEmail(self::buildTo($account), $locale, $params))->send();
}
public static function changeEmailConfirmCurrent(CurrentEmailConfirmation $emailActivation): void {
(new ChangeEmailConfirmCurrentEmail(self::buildTo($emailActivation->account), $emailActivation->key))->send();
}
public static function changeEmailConfirmNew(NewEmailConfirmation $emailActivation): void {
$account = $emailActivation->account;
(new ChangeEmailConfirmNewEmail(self::buildTo($account), $account->username, $emailActivation->key))->send();
}
public static function buildTo(Account $account): array {
return [$account->email => $account->username];
}
}

79
api/emails/Template.php Normal file
View File

@ -0,0 +1,79 @@
<?php
namespace api\emails;
use api\emails\exceptions\CannotSendEmailException;
use Yii;
use yii\base\InvalidConfigException;
use yii\mail\MailerInterface;
use yii\mail\MessageInterface;
abstract class Template {
/**
* @var \yii\swiftmailer\Mailer
*/
private $mailer;
/**
* @var string|array
*/
private $to;
/**
* @param string|array $to получатель письма. Задаётся как Email или как массив [email => name]
*/
public function __construct($to) {
$this->mailer = Yii::$app->mailer;
$this->to = $to;
}
/**
* @return array|string
*/
public function getTo() {
return $this->to;
}
abstract public function getSubject(): string;
/**
* @return array|string
* @throws InvalidConfigException
*/
public function getFrom() {
$fromEmail = Yii::$app->params['fromEmail'];
if (!$fromEmail) {
throw new InvalidConfigException('Please specify fromEmail app in app params');
}
return [$fromEmail => 'Ely.by Accounts'];
}
public function getParams(): array {
return [];
}
public function getMailer(): MailerInterface {
return $this->mailer;
}
public function send(): void {
if (!$this->createMessage()->send()) {
throw new CannotSendEmailException('Unable send email.');
}
}
/**
* @return string|array
*/
abstract protected function getView();
protected function createMessage(): MessageInterface {
return $this->getMailer()
->compose($this->getView(), $this->getParams())
->setTo($this->getTo())
->setFrom($this->getFrom())
->setSubject($this->getSubject());
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace api\emails;
use common\components\EmailRenderer;
use Yii;
use yii\mail\MessageInterface;
abstract class TemplateWithRenderer extends Template {
/**
* @var EmailRenderer
*/
private $emailRenderer;
/**
* @var string
*/
private $locale;
/**
* @inheritdoc
*/
public function __construct($to, string $locale) {
parent::__construct($to);
$this->emailRenderer = Yii::$app->emailRenderer;
$this->locale = $locale;
}
public function getLocale(): string {
return $this->locale;
}
public function getEmailRenderer(): EmailRenderer {
return $this->emailRenderer;
}
/**
* Метод должен возвращать имя шаблона, который должен быть использован.
* Имена можно взять в репозитории elyby/email-renderer
*
* @return string
*/
abstract protected function getTemplateName(): string;
protected final function getView() {
return $this->getTemplateName();
}
protected function createMessage(): MessageInterface {
return $this->getMailer()
->compose()
->setHtmlBody($this->render())
->setTo($this->getTo())
->setFrom($this->getFrom())
->setSubject($this->getSubject());
}
private function render(): string {
return $this->getEmailRenderer()
->getTemplate($this->getTemplateName())
->setLocale($this->getLocale())
->setParams($this->getParams())
->render();
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace api\emails\exceptions;
use Exception;
class CannotSendEmailException extends Exception {
}

View File

@ -0,0 +1,35 @@
<?php
namespace api\emails\templates;
use api\emails\Template;
class ChangeEmailConfirmCurrentEmail extends Template {
private $key;
public function __construct($to, string $key) {
parent::__construct($to);
$this->key = $key;
}
public function getSubject(): string {
return 'Ely.by Account change E-mail confirmation';
}
/**
* @return string|array
*/
protected function getView() {
return [
'html' => '@app/mails/current-email-confirmation-html',
'text' => '@app/mails/current-email-confirmation-text',
];
}
public function getParams(): array {
return [
'key' => $this->key,
];
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace api\emails\templates;
use api\emails\Template;
class ChangeEmailConfirmNewEmail extends Template {
private $username;
private $key;
public function __construct($to, string $username, string $key) {
parent::__construct($to);
$this->username = $username;
$this->key = $key;
}
public function getSubject(): string {
return 'Ely.by Account new E-mail confirmation';
}
/**
* @return string|array
*/
protected function getView() {
return [
'html' => '@app/mails/new-email-confirmation-html',
'text' => '@app/mails/new-email-confirmation-text',
];
}
public function getParams(): array {
return [
'key' => $this->key,
'username' => $this->username,
];
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace api\emails\templates;
use api\emails\TemplateWithRenderer;
class ForgotPasswordEmail extends TemplateWithRenderer {
private $params;
/**
* @inheritdoc
*/
public function __construct($to, string $locale, ForgotPasswordParams $params) {
TemplateWithRenderer::__construct($to, $locale);
$this->params = $params;
}
public function getSubject(): string {
return 'Ely.by Account forgot password';
}
protected function getTemplateName(): string {
return 'forgotPassword';
}
public function getParams(): array {
return [
'username' => $this->params->getUsername(),
'code' => $this->params->getCode(),
'link' => $this->params->getLink(),
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace api\emails\templates;
class ForgotPasswordParams {
private $username;
private $code;
private $link;
public function __construct(string $username, string $code, string $link) {
$this->username = $username;
$this->code = $code;
$this->link = $code;
}
public function getUsername(): string {
return $this->username;
}
public function getCode(): string {
return $this->code;
}
public function getLink(): string {
return $this->link;
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace api\emails\templates;
use api\emails\TemplateWithRenderer;
class RegistrationEmail extends TemplateWithRenderer {
private $params;
/**
* @inheritdoc
*/
public function __construct($to, string $locale, RegistrationEmailParams $params) {
TemplateWithRenderer::__construct($to, $locale);
$this->params = $params;
}
public function getSubject(): string {
return 'Ely.by Account registration';
}
protected function getTemplateName(): string {
return 'register';
}
public function getParams(): array {
return [
'username' => $this->params->getUsername(),
'code' => $this->params->getCode(),
'link' => $this->params->getLink(),
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace api\emails\templates;
class RegistrationEmailParams {
private $username;
private $code;
private $link;
public function __construct(string $username, string $code, string $link) {
$this->username = $username;
$this->code = $code;
$this->link = $code;
}
public function getUsername(): string {
return $this->username;
}
public function getCode(): string {
return $this->code;
}
public function getLink(): string {
return $this->link;
}
}

View File

@ -1,12 +1,12 @@
<?php
/**
* @var \common\models\Account $account
* @var string $username
* @var string $key
*/
?>
<p>
This E-mail was specified as new for account <?= $account->username ?>. To confirm this E-mail, pass code
This E-mail was specified as new for account <?= $username ?>. To confirm this E-mail, pass code
below into form on site.
</p>
<p>Code: <?= $key ?></p>

View File

@ -1,11 +1,11 @@
<?php
/**
* @var \common\models\Account $account
* @var string $username
* @var string $key
*/
?>
This E-mail was specified as new for account <?= $account->username ?>. To confirm this E-mail, pass code below into form on site.
This E-mail was specified as new for account <?= $username ?>. To confirm this E-mail, pass code below into form on site.
Code: <?= $key ?>

View File

@ -1,6 +1,7 @@
<?php
namespace api\models\authentication;
use api\emails\EmailHelper;
use api\models\base\ApiForm;
use api\validators\TotpValidator;
use common\helpers\Error as E;
@ -9,9 +10,7 @@ use common\components\UserFriendlyRandomKey;
use common\models\Account;
use common\models\confirmations\ForgotPassword;
use common\models\EmailActivation;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
class ForgotPasswordForm extends ApiForm {
use AccountFinder;
@ -92,41 +91,11 @@ class ForgotPasswordForm extends ApiForm {
throw new ErrorException('Cannot create email activation for forgot password form');
}
$this->sendMail($emailActivation);
EmailHelper::forgotPassword($emailActivation);
return true;
}
public function sendMail(EmailActivation $emailActivation) {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$fromEmail = Yii::$app->params['fromEmail'];
if (!$fromEmail) {
throw new InvalidConfigException('Please specify fromEmail app in app params');
}
$account = $emailActivation->account;
$htmlBody = Yii::$app->emailRenderer->getTemplate('forgotPassword')
->setLocale($account->lang)
->setParams([
'username' => $account->username,
'code' => $emailActivation->key,
'link' => Yii::$app->request->getHostInfo() . '/recover-password/' . $emailActivation->key,
])
->render();
/** @var \yii\swiftmailer\Message $message */
$message = $mailer->compose()
->setHtmlBody($htmlBody)
->setTo([$account->email => $account->username])
->setFrom([$fromEmail => 'Ely.by Accounts'])
->setSubject('Ely.by Account forgot password');
if (!$message->send()) {
throw new ErrorException('Unable send email with activation code.');
}
}
public function getLogin() {
return $this->login;
}

View File

@ -2,12 +2,12 @@
namespace api\models\authentication;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\emails\EmailHelper;
use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\components\UserFriendlyRandomKey;
use common\models\Account;
use common\models\confirmations\RegistrationConfirmation;
use common\models\EmailActivation;
use common\models\UsernameHistory;
use common\validators\EmailValidator;
use common\validators\LanguageValidator;
@ -17,7 +17,6 @@ use Exception;
use Ramsey\Uuid\Uuid;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use const common\LATEST_RULES_VERSION;
@ -103,7 +102,7 @@ class RegistrationForm extends ApiForm {
throw new ErrorException('Cannot save username history record');
}
$this->sendMail($emailActivation, $account);
EmailHelper::registration($emailActivation);
$transaction->commit();
} catch (Exception $e) {
@ -114,37 +113,6 @@ class RegistrationForm extends ApiForm {
return $account;
}
// TODO: подумать, чтобы вынести этот метод в какую-то отдельную конструкцию, т.к. используется и внутри NewAccountActivationForm
public function sendMail(EmailActivation $emailActivation, Account $account) {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$fromEmail = Yii::$app->params['fromEmail'];
if (!$fromEmail) {
throw new InvalidConfigException('Please specify fromEmail app in app params');
}
$htmlBody = Yii::$app->emailRenderer->getTemplate('register')
->setLocale($account->lang)
->setParams([
'username' => $account->username,
'code' => $emailActivation->key,
'link' => Yii::$app->request->getHostInfo() . '/activation/' . $emailActivation->key,
])
->render();
/** @var \yii\swiftmailer\Message $message */
$message = $mailer->compose()
->setHtmlBody($htmlBody)
->setTo([$account->email => $account->username])
->setFrom([$fromEmail => 'Ely.by Accounts'])
->setSubject('Ely.by Account registration');
if (!$message->send()) {
throw new ErrorException('Unable send email with activation code.');
}
}
/**
* Метод проверяет, можно ли занять указанный при регистрации ник или e-mail. Так случается,
* что пользователи вводят неправильный e-mail или ник, после замечают это и пытаются вновь

View File

@ -2,6 +2,7 @@
namespace api\models\authentication;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\emails\EmailHelper;
use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\components\UserFriendlyRandomKey;
@ -72,8 +73,7 @@ class RepeatAccountActivationForm extends ApiForm {
throw new ErrorException('Unable save email-activation model.');
}
$regForm = new RegistrationForm();
$regForm->sendMail($activation, $account);
EmailHelper::registration($activation);
$transaction->commit();
} catch (ErrorException $e) {

View File

@ -1,6 +1,7 @@
<?php
namespace api\models\profile\ChangeEmail;
use api\emails\EmailHelper;
use api\models\base\ApiForm;
use api\validators\PasswordRequiredValidator;
use common\helpers\Error as E;
@ -10,7 +11,6 @@ use common\models\EmailActivation;
use Yii;
use yii\base\ErrorException;
use yii\base\Exception;
use yii\base\InvalidConfigException;
class InitStateForm extends ApiForm {
@ -55,7 +55,8 @@ class InitStateForm extends ApiForm {
try {
$this->removeOldCode();
$activation = $this->createCode();
$this->sendCode($activation);
EmailHelper::changeEmailConfirmCurrent($activation);
$transaction->commit();
} catch (Exception $e) {
@ -93,29 +94,6 @@ class InitStateForm extends ApiForm {
$emailActivation->delete();
}
public function sendCode(EmailActivation $code) {
$mailer = Yii::$app->mailer;
$fromEmail = Yii::$app->params['fromEmail'];
if (!$fromEmail) {
throw new InvalidConfigException('Please specify fromEmail app in app params');
}
$acceptor = $code->account;
$message = $mailer->compose([
'html' => '@app/mails/current-email-confirmation-html',
'text' => '@app/mails/current-email-confirmation-text',
], [
'key' => $code->key,
])
->setTo([$acceptor->email => $acceptor->username])
->setFrom([$fromEmail => 'Ely.by Accounts'])
->setSubject('Ely.by Account change E-mail confirmation');
if (!$message->send()) {
throw new ErrorException('Unable send email with activation code.');
}
}
/**
* Возвращает E-mail активацию, которая использовалась внутри процесса для перехода на следующий шаг.
* Метод предназначен для проверки, не слишком ли часто отправляются письма о смене E-mail.

View File

@ -1,6 +1,7 @@
<?php
namespace api\models\profile\ChangeEmail;
use api\emails\EmailHelper;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\models\Account;
@ -9,7 +10,6 @@ use common\models\EmailActivation;
use common\validators\EmailValidator;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
class NewEmailForm extends ApiForm {
@ -45,7 +45,8 @@ class NewEmailForm extends ApiForm {
$previousActivation->delete();
$activation = $this->createCode();
$this->sendCode($activation);
EmailHelper::changeEmailConfirmNew($activation);
$transaction->commit();
@ -67,32 +68,6 @@ class NewEmailForm extends ApiForm {
return $emailActivation;
}
public function sendCode(EmailActivation $code) {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$fromEmail = Yii::$app->params['fromEmail'];
if (!$fromEmail) {
throw new InvalidConfigException('Please specify fromEmail app in app params');
}
$acceptor = $code->account;
/** @var \yii\swiftmailer\Message $message */
$message = $mailer->compose([
'html' => '@app/mails/new-email-confirmation-html',
'text' => '@app/mails/new-email-confirmation-text',
], [
'key' => $code->key,
'account' => $acceptor,
])
->setTo([$this->email => $acceptor->username])
->setFrom([$fromEmail => 'Ely.by Accounts'])
->setSubject('Ely.by Account new E-mail confirmation');
if (!$message->send()) {
throw new ErrorException('Unable send email with activation code.');
}
}
public function __construct(Account $account, array $config = []) {
$this->account = $account;
parent::__construct($config);