Skip to content

Commit

Permalink
add stringhelper minify tests and comments option #1791
Browse files Browse the repository at this point in the history
  • Loading branch information
nadar committed Apr 12, 2018
1 parent 3721262 commit 917ec1e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
24 changes: 19 additions & 5 deletions core/helpers/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,28 @@ public static function contains($needle, $haystack, $strict = false)
}

/**
* Minify html by removing spaces, tabs.
* "Minify" html content.
*
* @param string $content
* @return mixed
* + remove space
* + remove tabs
* + remove newlines
* + remove html comments
*
* @param string $content The content to minify.
* @param array $options Optional arguments to provide for minification:
* - comments: boolean, where html comments should be removed or not. defaults to false
* @return mixed Returns the minified content.
* @since 1.0.7
*/
public static function minify($content)
public static function minify($content, array $options = [])
{
return preg_replace(['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], trim($content));
$min = preg_replace(['/[\n\r]/', '/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', ], ['', '>', '<', '\\1'], trim($content));
$min = str_replace(['> <'], ['><'], $min);

if (ArrayHelper::getValue($options, 'comments', false)) {
$min = preg_replace('/<!--(.*)-->/Uis', '', $min);
}

return $min;
}
}
36 changes: 36 additions & 0 deletions tests/core/helpers/StringHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,40 @@ public function testStartsWithWildcard()
$this->assertFalse(StringHelper::startsWithWildcard('ABCDEFGHI', 'abc*'));
$this->assertTrue(StringHelper::startsWithWildcard('ABCDEFGHI', 'abc*', false));
}

public function testMinify()
{
$this->assertSame('foo bar', StringHelper::minify(' foo bar '));
$content = <<<EOT
foo
bar
EOT;
$this->assertSame('foo bar', StringHelper::minify($content));
$html = <<<EOT
<html>
<head>
<title>foobar</title>
<script>
function alert = function(msg) {
console.log(msg);
};
</script>
</head>
<body>
<p>foo bar</p> <p>bar foo</p> <p>qux</p>
</body>
</html>
EOT;

$this->assertSame('<html><head><title>foobar</title><script> function alert = function(msg) { console.log(msg); }; </script></head><body><p>foo bar</p><p>bar foo</p><p>qux</p></body></html>', StringHelper::minify($html));

$comment = <<<EOT
<div>
<p>foo bar</p>
<!-- foo bar end is near! -->
</div>
EOT;
$this->assertSame('<div><p>foo bar</p></div>', StringHelper::minify($comment, ['comments' => true]));
}
}

0 comments on commit 917ec1e

Please sign in to comment.