1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\MailTemplates; |
4
|
|
|
|
5
|
|
|
use Mustache_Engine; |
6
|
|
|
use Spatie\MailTemplates\Exceptions\CannotRenderTemplateMailable; |
7
|
|
|
|
8
|
|
|
class TemplateMailableRenderer |
9
|
|
|
{ |
10
|
|
|
public const RENDER_HTML_LAYOUT = 0; |
11
|
|
|
public const RENDER_TEXT_LAYOUT = 1; |
12
|
|
|
|
13
|
|
|
/** @var \Spatie\MailTemplates\TemplateMailable */ |
14
|
|
|
protected $templateMailable; |
15
|
|
|
|
16
|
|
|
/** @var \Spatie\MailTemplates\Interfaces\MailTemplateInterface */ |
17
|
|
|
protected $mailTemplate; |
18
|
|
|
|
19
|
|
|
/** @var \Mustache_Engine */ |
20
|
|
|
protected $mustache; |
21
|
|
|
|
22
|
|
|
public function __construct(TemplateMailable $templateMailable, Mustache_Engine $mustache) |
23
|
|
|
{ |
24
|
|
|
$this->templateMailable = $templateMailable; |
25
|
|
|
$this->mustache = $mustache; |
26
|
|
|
$this->mailTemplate = $templateMailable->getMailTemplate(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function renderHtmlLayout(array $data = []): string |
30
|
|
|
{ |
31
|
|
|
$body = $this->mustache->render( |
32
|
|
|
$this->mailTemplate->htmlTemplate(), |
33
|
|
|
$data |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
return $this->renderInLayout($body, static::RENDER_HTML_LAYOUT, $data); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function renderTextLayout(array $data = []): string |
40
|
|
|
{ |
41
|
|
|
$body = $this->mustache->render( |
42
|
|
|
$this->mailTemplate->textTemplate(), |
43
|
|
|
$data |
44
|
|
|
); |
45
|
|
|
|
46
|
|
|
return $this->renderInLayout($body, static::RENDER_TEXT_LAYOUT, $data); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function renderSubject(array $data = []): string |
50
|
|
|
{ |
51
|
|
|
return $this->mustache->render( |
52
|
|
|
$this->mailTemplate->subject(), |
53
|
|
|
$data |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
protected function renderInLayout(string $body, int $layoutType, array $data = []): string |
58
|
|
|
{ |
59
|
|
|
$method = $layoutType === static::RENDER_HTML_LAYOUT ? 'getHtmlLayout' : 'getTextLayout'; |
60
|
|
|
$layout = $this->templateMailable->$method() |
61
|
|
|
?? (method_exists($this->mailTemplate, $method) ? $this->mailTemplate->$method() : null) |
62
|
|
|
?? '{{{ body }}}'; |
63
|
|
|
|
64
|
|
|
$this->guardAgainstInvalidLayout($layout); |
65
|
|
|
|
66
|
|
|
$data = array_merge(['body' => $body], $data); |
67
|
|
|
|
68
|
|
|
return $this->mustache->render($layout, $data); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function guardAgainstInvalidLayout(string $layout): void |
72
|
|
|
{ |
73
|
|
|
if (! str_contains($layout, [ |
74
|
|
|
'{{{body}}}', |
75
|
|
|
'{{{ body }}}', |
76
|
|
|
'{{body}}', |
77
|
|
|
'{{ body }}', |
78
|
|
|
])) { |
79
|
|
|
throw CannotRenderTemplateMailable::layoutDoesNotContainABodyPlaceHolder($this->templateMailable); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|