Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
12
class CssToInlineStyles
13
{
14
    private $cssConverter;
15
 
16
    public function __construct()
17
    {
18
        if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
19
            $this->cssConverter = new CssSelectorConverter();
20
        }
21
    }
22
 
23
    /**
24
     * Will inline the $css into the given $html
25
     *
26
     * Remark: if the html contains <style>-tags those will be used, the rules
27
     * in $css will be appended.
28
     *
29
     * @param string $html
30
     * @param string $css
31
     *
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
     *
59
     * @return \DOMElement
60
     */
61
    public function inlineCssOnElement(\DOMElement $element, array $properties)
62
    {
63
        if (empty($properties)) {
64
            return $element;
65
        }
66
 
67
        $cssProperties = array();
68
        $inlineProperties = array();
69
 
70
        foreach ($this->getInlineStyles($element) as $property) {
71
            $inlineProperties[$property->getName()] = $property;
72
        }
73
 
74
        foreach ($properties as $property) {
75
            if (!isset($inlineProperties[$property->getName()])) {
76
                $cssProperties[$property->getName()] = $property;
77
            }
78
        }
79
 
80
        $rules = array();
81
        foreach (array_merge($cssProperties, $inlineProperties) as $property) {
82
            $rules[] = $property->toString();
83
        }
84
        $element->setAttribute('style', implode(' ', $rules));
85
 
86
        return $element;
87
    }
88
 
89
    /**
90
     * Get the current inline styles for a given DOMElement
91
     *
92
     * @param \DOMElement $element
93
     *
94
     * @return Css\Property\Property[]
95
     */
96
    public function getInlineStyles(\DOMElement $element)
97
    {
98
        $processor = new PropertyProcessor();
99
 
100
        return $processor->convertArrayToObjects(
101
            $processor->splitIntoSeparateProperties(
102
                $element->getAttribute('style')
103
            )
104
        );
105
    }
106
 
107
    /**
108
     * @param string $html
109
     *
110
     * @return \DOMDocument
111
     */
112
    protected function createDomDocumentFromHtml($html)
113
    {
114
        $document = new \DOMDocument('1.0', 'UTF-8');
115
        $internalErrors = libxml_use_internal_errors(true);
116
        $document->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, 0x1FFFFF], 'UTF-8'));
117
        libxml_use_internal_errors($internalErrors);
118
        $document->formatOutput = true;
119
 
120
        return $document;
121
    }
122
 
123
    /**
124
     * @param \DOMDocument $document
125
     *
126
     * @return string
127
     */
128
    protected function getHtmlFromDocument(\DOMDocument $document)
129
    {
130
        // retrieve the document element
131
        // we do it this way to preserve the utf-8 encoding
132
        $htmlElement = $document->documentElement;
133
        $html = $document->saveHTML($htmlElement);
134
        $html = trim($html);
135
 
136
        // retrieve the doctype
137
        $document->removeChild($htmlElement);
138
        $doctype = $document->saveHTML();
139
        $doctype = trim($doctype);
140
 
141
        // if it is the html5 doctype convert it to lowercase
142
        if ($doctype === '<!DOCTYPE html>') {
143
            $doctype = strtolower($doctype);
144
        }
145
 
146
        return $doctype."\n".$html;
147
    }
148
 
149
    /**
150
     * @param \DOMDocument    $document
151
     * @param Css\Rule\Rule[] $rules
152
     *
153
     * @return \DOMDocument
154
     */
155
    protected function inline(\DOMDocument $document, array $rules)
156
    {
157
        if (empty($rules)) {
158
            return $document;
159
        }
160
 
161
        $propertyStorage = new \SplObjectStorage();
162
 
163
        $xPath = new \DOMXPath($document);
164
 
165
        usort($rules, array(RuleProcessor::class, 'sortOnSpecificity'));
166
 
167
        foreach ($rules as $rule) {
168
            try {
169
                if (null !== $this->cssConverter) {
170
                    $expression = $this->cssConverter->toXPath($rule->getSelector());
171
                } else {
172
                    // Compatibility layer for Symfony 2.7 and older
173
                    $expression = CssSelector::toXPath($rule->getSelector());
174
                }
175
            } catch (ExceptionInterface $e) {
176
                continue;
177
            }
178
 
179
            $elements = $xPath->query($expression);
180
 
181
            if ($elements === false) {
182
                continue;
183
            }
184
 
185
            foreach ($elements as $element) {
186
                $propertyStorage[$element] = $this->calculatePropertiesToBeApplied(
187
                    $rule->getProperties(),
188
                    $propertyStorage->contains($element) ? $propertyStorage[$element] : array()
189
                );
190
            }
191
        }
192
 
193
        foreach ($propertyStorage as $element) {
194
            $this->inlineCssOnElement($element, $propertyStorage[$element]);
195
        }
196
 
197
        return $document;
198
    }
199
 
200
    /**
201
     * Merge the CSS rules to determine the applied properties.
202
     *
203
     * @param Css\Property\Property[] $properties
204
     * @param Css\Property\Property[] $cssProperties existing applied properties indexed by name
205
     *
206
     * @return Css\Property\Property[] updated properties, indexed by name
207
     */
208
    private function calculatePropertiesToBeApplied(array $properties, array $cssProperties)
209
    {
210
        if (empty($properties)) {
211
            return $cssProperties;
212
        }
213
 
214
        foreach ($properties as $property) {
215
            if (isset($cssProperties[$property->getName()])) {
216
                $existingProperty = $cssProperties[$property->getName()];
217
 
218
                //skip check to overrule if existing property is important and current is not
219
                if ($existingProperty->isImportant() && !$property->isImportant()) {
220
                    continue;
221
                }
222
 
223
                //overrule if current property is important and existing is not, else check specificity
224
                $overrule = !$existingProperty->isImportant() && $property->isImportant();
225
                if (!$overrule) {
226
                    $overrule = $existingProperty->getOriginalSpecificity()->compareTo($property->getOriginalSpecificity()) <= 0;
227
                }
228
 
229
                if ($overrule) {
230
                    unset($cssProperties[$property->getName()]);
231
                    $cssProperties[$property->getName()] = $property;
232
                }
233
            } else {
234
                $cssProperties[$property->getName()] = $property;
235
            }
236
        }
237
 
238
        return $cssProperties;
239
    }
240
}