Completed
Push — master ( c83f11...e27db7 )
by
unknown
01:42
created

TemplateMailableRenderer::renderHtmlLayout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
rs 9.9666
cc 1
nc 1
nop 1
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