Completed
Pull Request — master (#210)
by
unknown
01:46
created

CssToInlineStyles::parseXhtml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace TijsVerkoyen\CssToInlineStyles;
4
5
use LogicException;
6
use Masterminds\HTML5;
7
use Symfony\Component\CssSelector\CssSelector;
8
use Symfony\Component\CssSelector\CssSelectorConverter;
9
use Symfony\Component\CssSelector\Exception\ExceptionInterface;
10
use TijsVerkoyen\CssToInlineStyles\Css\Processor;
11
use TijsVerkoyen\CssToInlineStyles\Css\Property\Processor as PropertyProcessor;
12
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor;
13
14
class CssToInlineStyles
15
{
16
    private $cssConverter;
17
18
    /** @var HTML5|null */
19
    private $html5Parser;
20
21
    /** @var bool */
22
    private $isHtml5Document = false;
23
24
    /**
25
     * @param bool|null $useHtml5Parser Whether to use a HTML5 parser or the native DOM parser
26
     */
27
    public function __construct($useHtml5Parser = null)
28
    {
29
        if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
30
            $this->cssConverter = new CssSelectorConverter();
31
        }
32
33
        if ($useHtml5Parser) {
34
            if (! class_exists(HTML5::class)) {
35
                throw new LogicException('Using the HTML5 parser requires the html5-php library. Try running "composer require masterminds/html5".');
36
            }
37
38
            $this->html5Parser = new HTML5(['disable_html_ns' => true]);
39
        }
40
    }
41
42
    /**
43
     * Will inline the $css into the given $html
44
     *
45
     * Remark: if the html contains <style>-tags those will be used, the rules
46
     * in $css will be appended.
47
     *
48
     * @param string $html
49
     * @param string $css
50
     *
51
     * @return string
52
     */
53
    public function convert($html, $css = null)
54
    {
55
        $document = $this->createDomDocumentFromHtml($html);
56
        $processor = new Processor();
57
58
        // get all styles from the style-tags
59
        $rules = $processor->getRules(
60
            $processor->getCssFromStyleTags($html)
61
        );
62
63
        if ($css !== null) {
64
            $rules = $processor->getRules($css, $rules);
65
        }
66
67
        $document = $this->inline($document, $rules);
68
69
        return $this->getHtmlFromDocument($document);
70
    }
71
72
    /**
73
     * Inline the given properties on an given DOMElement
74
     *
75
     * @param \DOMElement             $element
76
     * @param Css\Property\Property[] $properties
77
     *
78
     * @return \DOMElement
79
     */
80
    public function inlineCssOnElement(\DOMElement $element, array $properties)
81
    {
82
        if (empty($properties)) {
83
            return $element;
84
        }
85
86
        $cssProperties = array();
87
        $inlineProperties = array();
88
89
        foreach ($this->getInlineStyles($element) as $property) {
90
            $inlineProperties[$property->getName()] = $property;
91
        }
92
93
        foreach ($properties as $property) {
94
            if (!isset($inlineProperties[$property->getName()])) {
95
                $cssProperties[$property->getName()] = $property;
96
            }
97
        }
98
99
        $rules = array();
100
        foreach (array_merge($cssProperties, $inlineProperties) as $property) {
101
            $rules[] = $property->toString();
102
        }
103
        $element->setAttribute('style', implode(' ', $rules));
104
105
        return $element;
106
    }
107
108
    /**
109
     * Get the current inline styles for a given DOMElement
110
     *
111
     * @param \DOMElement $element
112
     *
113
     * @return Css\Property\Property[]
114
     */
115
    public function getInlineStyles(\DOMElement $element)
116
    {
117
        $processor = new PropertyProcessor();
118
119
        return $processor->convertArrayToObjects(
120
            $processor->splitIntoSeparateProperties(
121
                $element->getAttribute('style')
122
            )
123
        );
124
    }
125
126
    /**
127
     * @param string $html
128
     *
129
     * @return \DOMDocument
130
     */
131
    protected function createDomDocumentFromHtml($html)
132
    {
133
        $this->isHtml5Document = false;
134
135
        if ($this->canParseHtml5String($html)) {
136
            return $this->parseHtml5($html);
137
        }
138
139
        return $this->parseXhtml($html);
140
    }
141
142
    /**
143
     * @param string $html
144
     * @return \DOMDocument
145
     */
146
    protected function parseHtml5($html)
147
    {
148
        $this->isHtml5Document = true;
149
150
        return $this->html5Parser->parse($this->convertToHtmlEntities($html));
151
    }
152
153
    /**
154
     * @param string $html
155
     * @return \DOMDocument
156
     */
157
    protected function parseXhtml($html)
158
    {
159
        $document = new \DOMDocument('1.0', 'UTF-8');
160
        $internalErrors = libxml_use_internal_errors(true);
161
        $document->loadHTML($this->convertToHtmlEntities($html));
162
        libxml_use_internal_errors($internalErrors);
163
        $document->formatOutput = true;
164
165
        return $document;
166
    }
167
168
    /**
169
     * @param string $content
170
     * @return bool
171
     */
172
    protected function canParseHtml5String($content)
173
    {
174
        if (null === $this->html5Parser) {
175
            return false;
176
        }
177
178
        if (false === ($pos = stripos($content, '<!doctype html>'))) {
179
            return false;
180
        }
181
182
        $header = substr($content, 0, $pos);
183
184
        return '' === $header || $this->isValidHtml5Heading($header);
185
    }
186
187
    /**
188
     * @param string $heading
189
     * @return bool
190
     */
191
    protected function isValidHtml5Heading($heading)
192
    {
193
        return 1 === preg_match('/^\x{FEFF}?\s*(<!--[^>]*?-->\s*)*$/u', $heading);
194
    }
195
196
    /**
197
     * @param string $html
198
     * @return array|false|string
199
     */
200
    protected function convertToHtmlEntities($html)
201
    {
202
        return mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
203
    }
204
205
    /**
206
     * @param \DOMDocument $document
207
     *
208
     * @return string
209
     */
210
    protected function getHtmlFromDocument(\DOMDocument $document)
211
    {
212
        $parser = $document;
213
        if (null !== $this->html5Parser && $this->isHtml5Document) {
214
            $parser = $this->html5Parser;
215
        }
216
217
        // retrieve the document element
218
        // we do it this way to preserve the utf-8 encoding
219
        $htmlElement = $document->documentElement;
220
        $html = $parser->saveHTML($htmlElement);
221
        $html = trim($html);
222
223
        // retrieve the doctype
224
        $document->removeChild($htmlElement);
225
        $doctype = $document->saveHTML();
226
        $doctype = trim($doctype);
227
228
        // if it is the html5 doctype convert it to lowercase
229
        if ($doctype === '<!DOCTYPE html>') {
230
            $doctype = strtolower($doctype);
231
        }
232
233
        return $doctype."\n".$html;
234
    }
235
236
    /**
237
     * @param \DOMDocument    $document
238
     * @param Css\Rule\Rule[] $rules
239
     *
240
     * @return \DOMDocument
241
     */
242
    protected function inline(\DOMDocument $document, array $rules)
243
    {
244
        if (empty($rules)) {
245
            return $document;
246
        }
247
248
        $propertyStorage = new \SplObjectStorage();
249
250
        $xPath = new \DOMXPath($document);
251
252
        usort($rules, array(RuleProcessor::class, 'sortOnSpecificity'));
253
254
        foreach ($rules as $rule) {
255
            try {
256
                if (null !== $this->cssConverter) {
257
                    $expression = $this->cssConverter->toXPath($rule->getSelector());
258
                } else {
259
                    // Compatibility layer for Symfony 2.7 and older
260
                    $expression = CssSelector::toXPath($rule->getSelector());
261
                }
262
            } catch (ExceptionInterface $e) {
263
                continue;
264
            }
265
266
            $elements = $xPath->query($expression);
267
268
            if ($elements === false) {
269
                continue;
270
            }
271
272
            foreach ($elements as $element) {
273
                $propertyStorage[$element] = $this->calculatePropertiesToBeApplied(
274
                    $rule->getProperties(),
275
                    $propertyStorage->contains($element) ? $propertyStorage[$element] : array()
276
                );
277
            }
278
        }
279
280
        foreach ($propertyStorage as $element) {
281
            $this->inlineCssOnElement($element, $propertyStorage[$element]);
282
        }
283
284
        return $document;
285
    }
286
287
    /**
288
     * Merge the CSS rules to determine the applied properties.
289
     *
290
     * @param Css\Property\Property[] $properties
291
     * @param Css\Property\Property[] $cssProperties existing applied properties indexed by name
292
     *
293
     * @return Css\Property\Property[] updated properties, indexed by name
294
     */
295
    private function calculatePropertiesToBeApplied(array $properties, array $cssProperties)
296
    {
297
        if (empty($properties)) {
298
            return $cssProperties;
299
        }
300
301
        foreach ($properties as $property) {
302
            if (isset($cssProperties[$property->getName()])) {
303
                $existingProperty = $cssProperties[$property->getName()];
304
305
                //skip check to overrule if existing property is important and current is not
306
                if ($existingProperty->isImportant() && !$property->isImportant()) {
307
                    continue;
308
                }
309
310
                //overrule if current property is important and existing is not, else check specificity
311
                $overrule = !$existingProperty->isImportant() && $property->isImportant();
312
                if (!$overrule) {
313
                    $overrule = $existingProperty->getOriginalSpecificity()->compareTo($property->getOriginalSpecificity()) <= 0;
0 ignored issues
show
Documentation introduced by
$property->getOriginalSpecificity() is of type object<Symfony\Component...ector\Node\Specificity>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
314
                }
315
316
                if ($overrule) {
317
                    unset($cssProperties[$property->getName()]);
318
                    $cssProperties[$property->getName()] = $property;
319
                }
320
            } else {
321
                $cssProperties[$property->getName()] = $property;
322
            }
323
        }
324
325
        return $cssProperties;
326
    }
327
}
328