Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix parsing of HTML comments within style elements #211

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions src/Css/Processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace TijsVerkoyen\CssToInlineStyles\Css;

use DOMDocument;
use DOMElement;
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Processor as RuleProcessor;
use TijsVerkoyen\CssToInlineStyles\Css\Rule\Rule;

Expand Down Expand Up @@ -33,20 +35,39 @@ public function getRules($css, $existingRules = array())
*/
public function getCssFromStyleTags($html)
{
$document = new DOMDocument('1.0', 'UTF-8');
$internalErrors = libxml_use_internal_errors(true);
$document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
libxml_use_internal_errors($internalErrors);

$css = '';
$matches = array();
$htmlNoComments = preg_replace('|<!--.*?-->|s', '', $html);
preg_match_all('|<style(?:\s.*)?>(.*)</style>|isU', $htmlNoComments, $matches);

if (!empty($matches[1])) {
foreach ($matches[1] as $match) {
$css .= trim($match) . "\n";
}
/** @var DOMElement $style */
foreach ($document->getElementsByTagName('style') as $style) {
$css .= $this->trimHtmlComments($style->nodeValue) . "\n";
}

return $css;
}

/**
* @param string $css
* @return string
*/
protected function trimHtmlComments($css)
{
$css = trim($css);
if (strncmp('<!--', $css, 4) === 0) {
$css = substr($css, 4);
}

if (strlen($css) > 3 && substr($css, -3) === '-->') {
$css = substr($css, 0, -3);
}

return trim($css);
}

/**
* @param string $css
*
Expand Down
17 changes: 17 additions & 0 deletions tests/Css/ProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,23 @@ public function testStyleTagsInCommentInHtml()
<p>foo</p>
</body>
</html>
EOF
)
);
}

public function testHtmlCommentsInStyle()
{
$expected = 'p{color:blue}' . "\n";
$this->assertEquals(
$expected,
$this->processor->getCssFromStyleTags(
<<<EOF
<!doctype html>
<html>
<head><style><!-- p{color:blue} --></style></head>
<body><p>foo</p></body>
</html>
EOF
)
);
Expand Down