update
This commit is contained in:
@@ -4,6 +4,7 @@ namespace App\Services\Email;
|
||||
|
||||
use App\Exceptions\InvalidTemplateVariableException;
|
||||
use App\Models\Template;
|
||||
use App\Support\MailPlaceholders;
|
||||
|
||||
/**
|
||||
* Render Template subject/message: chỉ thay thế placeholder dạng {{key}} đã khai báo
|
||||
@@ -11,7 +12,7 @@ use App\Models\Template;
|
||||
*/
|
||||
class EmailTemplateRenderer
|
||||
{
|
||||
private const PLACEHOLDER_PATTERN = '/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/';
|
||||
private const PLACEHOLDER_PATTERN = MailPlaceholders::PATTERN;
|
||||
|
||||
/**
|
||||
* @return array{subject: string, html: string}
|
||||
@@ -31,7 +32,7 @@ class EmailTemplateRenderer
|
||||
|
||||
private function assertKnownVariables(string $scenario, string $content, array $variables): void
|
||||
{
|
||||
$used = $this->extractPlaceholders($content);
|
||||
$used = MailPlaceholders::extract($content);
|
||||
$invalid = array_values(array_diff($used, array_keys($variables)));
|
||||
|
||||
if ($invalid !== []) {
|
||||
@@ -39,17 +40,13 @@ class EmailTemplateRenderer
|
||||
}
|
||||
}
|
||||
|
||||
private function extractPlaceholders(string $content): array
|
||||
{
|
||||
preg_match_all(self::PLACEHOLDER_PATTERN, $content, $matches);
|
||||
|
||||
return array_values(array_unique($matches[1]));
|
||||
}
|
||||
|
||||
private function replace(string $content, array $variables, array $data): string
|
||||
{
|
||||
return preg_replace_callback(self::PLACEHOLDER_PATTERN, function (array $match) use ($variables, $data) {
|
||||
$key = $match[1];
|
||||
if (!isset($variables[$key]) && !array_key_exists($key, $data)) {
|
||||
return $match[0];
|
||||
}
|
||||
$definition = $variables[$key] ?? [];
|
||||
$value = $data[$key] ?? $definition['example'] ?? '';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user