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 empty props and better empty tags removal #345

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
20 changes: 19 additions & 1 deletion src/CSS.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ public function execute($path = null, $parents = array())
$this->extractCustomProperties();
$css = $this->replace($css);

$css = $this->stripEmptyProperties($css);
$css = $this->stripWhitespace($css);
$css = $this->shortenColors($css);
$css = $this->shortenZeroes($css);
Expand Down Expand Up @@ -621,12 +622,29 @@ protected function shortenZeroes($content)
*/
protected function stripEmptyTags($content)
{
// Remove empty tags/selectors at the start of the file
$content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
$content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
// Remove empty tags/selectors (classes, ids and so on)
$content = preg_replace('/(?<=(\}|;|\{))[^\{\};]+\{\s*\}/', '', $content);
// Run it again to remove any empty media queries that had the empty selectors before
$content = preg_replace('/(?<=(\}|;|\{))[^\{\};]+\{\s*\}/', '', $content);

return $content;
}

/**
* Strip empty properties from source code.
* i.e: 'color: ;'
*
* @param string $content
*
* @return string
*/
protected function stripEmptyProperties($content)
{
return preg_replace('/[a-zA-Z-:().#]*:\s*;/', '', $content);
}

/**
* Strip comments from source code.
*/
Expand Down
38 changes: 38 additions & 0 deletions tests/css/CSSTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,44 @@ public function dataProvider()
'ul p{padding-left:calc((var(--icon-size) / 2) + var(--horisontal-space))}',
);

$tests[] = array('
body{
background: white;
}

.classWithEmptyProperties {
color::hover: ;
font-size: ;
font-weight::hover:not(#id.class): ;
}

@media(max-width: 576px) {
.emptyClass {
}

.nonEmptyClass {
display: flex;
--myColorVar: #fff;
color: var(--myColorVar);
}
}

@media(max-width: 850px) {
.emptyClassWithEmptyProperties {
color: ;
--myEmptyColor: ;
}

#emptyId {
}
}

@media(max-width: 1580px) {
#emptyId {
}
}
', 'body{background:#fff}@media(max-width:576px){.nonEmptyClass{display:flex;--myColorVar: #fff;color: var(--myColorVar)}}',

// https://github.com/matthiasmullie/minify/issues/351
$tests[] = array(
'clamp(2.5rem, 1rem + 4vw, 4rem)',
Expand Down