1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TijsVerkoyen\CssToInlineStyles\Css; |
4
|
|
|
|
5
|
|
|
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor; |
6
|
|
|
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Rule; |
7
|
|
|
|
8
|
|
|
class Processor |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Get the rules from a given CSS-string |
12
|
|
|
* |
13
|
|
|
* @param string $css |
14
|
|
|
* @param Rule[] $existingRules |
15
|
|
|
* |
16
|
|
|
* @return Rule[] |
17
|
|
|
*/ |
18
|
|
|
public function getRules($css, $existingRules = array()) |
19
|
|
|
{ |
20
|
|
|
$css = $this->doCleanup($css); |
21
|
|
|
$rulesProcessor = new RuleProcessor(); |
22
|
|
|
$rules = $rulesProcessor->splitIntoSeparateRules($css); |
23
|
|
|
|
24
|
|
|
return $rulesProcessor->convertArrayToObjects($rules, $existingRules); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Get all media queries from the given css string. Returns an empty array |
29
|
|
|
* when non were found. |
30
|
|
|
* |
31
|
|
|
* @param string $css |
32
|
|
|
* |
33
|
|
|
* @return string[] |
34
|
|
|
*/ |
35
|
|
|
public function getMediaQueries($css) |
36
|
|
|
{ |
37
|
|
|
if (preg_match_all('/@media [^{]*+{([^{}]++|{[^{}]*+})*+}/', $css, $matches)) { |
38
|
|
|
return $matches[0]; |
39
|
|
|
} |
40
|
|
|
return array(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Get the CSS from the style-tags in the given HTML-string |
45
|
|
|
* |
46
|
|
|
* @param string $html |
47
|
|
|
* |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
|
|
public function getCssFromStyleTags($html) |
51
|
|
|
{ |
52
|
|
|
$css = ''; |
53
|
|
|
$matches = array(); |
54
|
|
|
$htmlNoComments = preg_replace('|<!--.*?-->|s', '', $html); |
55
|
|
|
preg_match_all('|<style(?:\s.*)?>(.*)</style>|isU', $htmlNoComments, $matches); |
56
|
|
|
|
57
|
|
|
if (!empty($matches[1])) { |
58
|
|
|
foreach ($matches[1] as $match) { |
59
|
|
|
$css .= trim($match) . "\n"; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $css; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $css |
68
|
|
|
* |
69
|
|
|
* @return string |
70
|
|
|
*/ |
71
|
|
|
private function doCleanup($css) |
72
|
|
|
{ |
73
|
|
|
// remove charset |
74
|
|
|
$css = preg_replace('/@charset "[^"]++";/', '', $css); |
75
|
|
|
// remove media queries |
76
|
|
|
$css = preg_replace('/@media [^{]*+{([^{}]++|{[^{}]*+})*+}/', '', $css); |
77
|
|
|
|
78
|
|
|
$css = str_replace(array("\r", "\n"), '', $css); |
79
|
|
|
$css = str_replace(array("\t"), ' ', $css); |
80
|
|
|
$css = str_replace('"', '\'', $css); |
81
|
|
|
$css = preg_replace('|/\*.*?\*/|', '', $css); |
82
|
|
|
$css = preg_replace('/\s\s++/', ' ', $css); |
83
|
|
|
$css = trim($css); |
84
|
|
|
|
85
|
|
|
return $css; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|