Completed
Pull Request — master (#94)
by Piotr
01:57
created

TwigSwiftMessageFactory::createMessage()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 13
nc 4
nop 3
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
namespace FSi\Bundle\AdminSecurityBundle\Mailer;
11
12
use Symfony\Component\HttpFoundation\RequestStack;
13
use Twig_Environment;
14
15
class TwigSwiftMessageFactory implements SwiftMessageFactoryInterface
16
{
17
    /**
18
     * @var Twig_Environment
19
     */
20
    private $twig;
21
22
    /**
23
     * @var RequestStack
24
     */
25
    private $requestStack;
26
27
    public function __construct(
28
        Twig_Environment $twig,
29
        RequestStack $requestStack
30
    ) {
31
        $this->twig = $twig;
32
        $this->requestStack = $requestStack;
33
    }
34
35
    /**
36
     * @param string $email
37
     * @param string $template
38
     * @param array $data
39
     * @return \Swift_Message
40
     */
41
    public function createMessage($email, $template, array $data)
42
    {
43
        $masterRequest = $this->requestStack->getMasterRequest();
44
45
        if (!empty($masterRequest)) {
46
            $data['request'] = $masterRequest;
47
        }
48
49
        $templateContext = $this->twig->mergeGlobals($data);
50
51
        /** @var \Twig_Template $template */
52
        $template = $this->twig->loadTemplate($template);
53
        $subject = $template->renderBlock('subject', $templateContext);
54
        $htmlBody = $template->renderBlock('body_html', $templateContext);
55
        $message = new \Swift_Message($subject);
56
        $message->setTo($email);
57
58
        if (!empty($htmlBody)) {
59
            $message->setBody($htmlBody, 'text/html');
60
        }
61
62
        return $message;
63
    }
64
}
65