Completed
Push — master ( e58835...7cb891 )
by Frederik
02:40
created

FixedQuotation::prepareBody()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 6.6276

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 20
cts 27
cp 0.7407
rs 8.6737
c 0
b 0
f 0
cc 6
nc 5
nop 1
crap 6.6276
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Quotation;
5
6
use Genkgo\Mail\Address;
7
use Genkgo\Mail\AlternativeText;
8
use Genkgo\Mail\MessageBodyCollection;
9
use Genkgo\Mail\MessageInterface;
10
use Genkgo\Mail\QuotationInterface;
11
12
final class FixedQuotation implements QuotationInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    private $headerText;
18
19
    /**
20
     * @param string $headerText
21
     */
22 13
    public function __construct(string $headerText = '%s (%s):')
23
    {
24 13
        $this->headerText = $headerText;
25 13
    }
26
27
    /**
28
     * @param MessageBodyCollection $body
29
     * @param MessageInterface $originalMessage
30
     * @return MessageBodyCollection
31
     * @throws \DOMException
32
     */
33 13
    public function quote(MessageBodyCollection $body, MessageInterface $originalMessage): MessageBodyCollection
34
    {
35 13
        $originalBody = MessageBodyCollection::extract($originalMessage);
36 13
        $dateString = 'unknown';
37 13
        foreach ($originalMessage->getHeader('Date') as $header) {
38
            try {
39 6
                $date = new \DateTimeImmutable($header->getValue()->getRaw());
40 6
                $formatter = \IntlDateFormatter::create(
41 6
                    \Locale::getDefault(),
42 6
                    \IntlDateFormatter::MEDIUM,
43 6
                    \IntlDateFormatter::MEDIUM
44
                );
45
46 6
                if ($formatter === false) {
47
                    throw new \UnexpectedValueException('Cannot create date formatter');
48
                }
49
50 6
                $dateString = $formatter->format($date);
51 6
                break;
52
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
            }
54
        }
55
56 13
        $fromString = '';
57 13
        foreach ($originalMessage->getHeader('From') as $header) {
58 13
            $from = Address::fromString($header->getValue()->getRaw());
59 13
            $fromString = $from->getName() ? $from->getName() : (string)$from->getAddress();
60
        }
61
62 13
        $headerText = \sprintf($this->headerText, $fromString, $dateString);
63
64
        return $body
65 13
            ->withHtmlAndNoGeneratedAlternativeText(
66 13
                $this->quoteHtml(
67 13
                    $body->getHtml(),
68 13
                    $originalBody->getHtml(),
69
                    $headerText
70
                )
71
            )
72 13
            ->withAlternativeText(
73 13
                $this->quoteText(
74 13
                    $body->getText(),
75 13
                    $originalBody->getText(),
76
                    $headerText
77
                )
78
            );
79
    }
80
81
    /**
82
     * @param string $newHtml
83
     * @param string $originalHtml
84
     * @param string $headerText
85
     * @return string
86
     * @throws \DOMException
87
     */
88 13
    private function quoteHtml(string $newHtml, string $originalHtml, string $headerText): string
89
    {
90 13
        $originalHtml = \trim($originalHtml);
91 13
        if ($originalHtml === '') {
92 2
            return '';
93
        }
94
95 11
        $document = new \DOMDocument();
96 11
        $document->substituteEntities = false;
97 11
        $document->resolveExternals = false;
98
99 11
        $result = @$document->loadHTML($originalHtml);
100 11
        if ($result === false) {
101
            throw new \DOMException('Incorrect HTML');
102
        }
103
104 11
        if ($document->documentElement !== null) {
105 11
            $query = new \DOMXPath($document);
106 11
            $removeItems = $query->query('//head|//script|//body/@style|//html/@style', $document->documentElement);
107 11
            if ($removeItems instanceof \DOMNodeList) {
108
                /** @var \DOMElement $removeItem */
109 11
                foreach ($removeItems as $removeItem) {
110
                    /** @var \DOMElement $parent */
111 2
                    $parent = $removeItem->parentNode;
112 2
                    $parent->removeChild($removeItem);
113
                }
114
            }
115
116 11
            $body = $document->getElementsByTagName('body');
117 11
            $quote = $document->createElement('blockquote');
118 11
            $quote->setAttribute('type', 'cite');
119
120 11
            if ($body->length === 0) {
121
                $quote->appendChild($document->removeChild($document->documentElement));
122
            } else {
123 11
                $root = $body->item(0);
124 11
                if ($root instanceof \DOMElement) {
125 11
                    while ($root->childNodes->length !== 0) {
126
                        /** @var \DOMElement $child */
127 11
                        $child = $root->childNodes->item(0);
128 11
                        $quote->appendChild($child);
129
                    }
130
                }
131
            }
132
133 11
            $newDocument = new \DOMDocument();
134 11
            $newDocument->substituteEntities = false;
135 11
            $newDocument->resolveExternals = false;
136 11
            $result = @$newDocument->loadHTML($newHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
137 11
            if ($result === false) {
138
                throw new \DOMException('Incorrect HTML');
139
            }
140
141 11
            $quotedNode = $newDocument->importNode($quote, true);
142 11
            $newBody = $this->prepareBody($newDocument);
143 11
            $newBody->appendChild($quotedNode);
144
145 11
            $header = $newDocument->createElement('p');
146 11
            $header->textContent = $headerText;
147
148
            /** @var \DOMElement $parent */
149 11
            $parent = $quotedNode->parentNode;
150 11
            $parent->insertBefore($header, $quotedNode);
151
152 11
            return \trim((string)$newDocument->saveHTML());
153
        }
154
155
        return '';
156
    }
157
158
    /**
159
     * @param \DOMDocument $document
160
     * @return \DOMElement
161
     */
162 11
    private function prepareBody(\DOMDocument $document): \DOMElement
163
    {
164 11
        if (!$document->documentElement) {
165
            throw new \UnexpectedValueException('Cannot prepare empty document');
166
        }
167
168 11
        $bodyList = $document->getElementsByTagName('body');
169 11
        if ($bodyList->length === 0) {
170 2
            $html = $document->createElement('html');
171 2
            $body = $document->createElement('body');
172 2
            $html->appendChild($body);
173 2
            $body->appendChild($document->documentElement);
174 2
            if ($document->documentElement instanceof \DOMElement) {
175
                $document->removeChild($document->documentElement);
176
            }
177 2
            $document->appendChild($html);
178 2
            return $body;
179
        }
180
181
        /** @var \DOMElement $body */
182 9
        $body = $bodyList->item(0);
183
184 9
        $queryHtml = new \DOMXPath($document);
185 9
        $htmlTags = $queryHtml->query('//html');
186 9
        if ($htmlTags && $htmlTags->length > 0) {
187
            /** @var \DOMElement $html */
188 9
            $html = $htmlTags->item(0);
189 9
            $html->appendChild($body);
190 9
            $document->removeChild($document->documentElement);
191 9
            $document->appendChild($html);
192 9
            return $body;
193
        }
194
195
        $html = $document->createElement('html');
196
        $html->appendChild($body);
197
        $document->removeChild($document->documentElement);
198
        $document->appendChild($html);
199
        return $body;
200
    }
201
202
    /**
203
     * @param AlternativeText $newText
204
     * @param AlternativeText $originalText
205
     * @param string $headerText
206
     * @return AlternativeText
207
     */
208 13
    private function quoteText(
209
        AlternativeText $newText,
210
        AlternativeText $originalText,
211
        string $headerText
212
    ): AlternativeText {
213 13
        return new AlternativeText(
214 13
            \sprintf(
215 13
                "%s\n\n%s\n>%s",
216 13
                (string)$newText,
217 13
                $headerText,
218 13
                \str_replace("\n", "\n>", $originalText->getRaw())
219
            )
220
        );
221
    }
222
}
223