Passed
Branch 1 (deb1ae)
by Roman
02:39
created

EmogrifierPlugin::getCss()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bummzack\SwiftMailer\EmogrifyPlugin;
4
5
use Pelago\Emogrifier\CssInliner;
6
use Swift_Events_SendEvent;
7
use Swift_Events_SendListener;
8
use Symfony\Component\CssSelector\Exception\ParseException;
9
10
/**
11
 * Emogrifier Plugin that will convert your CSS to inline styles.
12
 * To be used with SwiftMailer.
13
 *
14
 * @package Bummzack\SwiftMailer\EmogrifyPlugin
15
 */
16
class EmogrifierPlugin implements Swift_Events_SendListener
17
{
18
    protected $css = null;
19
20
    public function getCss(): ?string
21
    {
22
        return $this->css;
23
    }
24
25
    public function setCss($value): self
26
    {
27
        $this->css = $value;
28
        return $this;
29
    }
30
31
    /**
32
     * @param Swift_Events_SendEvent $evt
33
     * @throws ParseException
34
     */
35
    public function beforeSendPerformed(Swift_Events_SendEvent $evt)
36
    {
37
        $message = $evt->getMessage();
38
39
        $body = $message->getBody();
40
        if (!empty($body) && $message->getContentType() !== 'text/plain') {
41
            $html = CssInliner::fromHtml($body)->inlineCss($this->css ?? '')->renderBodyContent();
42
            $message->setBody($html);
43
        }
44
45
        foreach ($message->getChildren() as $messagePart) {
46
            if ($messagePart->getContentType() === 'text/html') {
47
                $body = $messagePart->getBody();
48
49
                if (empty($body)) {
50
                    continue;
51
                }
52
53
                $html = CssInliner::fromHtml($body)->inlineCss($this->css ?? '')->renderBodyContent();
54
                $messagePart->setBody($html);
55
            }
56
        }
57
    }
58
59
    /**
60
     * @param Swift_Events_SendEvent $evt
61
     */
62
    public function sendPerformed(\Swift_Events_SendEvent $evt)
63
    {
64
        /* No op */
65
    }
66
}
67