FixedQuotation::quoteHtml()   C
last analyzed

Complexity

Conditions 11
Paths 15

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 38
CRAP Score 11.1903

Importance

Changes 0
Metric Value
dl 0
loc 72
ccs 38
cts 43
cp 0.8837
rs 6.4642
c 0
b 0
f 0
cc 11
nc 15
nop 3
crap 11.1903

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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