Completed
Pull Request — master (#94)
by Piotr
09:20 queued 02:35
created

TwigSwiftMessageFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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(Twig_Environment $twig, RequestStack $requestStack)
28
    {
29
        $this->twig = $twig;
30
        $this->requestStack = $requestStack;
31
    }
32
33
    /**
34
     * @param string $email
35
     * @param string $template
36
     * @param array $data
37
     * @return \Swift_Message
38
     */
39
    public function createMessage($email, $template, array $data)
40
    {
41
        $masterRequest = $this->requestStack->getMasterRequest();
42
43
        if (!empty($masterRequest)) {
44
            $data['request'] = $masterRequest;
45
        }
46
47
        $templateContext = $this->twig->mergeGlobals($data);
48
49
        /** @var \Twig_Template $template */
50
        $template = $this->twig->loadTemplate($template);
51
        $subject = $template->renderBlock('subject', $templateContext);
52
        $htmlBody = $template->renderBlock('body_html', $templateContext);
53
        $message = new \Swift_Message($subject);
54
        $message->setTo($email);
55
56
        if (!empty($htmlBody)) {
57
            $message->setBody($htmlBody, 'text/html');
58
        }
59
60
        return $message;
61
    }
62
}
63