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

FixedQuotation::quoteHtml()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 7.3599

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 29
cts 36
cp 0.8056
rs 7.8331
c 0
b 0
f 0
cc 7
eloc 37
nc 10
nop 3
crap 7.3599

How to fix   Long Method   

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\Quote;
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\QuoteInterface;
11
12
final class FixedQuotation implements QuoteInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    private $headerText;
18
19
    /**
20
     * @param string $headerText
21
     */
22 1
    public function __construct(string $headerText = "%s (%s):")
23
    {
24 1
        $this->headerText = $headerText;
25 1
    }
26
27
    /**
28
     * @param MessageBodyCollection $body
29
     * @param MessageInterface $originalMessage
30
     * @return MessageBodyCollection
31
     * @throws \DOMException
32
     */
33 1
    public function quote(MessageBodyCollection $body, MessageInterface $originalMessage): MessageBodyCollection
34
    {
35 1
        $originalBody = MessageBodyCollection::extract($originalMessage);
36 1
        $dateString = 'unknown';
37 1
        foreach ($originalMessage->getHeader('Date') as $header) {
38
            try {
39 1
                $date = new \DateTimeImmutable($header->getValue()->getRaw());
40 1
                $dateString = \IntlDateFormatter::create(
41 1
                    \Locale::getDefault(),
42 1
                    \IntlDateFormatter::MEDIUM,
43 1
                    \IntlDateFormatter::MEDIUM
44 1
                )->format($date);
45 1
            } 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 1
        $fromString = '';
50 1
        foreach ($originalMessage->getHeader('From') as $header) {
51 1
            $from = Address::fromString($header->getValue()->getRaw());
52 1
            $fromString = $from->getName() ? $from->getName() : (string)$from->getAddress();
53
        }
54
55 1
        $headerText = \sprintf($this->headerText, $fromString, $dateString);
56
57
        return $body
58 1
            ->withHtmlAndNoGeneratedAlternativeText(
59 1
                $this->quoteHtml(
60 1
                    $body->getHtml(),
61 1
                    $originalBody->getHtml(),
62 1
                    $headerText
63
                )
64
            )
65 1
            ->withAlternativeText($this->quoteText($body->getText(), $originalBody->getText()));
66
    }
67
68
    /**
69
     * @param string $newHtml
70
     * @param string $originalHtml
71
     * @param string $headerText
72
     * @return string
73
     * @throws \DOMException
74
     */
75 1
    private function quoteHtml(string $newHtml, string $originalHtml, string $headerText): string
76
    {
77 1
        $originalHtml = \trim($originalHtml);
78 1
        if ($originalHtml === '') {
79
            return '';
80
        }
81
82 1
        $document = new \DOMDocument();
83 1
        $document->substituteEntities = false;
84 1
        $document->resolveExternals = false;
85
86 1
        $result = @$document->loadHTML($originalHtml);
87 1
        if ($result === false) {
88
            throw new \DOMException('Incorrect HTML');
89
        }
90
91 1
        $query = new \DOMXPath($document);
92 1
        $removeItems = $query->query('//head|//script|//body/@style|//html/@style', $document->documentElement);
93
        /** @var \DOMElement $removeItem */
94 1
        foreach ($removeItems as $removeItem) {
95
            $parent = $removeItem->parentNode;
96
            $parent->removeChild($removeItem);
97
        }
98
99 1
        $body = $document->getElementsByTagName('body');
100 1
        if ($body->length === 0) {
101
            $quote = $document->createElement('blockquote');
102
            $quote->appendChild($document->removeChild($document->documentElement));
103
        } else {
104 1
            $root = $body->item(0);
105 1
            $quote = $document->createElement('blockquote');
106 1
            while ($root->childNodes->length !== 0) {
107 1
                $quote->appendChild($root->childNodes->item(0));
108
            }
109
        }
110
111 1
        $newDocument = new \DOMDocument();
112 1
        $newDocument->substituteEntities = false;
113 1
        $newDocument->resolveExternals = false;
114 1
        $result = @$newDocument->loadHTML($newHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
115 1
        if ($result === false) {
116
            throw new \DOMException('Incorrect HTML');
117
        }
118
119 1
        $quotedNode = $newDocument->importNode($quote, true);
120 1
        $newBody = $this->prepareBody($newDocument);
121 1
        $newBody->appendChild($quotedNode);
122
123 1
        $header = $newDocument->createElement('p');
124 1
        $header->textContent = $headerText;
125
126 1
        $quotedNode->parentNode->insertBefore($header, $quotedNode);
127 1
        return \trim($newDocument->saveHTML());
128
    }
129
130
    /**
131
     * @param \DOMDocument $document
132
     * @return \DOMElement
133
     */
134 1
    private function prepareBody(\DOMDocument $document): \DOMElement
135
    {
136 1
        $bodyList = $document->getElementsByTagName('body');
137 1
        if ($bodyList->length === 0) {
138
            $html = $document->createElement('html');
139
            $body = $document->createElement('body');
140
            $html->appendChild($body);
141
            $body->appendChild($document->documentElement);
142
            $document->removeChild($document->documentElement);
143
            $document->appendChild($html);
144
            return $body;
145
        }
146
147 1
        $body = $bodyList->item(0);
148
149 1
        $queryHtml = new \DOMXPath($document);
150 1
        $htmlTags = $queryHtml->query('//html');
151 1
        if ($htmlTags->length > 0) {
152 1
            $html = $htmlTags->item(0);
153 1
            $html->appendChild($body);
154 1
            $document->removeChild($document->documentElement);
155 1
            $document->appendChild($html);
156 1
            return $body;
157
        }
158
159
        $html = $document->createElement('html');
160
        $html->appendChild($body);
161
        $document->removeChild($document->documentElement);
162
        $document->appendChild($html);
163
        return $body;
164
    }
165
166
    /**
167
     * @param AlternativeText $newText
168
     * @param AlternativeText $originalText
169
     * @return AlternativeText
170
     */
171 1
    private function quoteText(AlternativeText $newText, AlternativeText $originalText): AlternativeText
0 ignored issues
show
Unused Code introduced by
The parameter $newText is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
172
    {
173 1
        return $originalText;
174
    }
175
}
176