Passed
Push — master ( 74a26b...1c65a1 )
by Thomas
02:33
created

EmailUtils::stringifyArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
namespace LeKoala\SparkPost;
4
5
use Pelago\Emogrifier\CssInliner;
6
use Symfony\Component\Mime\Address;
7
use Pelago\Emogrifier\HtmlProcessor\HtmlPruner;
8
use Pelago\Emogrifier\HtmlProcessor\CssToAttributeConverter;
9
10
class EmailUtils
11
{
12
    /**
13
     * Inline styles using Pelago Emogrifier V7
14
     *
15
     * This is much better than the functionnality provided by SparkPost anyway
16
     *
17
     * @link https://github.com/MyIntervals/emogrifier#more-complex-example
18
     * @param string $html
19
     * @param string $css (optional) css to inline
20
     * @return string
21
     */
22
    public static function inline_styles($html, $css = '')
23
    {
24
        $domDocument = CssInliner::fromHtml($html)->inlineCss($css)->getDomDocument();
25
26
        HtmlPruner::fromDomDocument($domDocument)->removeElementsWithDisplayNone();
27
        $html = CssToAttributeConverter::fromDomDocument($domDocument)
28
            ->convertCssToVisualAttributes()->render();
29
30
        return $html;
31
    }
32
33
    /**
34
     * @param array<string|int,string|null>|string|null|bool|Address $email
35
     * @return string|null
36
     */
37
    public static function stringify($email)
38
    {
39
        if (!$email || is_bool($email)) {
40
            return null;
41
        }
42
        if ($email instanceof Address) {
43
            if ($email->getName()) {
44
                return $email->getName() . ' <' . $email->getAddress() . '>';
45
            }
46
            return $email->getAddress();
47
        }
48
        if (is_array($email)) {
49
            return $email[1] . ' <' . $email[0] . '>';
50
        }
51
        return $email;
52
    }
53
54
    /**
55
     * @param array<mixed> $emails
56
     * @return string
57
     */
58
    public static function stringifyArray(array $emails)
59
    {
60
        $result = [];
61
        foreach ($emails as $email) {
62
            $result[] = self::stringify($email);
63
        }
64
        return implode(", ", $result);
65
    }
66
67
    /**
68
     * @param array<string|int,string|null>|string|null|bool $email
69
     * @return bool
70
     */
71
    public static function validate($email)
72
    {
73
        return boolval(filter_var(self::stringify($email), FILTER_VALIDATE_EMAIL));
74
    }
75
76
    /**
77
     * Convert an html email to a text email while keeping formatting and links
78
     *
79
     * @param string $content
80
     * @return string
81
     */
82
    public static function convert_html_to_text($content)
83
    {
84
        // Prevent styles to be included
85
        $content = preg_replace('/<style.*>([\s\S]*)<\/style>/i', '', $content);
86
        // Convert html entities to strip them later on
87
        $content = html_entity_decode($content);
88
        // Bold
89
        $content = str_ireplace(['<strong>', '</strong>', '<b>', '</b>'], "*", $content);
90
        // Replace links to keep them accessible
91
        $content = preg_replace('/<a(.*?)href=[\'"](.*?)[\'"](.*?)>(.*?)<\/a>/i', '$4 ($2)', $content);
92
        // Replace new lines
93
        $content = str_replace(['<br>', '<br/>', '<br />'], "\r\n", $content);
94
        // Remove html tags
95
        $content = strip_tags($content);
96
        // Avoid lots of spaces
97
        $content = preg_replace('/^[\s][\s]+(\S)/m', "\n$1", $content);
98
        // Trim content so that it's nice
99
        $content = trim($content);
100
        return $content;
101
    }
102
103
    /**
104
     * Match all words and whitespace, will be terminated by '<'
105
     *
106
     * Note: use /u to support utf8 strings
107
     *
108
     * @param string $rfc_email_string
109
     * @return string
110
     */
111
    public static function get_displayname_from_rfc_email($rfc_email_string)
112
    {
113
        $name = preg_match('/[\w\s\-\.]+/u', $rfc_email_string, $matches);
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
114
        $matches[0] = trim($matches[0]);
115
        return $matches[0];
116
    }
117
118
    /**
119
     * Extract parts between brackets
120
     *
121
     * @param string $rfc_email_string
122
     * @return string
123
     */
124
    public static function get_email_from_rfc_email($rfc_email_string)
125
    {
126
        if (strpos($rfc_email_string, '<') === false) {
127
            return $rfc_email_string;
128
        }
129
        $mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches);
0 ignored issues
show
Unused Code introduced by
The assignment to $mailAddress is dead and can be removed.
Loading history...
130
        if (empty($matches)) {
131
            return $rfc_email_string;
132
        }
133
        return $matches[1];
134
    }
135
136
    /**
137
     * @deprecated
138
     * @param \SilverStripe\Control\Email\Email $Email
139
     * @return \Symfony\Component\Mime\Header\Headers
140
     */
141
    public static function getHeaders($Email)
142
    {
143
        return method_exists($Email, 'getSwiftMessage') ? $Email->getSwiftMessage()->getHeaders() : $Email->getHeaders();
144
    }
145
}
146