93 lines
3.0 KiB
PHP
93 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Client;
|
|
use App\Models\ClientCase;
|
|
use App\Models\Contract;
|
|
use App\Models\Person\Person;
|
|
|
|
class EmailTemplateRenderer
|
|
{
|
|
/**
|
|
* Render subject and bodies using a simple {{ key }} replacement.
|
|
* Supported entities: client, person, client_case, contract
|
|
*
|
|
* @param array{subject:string, html?:string|null, text?:string|null} $template
|
|
* @param array{client?:Client, person?:Person, client_case?:ClientCase, contract?:Contract, extra?:array} $ctx
|
|
* @return array{subject:string, html?:string, text?:string}
|
|
*/
|
|
public function render(array $template, array $ctx): array
|
|
{
|
|
$map = $this->buildMap($ctx);
|
|
$replacer = static function (?string $input) use ($map): ?string {
|
|
if ($input === null) {
|
|
return null;
|
|
}
|
|
|
|
return preg_replace_callback('/{{\s*([a-zA-Z0-9_.]+)\s*}}/', function ($m) use ($map) {
|
|
$key = $m[1];
|
|
|
|
return (string) data_get($map, $key, '');
|
|
}, $input);
|
|
};
|
|
|
|
return [
|
|
'subject' => $replacer($template['subject']) ?? '',
|
|
'html' => $replacer($template['html'] ?? null) ?? null,
|
|
'text' => $replacer($template['text'] ?? null) ?? null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array{client?:Client, person?:Person, client_case?:ClientCase, contract?:Contract, extra?:array} $ctx
|
|
*/
|
|
protected function buildMap(array $ctx): array
|
|
{
|
|
$out = [];
|
|
if (isset($ctx['client'])) {
|
|
$c = $ctx['client'];
|
|
$out['client'] = [
|
|
'id' => data_get($c, 'id'),
|
|
'uuid' => data_get($c, 'uuid'),
|
|
];
|
|
}
|
|
if (isset($ctx['person'])) {
|
|
$p = $ctx['person'];
|
|
$out['person'] = [
|
|
'first_name' => data_get($p, 'first_name'),
|
|
'last_name' => data_get($p, 'last_name'),
|
|
'full_name' => trim((data_get($p, 'first_name', '')).' '.(data_get($p, 'last_name', ''))),
|
|
'email' => data_get($p, 'email'),
|
|
'phone' => data_get($p, 'phone'),
|
|
];
|
|
}
|
|
if (isset($ctx['client_case'])) {
|
|
$c = $ctx['client_case'];
|
|
$out['case'] = [
|
|
'id' => data_get($c, 'id'),
|
|
'uuid' => data_get($c, 'uuid'),
|
|
'reference' => data_get($c, 'reference'),
|
|
];
|
|
}
|
|
if (isset($ctx['contract'])) {
|
|
$co = $ctx['contract'];
|
|
$out['contract'] = [
|
|
'id' => data_get($co, 'id'),
|
|
'uuid' => data_get($co, 'uuid'),
|
|
'reference' => data_get($co, 'reference'),
|
|
'amount' => data_get($co, 'amount'),
|
|
];
|
|
$meta = data_get($co, 'meta');
|
|
if (is_array($meta)) {
|
|
$out['contract']['meta'] = $meta;
|
|
}
|
|
}
|
|
if (! empty($ctx['extra']) && is_array($ctx['extra'])) {
|
|
$out['extra'] = $ctx['extra'];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
}
|