Skip to content

Commit

Permalink
Merge pull request #65 from WyriHaximus/fix-62
Browse files Browse the repository at this point in the history
Strip CSS comments from <style> tags
  • Loading branch information
WyriHaximus authored Sep 8, 2019
2 parents 92e31e8 + fe2ac77 commit d1d2f1b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Pattern/Style.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@

final class Style implements PatternInterface
{
private const ZERO = 0;
private const CSS_COMMENT_OPEN = '<!--';
private const CSS_COMMENT_OPEN_LENGTH = 4;
private const CSS_COMMENT_CLOSE = '-->';

/** @var CompressorInterface */
private $compressor;

Expand All @@ -25,6 +30,7 @@ public function compress(SimpleHtmlDomInterface $element): void
{
/** @var string $innerHtml */
$innerHtml = $element->innerhtml;
$innerHtml = $this->stripComments($innerHtml);
$compressedInnerHtml = $this->compressor->compress($innerHtml);

if ($compressedInnerHtml === '') {
Expand All @@ -37,4 +43,18 @@ public function compress(SimpleHtmlDomInterface $element): void

$element->innerhtml = $compressedInnerHtml;
}

private function stripComments(string $contents): string
{
if (\strpos($contents, self::CSS_COMMENT_OPEN) === self::ZERO) {
$contents = \substr($contents, self::CSS_COMMENT_OPEN_LENGTH);
}

$pos = \strpos($contents, self::CSS_COMMENT_CLOSE);
if ($pos !== false) {
$contents = \substr($contents, self::ZERO, $pos);
}

return $contents;
}
}
7 changes: 7 additions & 0 deletions tests/EdgeCases/css-wrapped-in-comments/in.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<style>
<!--
h1 {
color: red;
}
-->
</style>
1 change: 1 addition & 0 deletions tests/EdgeCases/css-wrapped-in-comments/out.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<style>h1{color:red}</style>

0 comments on commit d1d2f1b

Please sign in to comment.