2019-06-07 04:46:13 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace common\components\EmailsRenderer;
|
|
|
|
|
|
|
|
use common\components\EmailsRenderer\Request\TemplateRequest;
|
2019-06-17 02:29:19 +05:30
|
|
|
use common\emails\RendererInterface;
|
2019-06-07 04:46:13 +05:30
|
|
|
use Yii;
|
|
|
|
use yii\base\InvalidConfigException;
|
|
|
|
use yii\helpers\ArrayHelper;
|
|
|
|
use yii\helpers\FileHelper;
|
|
|
|
|
|
|
|
class Component extends \yii\base\Component implements RendererInterface {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var string The address of the templates rendering service.
|
|
|
|
*/
|
|
|
|
public $serviceUrl;
|
|
|
|
|
|
|
|
/**
|
2019-06-17 02:29:19 +05:30
|
|
|
* @var string application base domain. Can be omitted for web applications (will be extracted from request)
|
2019-06-07 04:46:13 +05:30
|
|
|
*/
|
2019-06-17 02:29:19 +05:30
|
|
|
public $baseDomain;
|
2019-06-07 04:46:13 +05:30
|
|
|
|
|
|
|
/**
|
2019-06-17 02:29:19 +05:30
|
|
|
* @var string base path after the host. For example "/emails-images"
|
2019-06-07 04:46:13 +05:30
|
|
|
*/
|
2019-06-17 02:29:19 +05:30
|
|
|
public $basePath = '';
|
2019-06-07 04:46:13 +05:30
|
|
|
|
|
|
|
/**
|
2019-06-17 02:29:19 +05:30
|
|
|
* @var Api
|
2019-06-07 04:46:13 +05:30
|
|
|
*/
|
2019-06-17 02:29:19 +05:30
|
|
|
private $api;
|
2019-06-07 04:46:13 +05:30
|
|
|
|
|
|
|
public function init(): void {
|
|
|
|
parent::init();
|
|
|
|
|
|
|
|
if ($this->serviceUrl === null) {
|
|
|
|
throw new InvalidConfigException('serviceUrl is required');
|
|
|
|
}
|
|
|
|
|
2019-06-17 02:29:19 +05:30
|
|
|
if ($this->baseDomain === null) {
|
|
|
|
$this->baseDomain = Yii::$app->urlManager->getHostInfo();
|
|
|
|
if ($this->baseDomain === null) {
|
2019-06-07 04:46:13 +05:30
|
|
|
throw new InvalidConfigException('Cannot automatically obtain base domain');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $templateName
|
|
|
|
* @param string $locale
|
|
|
|
* @param array $params
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
* @throws \GuzzleHttp\Exception\GuzzleException
|
|
|
|
*/
|
|
|
|
public function render(string $templateName, string $locale, array $params = []): string {
|
|
|
|
$request = new TemplateRequest($templateName, $locale, ArrayHelper::merge($params, [
|
|
|
|
'assetsHost' => $this->buildBasePath(),
|
|
|
|
]));
|
|
|
|
|
|
|
|
return $this->getApi()->getTemplate($request);
|
|
|
|
}
|
|
|
|
|
|
|
|
private function getApi(): Api {
|
|
|
|
if ($this->api === null) {
|
|
|
|
$this->api = new Api($this->serviceUrl);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->api;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function buildBasePath(): string {
|
2019-06-17 02:29:19 +05:30
|
|
|
return FileHelper::normalizePath($this->baseDomain . '/' . $this->basePath, '/');
|
2019-06-07 04:46:13 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|