1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\MailTemplates; |
4
|
|
|
|
5
|
|
|
use Mustache_Engine; |
6
|
|
|
use Spatie\MailTemplates\Exceptions\CannotRenderTemplateMailable; |
7
|
|
|
|
8
|
|
|
class TemplateMailableRenderer |
9
|
|
|
{ |
10
|
|
|
/** @var \Spatie\MailTemplates\TemplateMailable */ |
11
|
|
|
protected $templateMailable; |
12
|
|
|
|
13
|
|
|
/** @var \Spatie\MailTemplates\Models\MailTemplate */ |
14
|
|
|
protected $mailTemplate; |
15
|
|
|
|
16
|
|
|
/** @var \Mustache_Engine */ |
17
|
|
|
protected $mustache; |
18
|
|
|
|
19
|
|
|
public function __construct(TemplateMailable $templateMailable, Mustache_Engine $mustache) |
20
|
|
|
{ |
21
|
|
|
$this->templateMailable = $templateMailable; |
22
|
|
|
$this->mustache = $mustache; |
23
|
|
|
|
24
|
|
|
$templateModel = $this->templateMailable->getTemplateModel(); |
25
|
|
|
$this->mailTemplate = $templateModel::findForMailable($templateMailable); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function render(array $data = []): string |
29
|
|
|
{ |
30
|
|
|
$html = $this->mustache->render( |
31
|
|
|
$this->mailTemplate->template, |
|
|
|
|
32
|
|
|
$data |
33
|
|
|
); |
34
|
|
|
|
35
|
|
|
return $this->renderInLayout($html, $data); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function renderSubject(array $data = []): string |
39
|
|
|
{ |
40
|
|
|
return $this->mustache->render( |
41
|
|
|
$this->mailTemplate->subject, |
|
|
|
|
42
|
|
|
$data |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
protected function renderInLayout(string $html, array $data = []): string |
47
|
|
|
{ |
48
|
|
|
$layout = $this->templateMailable->getLayout() |
49
|
|
|
?? $this->mailTemplate->getLayout() |
50
|
|
|
?? '{{{ body }}}'; |
51
|
|
|
|
52
|
|
|
$this->guardAgainstInvalidLayout($layout); |
53
|
|
|
|
54
|
|
|
$data = array_merge(['body' => $html], $data); |
55
|
|
|
|
56
|
|
|
return $this->mustache->render($layout, $data); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
protected function guardAgainstInvalidLayout(string $layout) |
60
|
|
|
{ |
61
|
|
|
if (!str_contains($layout, [ |
62
|
|
|
'{{{body}}}', |
63
|
|
|
'{{{ body }}}', |
64
|
|
|
'{{body}}', |
65
|
|
|
'{{ body }}' |
66
|
|
|
])) { |
67
|
|
|
throw CannotRenderTemplateMailable::layoutDoesNotContainABodyPlaceHolder($this->templateMailable, $this->mailTemplate, $layout); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
Since your code implements the magic getter
_get
, this function will be called for any read access on an undefined variable. You can add the@property
annotation to your class or interface to document the existence of this variable.If the property has read access only, you can use the @property-read annotation instead.
Of course, you may also just have mistyped another name, in which case you should fix the error.
See also the PhpDoc documentation for @property.