Passed
Push — master ( 3259b8...261523 )
by Aleksei
12:20
created

ViewRenderer::render()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5.3906

Importance

Changes 0
Metric Value
eloc 23
c 0
b 0
f 0
dl 0
loc 38
ccs 18
cts 24
cp 0.75
rs 9.2408
cc 5
nc 9
nop 1
crap 5.3906
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\SendIt\Renderer;
6
7
use Spiral\Mailer\Exception\MailerException;
8
use Spiral\Mailer\MessageInterface;
9
use Spiral\SendIt\RendererInterface;
10
use Spiral\Views\Exception\ViewException;
11
use Spiral\Views\ViewsInterface;
12
use Symfony\Component\Mime\Email;
13
14
final class ViewRenderer implements RendererInterface
15
{
16 3
    public function __construct(
17
        private readonly ViewsInterface $views,
18 3
    ) {}
19
20
    /**
21
     * Copy-pasted form https://stackoverflow.com/a/20806227
22
     * Make sure the subject is ASCII-clean
23
     *
24
     * @param string $subject Subject to encode
25
     * @return string Encoded subject
26
     */
27 1
    public static function escapeSubject(string $subject): string
28
    {
29 1
        if (!\preg_match('/[^\x20-\x7e]/', $subject)) {
30
            // ascii-only subject, return as-is
31 1
            return $subject;
32
        }
33
34
        // Subject is non-ascii, needs encoding
35
        $encoded = \base64_encode($subject);
36
        $prefix = '=?UTF-8?B?';
37
        $suffix = '?=';
38
39
        return $prefix . \str_replace("=\r\n", $suffix . "\r\n  " . $prefix, $encoded) . $suffix;
40
    }
41
42 3
    public function render(MessageInterface $message): Email
43
    {
44
        try {
45 3
            $view = $this->views->get($message->getSubject());
46 1
        } catch (ViewException $e) {
47 1
            throw new MailerException(
48 1
                \sprintf('Invalid email template `%s`: %s', $message->getSubject(), $e->getMessage()),
49 1
                $e->getCode(),
50 1
                $e,
51 1
            );
52
        }
53
54 2
        $msg = new Email();
55
56 2
        if ($message->getFrom() !== null) {
57 1
            $msg->from($message->getFrom());
58
        }
59
60 2
        if ($message->getReplyTo() !== null) {
61 1
            $msg->replyTo($message->getReplyTo());
62
        }
63
64 2
        $msg->to(...$message->getTo());
65 2
        $msg->cc(...$message->getCC());
66 2
        $msg->bcc(...$message->getBCC());
67
68
        try {
69
            // render message partials
70 2
            $view->render(\array_merge(['_msg_' => $msg], $message->getData()));
71
        } catch (ViewException $e) {
72
            throw new MailerException(
73
                \sprintf('Unable to render email `%s`: %s', $message->getSubject(), $e->getMessage()),
74
                $e->getCode(),
75
                $e,
76
            );
77
        }
78
79 2
        return $msg;
80
    }
81
}
82