Refactor emails models objects, rework related tests

This commit is contained in:
ErickSkrauch
2019-06-16 23:59:19 +03:00
parent 1bf249030f
commit 70d1999d55
24 changed files with 522 additions and 196 deletions

View File

@@ -3,9 +3,8 @@ declare(strict_types=1);
namespace common\emails;
use common\components\EmailsRenderer\RendererInterface;
use ErrorException;
use Exception;
use yii\mail\MailerInterface;
use yii\mail\MessageInterface;
abstract class TemplateWithRenderer extends Template {
@@ -18,59 +17,61 @@ abstract class TemplateWithRenderer extends Template {
/**
* @var string
*/
private $locale;
private $locale = 'en';
/**
* @inheritdoc
*/
public function __construct($to, string $locale, RendererInterface $renderer) {
parent::__construct($to);
$this->locale = $locale;
public function __construct(MailerInterface $mailer, RendererInterface $renderer) {
parent::__construct($mailer);
$this->renderer = $renderer;
}
public function setLocale(string $locale): void {
$this->locale = $locale;
}
public function getLocale(): string {
return $this->locale;
}
public function getRenderer(): RendererInterface {
return $this->renderer;
}
/**
* Метод должен возвращать имя шаблона, который должен быть использован.
* Имена можно взять в репозитории elyby/email-renderer
* This method should return the template's name, which will be rendered.
* List of available templates names can be found at https://github.com/elyby/emails-renderer
*
* @return string
*/
abstract public function getTemplateName(): string;
final protected function getRenderer(): RendererInterface {
return $this->renderer;
}
final protected function getView() {
return $this->getTemplateName();
}
/**
* @param string|array $for
*
* @return MessageInterface
* @throws ErrorException
* @throws \common\emails\exceptions\CannotRenderEmailException
*/
protected function createMessage(): MessageInterface {
protected function createMessage($for): MessageInterface {
return $this->getMailer()
->compose()
->setHtmlBody($this->render())
->setTo($this->getTo())
->setTo($for)
->setFrom($this->getFrom())
->setSubject($this->getSubject());
}
/**
* @return string
* @throws ErrorException
* @throws \common\emails\exceptions\CannotRenderEmailException
*/
private function render(): string {
try {
return $this->getRenderer()->render($this->getTemplateName(), $this->getLocale(), $this->getParams());
} catch (Exception $e) {
throw new ErrorException('Unable to render the template', 0, 1, __FILE__, __LINE__, $e);
throw new exceptions\CannotRenderEmailException($e);
}
}