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

Strip CSS comments from <style> tags #65

Merged
merged 1 commit into from
Sep 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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>