Completed
Pull Request — master (#211)
by
unknown
01:41
created

Processor::trimHtmlComments()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace TijsVerkoyen\CssToInlineStyles\Css;
4
5
use DOMDocument;
6
use DOMElement;
7
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor;
8
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Rule;
9
10
class Processor
11
{
12
    /**
13
     * Get the rules from a given CSS-string
14
     *
15
     * @param string $css
16
     * @param Rule[] $existingRules
17
     *
18
     * @return Rule[]
19
     */
20
    public function getRules($css, $existingRules = array())
21
    {
22
        $css = $this->doCleanup($css);
23
        $rulesProcessor = new RuleProcessor();
24
        $rules = $rulesProcessor->splitIntoSeparateRules($css);
25
26
        return $rulesProcessor->convertArrayToObjects($rules, $existingRules);
27
    }
28
29
    /**
30
     * Get the CSS from the style-tags in the given HTML-string
31
     *
32
     * @param string $html
33
     *
34
     * @return string
35
     */
36
    public function getCssFromStyleTags($html)
37
    {
38
        $document = new DOMDocument('1.0', 'UTF-8');
39
        $internalErrors = libxml_use_internal_errors(true);
40
        $document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
41
        libxml_use_internal_errors($internalErrors);
42
43
        $css = '';
44
45
        /** @var DOMElement $style */
46
        foreach ($document->getElementsByTagName('style') as $style) {
47
            $css .= $this->trimHtmlComments($style->nodeValue) . "\n";
48
        }
49
50
        return $css;
51
    }
52
53
    /**
54
     * @param string $css
55
     * @return string
56
     */
57
    protected function trimHtmlComments($css)
58
    {
59
        $css = trim($css);
60
        if (strncmp('<!--', $css, 4) === 0) {
61
            $css = substr($css, 4);
62
        }
63
64
        if (strlen($css) > 3 && substr($css, -3) === '-->') {
65
            $css = substr($css, 0, -3);
66
        }
67
68
        return trim($css);
69
    }
70
71
    /**
72
     * @param string $css
73
     *
74
     * @return string
75
     */
76
    private function doCleanup($css)
77
    {
78
        // remove charset
79
        $css = preg_replace('/@charset "[^"]++";/', '', $css);
80
        // remove media queries
81
        $css = preg_replace('/@media [^{]*+{([^{}]++|{[^{}]*+})*+}/', '', $css);
82
83
        $css = str_replace(array("\r", "\n"), '', $css);
84
        $css = str_replace(array("\t"), ' ', $css);
85
        $css = str_replace('"', '\'', $css);
86
        $css = preg_replace('|/\*.*?\*/|', '', $css);
87
        $css = preg_replace('/\s\s++/', ' ', $css);
88
        $css = trim($css);
89
90
        return $css;
91
    }
92
}
93