Skip to content

Commit

Permalink
Refactor removing style tags
Browse files Browse the repository at this point in the history
This uses xPath to find the style tags and either remove the style tag completely, or replace them with just the media queries, based on the excludeMediaQueries flag.
This follows the logic that if the mediaqueries are excluded from inlining, they should not be stripped from the document, because they aren't processed.
If for some reason they are processed (don't know the use case) they can just be removed.
  • Loading branch information
barryvdh committed Jul 26, 2014
1 parent 3dcfeae commit 1200bb0
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions src/CssToInlineStyles.php
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,11 @@ public function convert($outputXHTML = false)
}
}

// strip original style tags if we need to
if ($this->stripOriginalStyleTags) {
$this->stripOriginalStyleTags($xPath);
}

// should we output XHTML?
if ($outputXHTML) {
// set formating
Expand Down Expand Up @@ -391,11 +396,6 @@ public function convert($outputXHTML = false)
$html = $this->cleanupHTML($html);
}

// strip original style tags if we need to
if ($this->stripOriginalStyleTags) {
$html = $this->stripOriginalStyleTags($html);
}

// return
return $html;
}
Expand Down Expand Up @@ -625,11 +625,25 @@ public function setExcludeMediaQueries($on = true)
* Strip style tags into the generated HTML
*
* @return string
* @param string $html The HTML to strip style tags.
* @param \DOMXPath $xPath The DOMXPath for the entire document.
*/
private function stripOriginalStyleTags($html)
private function stripOriginalStyleTags(\DOMXPath $xPath)
{
return preg_replace('|<style(.*)>(.*)</style>|isU', '', $html);
// Get all style tags
$nodes = $xPath->query('descendant-or-self::style');

foreach ($nodes as $node) {
if ($this->excludeMediaQueries) {
//Search for Media Queries
preg_match_all('/@media [^{]*{([^{}]|{[^{}]*})*}/', $node->nodeValue, $mqs);

// Replace the nodeValue with just the Media Queries
$node->nodeValue = implode("\n", $mqs[0]);
} else {
// Remove the entire style tag
$node->parentNode->removeChild($node);
}
}
}

/**
Expand Down

0 comments on commit 1200bb0

Please sign in to comment.