TwigSwiftMessageFactory::createMessage()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
nc 4
nop 3
dl 0
loc 22
rs 9.8666
c 2
b 0
f 0
1
<?php
2
3
/**
4
 * (c) FSi sp. z o.o. <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace FSi\Bundle\AdminSecurityBundle\Mailer;
13
14
use Symfony\Component\HttpFoundation\RequestStack;
15
use Twig_Environment;
16
17
class TwigSwiftMessageFactory implements SwiftMessageFactoryInterface
18
{
19
    /**
20
     * @var Twig_Environment
21
     */
22
    private $twig;
23
24
    /**
25
     * @var RequestStack
26
     */
27
    private $requestStack;
28
29
    public function __construct(Twig_Environment $twig, RequestStack $requestStack)
30
    {
31
        $this->twig = $twig;
32
        $this->requestStack = $requestStack;
33
    }
34
35
    public function createMessage(string $email, string $template, array $data): \Swift_Message
36
    {
37
        $masterRequest = $this->requestStack->getMasterRequest();
38
39
        if (null !== $masterRequest) {
40
            $data['request'] = $masterRequest;
41
        }
42
43
        $templateContext = $this->twig->mergeGlobals($data);
44
45
        /** @var \Twig_Template $template */
46
        $template = $this->twig->loadTemplate($template);
47
        $subject = $template->renderBlock('subject', $templateContext);
48
        $htmlBody = $template->renderBlock('body_html', $templateContext);
49
        $message = new \Swift_Message($subject);
50
        $message->setTo($email);
51
52
        if (!empty($htmlBody)) {
53
            $message->setBody($htmlBody, 'text/html');
54
        }
55
56
        return $message;
57
    }
58
}
59