Completed
Pull Request — master (#50)
by Frederik
02:02
created

FixedQuotation   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B quote() 0 40 5
B quoteHtml() 0 55 7
B prepareBody() 0 31 3
A quoteText() 0 14 1
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
    public function __construct(string $headerText = '%s (%s):')
23
    {
24
        $this->headerText = $headerText;
25
    }
26
27
    /**
28
     * @param MessageBodyCollection $body
29
     * @param MessageInterface $originalMessage
30
     * @return MessageBodyCollection
31
     * @throws \DOMException
32
     */
33
    public function quote(MessageBodyCollection $body, MessageInterface $originalMessage): MessageBodyCollection
34
    {
35
        $originalBody = MessageBodyCollection::extract($originalMessage);
36
        $dateString = 'unknown';
37
        foreach ($originalMessage->getHeader('Date') as $header) {
38
            try {
39
                $date = new \DateTimeImmutable($header->getValue()->getRaw());
40
                $dateString = \IntlDateFormatter::create(
41
                    \Locale::getDefault(),
42
                    \IntlDateFormatter::MEDIUM,
43
                    \IntlDateFormatter::MEDIUM
44
                )->format($date);
45
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
46
            }
47
        }
48
49
        $fromString = '';
50
        foreach ($originalMessage->getHeader('From') as $header) {
51
            $from = Address::fromString($header->getValue()->getRaw());
52
            $fromString = $from->getName() ? $from->getName() : (string)$from->getAddress();
53
        }
54
55
        $headerText = \sprintf($this->headerText, $fromString, $dateString);
56
57
        return $body
58
            ->withHtmlAndNoGeneratedAlternativeText(
59
                $this->quoteHtml(
60
                    $body->getHtml(),
61
                    $originalBody->getHtml(),
62
                    $headerText
63
                )
64
            )
65
            ->withAlternativeText(
66
                $this->quoteText(
67
                    $body->getText(),
68
                    $originalBody->getText(),
69
                    $headerText
70
                )
71
            );
72
    }
73
74
    /**
75
     * @param string $newHtml
76
     * @param string $originalHtml
77
     * @param string $headerText
78
     * @return string
79
     * @throws \DOMException
80
     */
81
    private function quoteHtml(string $newHtml, string $originalHtml, string $headerText): string
82
    {
83
        $originalHtml = \trim($originalHtml);
84
        if ($originalHtml === '') {
85
            return '';
86
        }
87
88
        $document = new \DOMDocument();
89
        $document->substituteEntities = false;
90
        $document->resolveExternals = false;
91
92
        $result = @$document->loadHTML($originalHtml);
93
        if ($result === false) {
94
            throw new \DOMException('Incorrect HTML');
95
        }
96
97
        $query = new \DOMXPath($document);
98
        $removeItems = $query->query('//head|//script|//body/@style|//html/@style', $document->documentElement);
99
        /** @var \DOMElement $removeItem */
100
        foreach ($removeItems as $removeItem) {
101
            $parent = $removeItem->parentNode;
102
            $parent->removeChild($removeItem);
103
        }
104
105
        $body = $document->getElementsByTagName('body');
106
        $quote = $document->createElement('blockquote');
107
        $quote->setAttribute('type', 'cite');
108
109
        if ($body->length === 0) {
110
            $quote->appendChild($document->removeChild($document->documentElement));
111
        } else {
112
            $root = $body->item(0);
113
            while ($root->childNodes->length !== 0) {
114
                $quote->appendChild($root->childNodes->item(0));
115
            }
116
        }
117
118
        $newDocument = new \DOMDocument();
119
        $newDocument->substituteEntities = false;
120
        $newDocument->resolveExternals = false;
121
        $result = @$newDocument->loadHTML($newHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
122
        if ($result === false) {
123
            throw new \DOMException('Incorrect HTML');
124
        }
125
126
        $quotedNode = $newDocument->importNode($quote, true);
127
        $newBody = $this->prepareBody($newDocument);
128
        $newBody->appendChild($quotedNode);
129
130
        $header = $newDocument->createElement('p');
131
        $header->textContent = $headerText;
132
133
        $quotedNode->parentNode->insertBefore($header, $quotedNode);
134
        return \trim($newDocument->saveHTML());
135
    }
136
137
    /**
138
     * @param \DOMDocument $document
139
     * @return \DOMElement
140
     */
141
    private function prepareBody(\DOMDocument $document): \DOMElement
142
    {
143
        $bodyList = $document->getElementsByTagName('body');
144
        if ($bodyList->length === 0) {
145
            $html = $document->createElement('html');
146
            $body = $document->createElement('body');
147
            $html->appendChild($body);
148
            $body->appendChild($document->documentElement);
149
            $document->removeChild($document->documentElement);
150
            $document->appendChild($html);
151
            return $body;
152
        }
153
154
        $body = $bodyList->item(0);
155
156
        $queryHtml = new \DOMXPath($document);
157
        $htmlTags = $queryHtml->query('//html');
158
        if ($htmlTags->length > 0) {
159
            $html = $htmlTags->item(0);
160
            $html->appendChild($body);
161
            $document->removeChild($document->documentElement);
162
            $document->appendChild($html);
163
            return $body;
164
        }
165
166
        $html = $document->createElement('html');
167
        $html->appendChild($body);
168
        $document->removeChild($document->documentElement);
169
        $document->appendChild($html);
170
        return $body;
171
    }
172
173
    /**
174
     * @param AlternativeText $newText
175
     * @param AlternativeText $originalText
176
     * @param string $headerText
177
     * @return AlternativeText
178
     */
179
    private function quoteText(
180
        AlternativeText $newText,
181
        AlternativeText $originalText,
182
        string $headerText
183
    ): AlternativeText {
184
        return new AlternativeText(
185
            \sprintf(
186
                "%s\n\n%s\n>%s",
187
                (string)$newText,
188
                $headerText,
189
                \str_replace("\n", "\n>", $originalText->getRaw())
190
            )
191
        );
192
    }
193
}
194