Completed
Pull Request — master (#160)
by Sebastiaan de
03:01
created

CssToInlineStyles::getInlineStyles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace TijsVerkoyen\CssToInlineStyles;
4
5
use Symfony\Component\CssSelector\CssSelector;
6
use Symfony\Component\CssSelector\CssSelectorConverter;
7
use Symfony\Component\CssSelector\Exception\ExceptionInterface;
8
use TijsVerkoyen\CssToInlineStyles\Css\Processor;
9
use TijsVerkoyen\CssToInlineStyles\Css\Property\Processor as PropertyProcessor;
10
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor;
11
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Rule;
12
13
class CssToInlineStyles
14
{
15
    private $cssConverter;
16
17
    public function __construct()
18
    {
19
        if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
20
            $this->cssConverter = new CssSelectorConverter();
21
        }
22
    }
23
24
    /**
25
     * Will inline the $css into the given $html
26
     *
27
     * Remark: if the html contains <style>-tags those will be used, the rules
28
     * in $css will be appended.
29
     *
30
     * @param string $html
31
     * @param string $css
32
     * @return string
33
     */
34
    public function convert($html, $css = null)
35
    {
36
        $document = $this->createDomDocumentFromHtml($html);
37
        $processor = new Processor();
38
39
        // get all styles from the style-tags
40
        $rules = $processor->getRules(
41
            $processor->getCssFromStyleTags($html)
42
        );
43
44
        if ($css !== null) {
45
            $rules = $processor->getRules($css, $rules);
46
        }
47
48
        $document = $this->inline($document, $rules);
49
50
        return $this->getHtmlFromDocument($document);
51
    }
52
53
    /**
54
     * Inle the given properties on an given DOMElement
55
     *
56
     * @param \DOMElement             $element
57
     * @param Css\Property\Property[] $properties
58
     * @return \DOMElement
59
     */
60
    public function inlineCssOnElement(\DOMElement $element, array $properties)
61
    {
62
        if (empty($properties)) {
63
            return $element;
64
        }
65
66
        $cssProperties = array();
67
        $inlineProperties = array();
68
69
        foreach ($this->getInlineStyles($element) as $property) {
70
            $inlineProperties[$property->getName()] = $property;
71
        }
72
73
        foreach ($properties as $property) {
74
            if (!isset($inlineProperties[$property->getName()])) {
75
                $cssProperties[$property->getName()] = $property;
76
            }
77
        }
78
79
        $rules = array();
80
        foreach (array_merge($cssProperties, $inlineProperties) as $property) {
81
            $rules[] = $property->toString();
82
        }
83
        $element->setAttribute('style', implode(' ', $rules));
84
85
        return $element;
86
    }
87
88
    /**
89
     * Get the current inline styles for a given DOMElement
90
     *
91
     * @param \DOMElement $element
92
     * @return Css\Property\Property[]
93
     */
94
    public function getInlineStyles(\DOMElement $element)
95
    {
96
        $processor = new PropertyProcessor();
97
98
        return $processor->convertArrayToObjects(
99
            $processor->splitIntoSeparateProperties(
100
                $element->getAttribute('style')
101
            )
102
        );
103
    }
104
105
    /**
106
     * @param string $html
107
     * @return \DOMDocument
108
     */
109
    protected function createDomDocumentFromHtml($html)
110
    {
111
        $document = new \DOMDocument('1.0', 'UTF-8');
112
        $internalErrors = libxml_use_internal_errors(true);
113
        $document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
114
        libxml_use_internal_errors($internalErrors);
115
        $document->formatOutput = true;
116
117
        return $document;
118
    }
119
120
    /**
121
     * @param \DOMDocument $document
122
     * @return string
123
     */
124
    protected function getHtmlFromDocument(\DOMDocument $document)
125
    {
126
        // retrieve the document element
127
        // we do it this way to preserve the utf-8 encoding
128
        $htmlElement = $document->documentElement;
129
        $html = $document->saveHTML($htmlElement);
130
        $html = trim($html);
131
132
        // retrieve the doctype
133
        $document->removeChild($htmlElement);
134
        $doctype = $document->saveHTML();
135
        $doctype = trim($doctype);
136
137
        // if it is the html5 doctype convert it to lowercase
138
        if ($doctype === '<!DOCTYPE html>') {
139
            $doctype = strtolower($doctype);
140
        }
141
142
        return $doctype."\n".$html;
143
    }
144
145
    /**
146
     * @param \DOMDocument    $document
147
     * @param Css\Rule\Rule[] $rules
148
     * @return \DOMDocument
149
     */
150
    protected function inline(\DOMDocument $document, array $rules)
151
    {
152
        if (empty($rules)) {
153
            return $document;
154
        }
155
156
        $xPath = new \DOMXPath($document);
157
158
        usort($rules, array(RuleProcessor::class, 'sortOnSpecificity'));
159
160
        foreach ($rules as $rule) {
161
            try {
162
                if (null !== $this->cssConverter) {
163
                    $expression = $this->cssConverter->toXPath($rule->getSelector());
164
                } else {
165
                    // Compatibility layer for Symfony 2.7 and older
166
                    $expression = CssSelector::toXPath($rule->getSelector());
167
                }
168
            } catch (ExceptionInterface $e) {
169
                continue;
170
            }
171
172
            $elements = $xPath->query($expression);
173
174
            if ($elements === false) {
175
                continue;
176
            }
177
178
            foreach ($elements as $element) {
179
                $this->calculatePropertiesToBeApplied($element, $rule->getProperties());
180
            }
181
        }
182
183
        $elements = $xPath->query('//*[@data-css-to-inline-styles]');
184
185
        foreach ($elements as $element) {
186
            $propertiesToBeApplied = $element->attributes->getNamedItem('data-css-to-inline-styles');
187
            $element->removeAttribute('data-css-to-inline-styles');
188
189
            if ($propertiesToBeApplied !== null) {
190
                $properties = unserialize(base64_decode($propertiesToBeApplied->value));
191
                $this->inlineCssOnElement($element, $properties);
192
            }
193
        }
194
195
        return $document;
196
    }
197
198
    /**
199
     * Store the calculated values in a temporary data-attribute
200
     *
201
     * @param \DOMElement             $element
202
     * @param Css\Property\Property[] $properties
203
     * @return \DOMElement
204
     */
205
    private function calculatePropertiesToBeApplied(
206
        \DOMElement $element,
207
        array $properties
208
    ) {
209
        if (empty($properties)) {
210
            return $element;
211
        }
212
213
        $cssProperties = array();
214
        $currentStyles = $element->attributes->getNamedItem('data-css-to-inline-styles');
215
216
        if ($currentStyles !== null) {
217
            $currentProperties = unserialize(
218
                base64_decode(
219
                    $currentStyles->value
220
                )
221
            );
222
223
            foreach ($currentProperties as $property) {
224
                $cssProperties[$property->getName()] = $property;
225
            }
226
        }
227
228
        foreach ($properties as $property) {
229
            if (isset($cssProperties[$property->getName()])) {
230
                $existingProperty = $cssProperties[$property->getName()];
231
232
                //skip check to overrule if existing property is important and current is not
233
                if ($existingProperty->isImportant() && !$property->isImportant()) {
234
                    continue;
235
                }
236
237
                //overrule if current property is important and existing is not, else check specificity
238
                $overrule = !$existingProperty->isImportant() && $property->isImportant();
239
                if (!$overrule) {
240
                    $overrule = $existingProperty->getOriginalSpecificity()->compareTo($property->getOriginalSpecificity()) <= 0;
241
                }
242
243
                if ($overrule) {
244
                    unset($cssProperties[$property->getName()]);
245
                    $cssProperties[$property->getName()] = $property;
246
                }
247
            } else {
248
                $cssProperties[$property->getName()] = $property;
249
            }
250
        }
251
252
        $element->setAttribute(
253
            'data-css-to-inline-styles',
254
            base64_encode(
255
                serialize(
256
                    array_values($cssProperties)
257
                )
258
            )
259
        );
260
261
        return $element;
262
    }
263
}
264