Completed
Pull Request — master (#91)
by Piotr
02:36
created

TwigSwiftMessageFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 51
c 0
b 0
f 0
wmc 4
lcom 1
cbo 4
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B createMessage() 0 24 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 = \Swift_Message::newInstance()
56
            ->setSubject($subject)
57
            ->setTo($email);
58
59
        if (!empty($htmlBody)) {
60
            $message->setBody($htmlBody, 'text/html');
61
        }
62
63
        return $message;
64
    }
65
}
66