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

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