| 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 the CSS from the style-tags in the given HTML-string |
| 29 |
* |
| 30 |
* @param string $html |
| 31 |
* |
| 32 |
* @return string |
| 33 |
*/ |
| 34 |
public function getCssFromStyleTags($html) |
| 35 |
{ |
| 36 |
$css = ''; |
| 37 |
$matches = array(); |
| 38 |
$htmlNoComments = preg_replace('|<!--.*?-->|s', '', $html) ?? $html; |
| 39 |
preg_match_all('|<style(?:\s.*)?>(.*)</style>|isU', $htmlNoComments, $matches); |
| 40 |
|
| 41 |
if (!empty($matches[1])) { |
| 42 |
foreach ($matches[1] as $match) { |
| 43 |
$css .= trim($match) . "\n"; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
return $css; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* @param string $css |
| 52 |
* |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
private function doCleanup($css) |
| 56 |
{ |
| 57 |
// remove charset |
| 58 |
$css = preg_replace('/@charset "[^"]++";/', '', $css) ?? $css; |
| 59 |
// remove media queries |
| 60 |
$css = preg_replace('/@media [^{]*+{([^{}]++|{[^{}]*+})*+}/', '', $css) ?? $css; |
| 61 |
|
| 62 |
$css = str_replace(array("\r", "\n"), '', $css); |
| 63 |
$css = str_replace(array("\t"), ' ', $css); |
| 64 |
$css = str_replace('"', '\'', $css); |
| 65 |
$css = preg_replace('|/\*.*?\*/|', '', $css) ?? $css; |
| 66 |
$css = preg_replace('/\s\s++/', ' ', $css) ?? $css; |
| 67 |
$css = trim($css); |
| 68 |
|
| 69 |
return $css; |
| 70 |
} |
| 71 |
} |
| 72 |
|