Completed
Pull Request — master (#94)
by Piotr
08:16
created

TwigSwiftMessageFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A createMessage() 0 23 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(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