Completed
Pull Request — master (#208)
by
unknown
01:28
created

CssToInlineStyles::getLastLibxmlErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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