Completed
Push — master ( fb881a...1dc1c7 )
by Tijs
03:01 queued 19s
created

CssToInlineStyles::inlineCssOnElement()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
rs 8.439
cc 6
eloc 15
nc 13
nop 2
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
     * Inline 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
        $propertyStorage = new \SplObjectStorage();
157
158
        $xPath = new \DOMXPath($document);
159
160
        usort($rules, array(RuleProcessor::class, 'sortOnSpecificity'));
161
162
        foreach ($rules as $rule) {
163
            try {
164
                if (null !== $this->cssConverter) {
165
                    $expression = $this->cssConverter->toXPath($rule->getSelector());
166
                } else {
167
                    // Compatibility layer for Symfony 2.7 and older
168
                    $expression = CssSelector::toXPath($rule->getSelector());
169
                }
170
            } catch (ExceptionInterface $e) {
171
                continue;
172
            }
173
174
            $elements = $xPath->query($expression);
175
176
            if ($elements === false) {
177
                continue;
178
            }
179
180
            foreach ($elements as $element) {
181
                $propertyStorage[$element] = $this->calculatePropertiesToBeApplied(
182
                    $rule->getProperties(),
183
                    $propertyStorage->contains($element) ? $propertyStorage[$element] : array()
184
                );
185
            }
186
        }
187
188
        foreach ($propertyStorage as $element) {
189
            $this->inlineCssOnElement($element, $propertyStorage[$element]);
190
        }
191
192
        return $document;
193
    }
194
195
    /**
196
     * Merge the CSS rules to determine the applied properties.
197
     *
198
     * @param Css\Property\Property[] $properties
199
     * @param Css\Property\Property[] $cssProperties existing applied properties indexed by name
200
     *
201
     * @return Css\Property\Property[] updated properties, indexed by name
202
     */
203
    private function calculatePropertiesToBeApplied(array $properties, array $cssProperties)
204
    {
205
        if (empty($properties)) {
206
            return $cssProperties;
207
        }
208
209
        foreach ($properties as $property) {
210
            if (isset($cssProperties[$property->getName()])) {
211
                $existingProperty = $cssProperties[$property->getName()];
212
213
                //skip check to overrule if existing property is important and current is not
214
                if ($existingProperty->isImportant() && !$property->isImportant()) {
215
                    continue;
216
                }
217
218
                //overrule if current property is important and existing is not, else check specificity
219
                $overrule = !$existingProperty->isImportant() && $property->isImportant();
220
                if (!$overrule) {
221
                    $overrule = $existingProperty->getOriginalSpecificity()->compareTo($property->getOriginalSpecificity()) <= 0;
222
                }
223
224
                if ($overrule) {
225
                    unset($cssProperties[$property->getName()]);
226
                    $cssProperties[$property->getName()] = $property;
227
                }
228
            } else {
229
                $cssProperties[$property->getName()] = $property;
230
            }
231
        }
232
233
        return $cssProperties;
234
    }
235
}
236