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;
|
|
|
|
|
|
|
|
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
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
private ?Api $api = null;
|
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');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-12-02 15:40:55 +05:30
|
|
|
* @param array<string, mixed> $params
|
2019-06-07 04:46:13 +05:30
|
|
|
*
|
|
|
|
* @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);
|
|
|
|
}
|
|
|
|
|
2019-06-18 03:49:07 +05:30
|
|
|
protected function getApi(): Api {
|
2019-06-07 04:46:13 +05:30
|
|
|
if ($this->api === null) {
|
|
|
|
$this->api = new Api($this->serviceUrl);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->api;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function buildBasePath(): string {
|
2019-06-18 03:49:07 +05:30
|
|
|
return trim($this->baseDomain, '/') . '/' . trim($this->basePath, '/');
|
2019-06-07 04:46:13 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|