Skip to content

Commit

Permalink
Remove Duplicate CSS Selectors from the final content
Browse files Browse the repository at this point in the history
i noticed that if i add two of the same (or content) the script will still show them, and that will add up to the final file size (content).

for instance if i add default.css and default.css?v=1 and both have 'body{font-family:xx}, the final file will contain both files contents resulting in duplicate css selectors.

i added a method which gets all css selectors and array_unique that with implode of a NULL glue.

that will save a lot of data. for the example files i gave here it will cut the file size (and content) to half.
  • Loading branch information
emadha committed Feb 7, 2018
1 parent 62dac3b commit 1169514
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/CSS.php
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,10 @@ protected function importFiles($source, $content)
* Perform CSS optimizations.
*
* @param string[optional] $path Path to write the data to
* @param string[] $parents Parent paths, for circular reference checks
* @param string[] $parents Parent paths, for circular reference checks
*
* @return string The minified data
* @throws FileImportException
*/
public function execute($path = null, $parents = array())
{
Expand Down Expand Up @@ -337,6 +338,37 @@ public function execute($path = null, $parents = array())

$content = $this->moveImportsToTop($content);

/*
* After getting the merged data of all css files
* this method here will remove duplicate css selectors
* for instance, a user might add two css files like default.css & default.css?v=1
* both files contain the same selectors "body {font-family: xxx}"
* this method will deal with those duplicates and remove them from the final content.
*/
$content = $this->removeDuplicates($content);

return $content;
}

/**
* Remove Duplicate CSS Selectors
* for example if there is duplicate body{font-size:13px}
* this method will return one selector
*
* @param $content
* @return string
*/
private function removeDuplicates($content)
{

// Collect Selectors
preg_match_all('/(?ims)([a-z0-9, \s\.\:#_\-@]+)\{([^\}]*)\}/', $content, $selectors);

if (isset($selectors[0]))

// return a unique array of selectors and implode it into a string
return implode(null, array_unique($selectors[0]));

return $content;
}

Expand Down

0 comments on commit 1169514

Please sign in to comment.