Skip to content

Instantly share code, notes, and snippets.

@darren131
Forked from steveh/README.md
Created May 1, 2014 03:30
Show Gist options
  • Save darren131/dafdd74bee837d0750b6 to your computer and use it in GitHub Desktop.
Save darren131/dafdd74bee837d0750b6 to your computer and use it in GitHub Desktop.

INSTALLATION

  1. Save script to e.g. /usr/local/bin/media-query-combiner
  2. chmod +x /usr/local/bin/media-query-combiner

USAGE

Reads from stdin and writes to stdout. Returns error code 0 on success, or >0 on failure, with an error message on stderr.

EXAMPLE

media-query-combiner < input.css > output.css

#!/usr/bin/env php
<?php
// helps for large CSS files
ini_set('pcre.backtrack_limit', '10000000');
// from https://github.com/aaronjensen/sass-media_query_combiner
$pattern = '/
\\n? # Optional newline
(?<query> # The media query parameters, this will be $1
@media # Start with @media
(?!\ -sass-debug-info) # Ignore sass-debug-info
[^{]+ # One to many characters that are not {, we are guaranteed to have a space
)
{
(?<body> # The actual body, this will be $2
(?<braces> # Recursive capture group
(?:
[^{}]* # Anything that is not a brace
| # OR
{\g<braces>} # Recursively capture things within braces, this allows for balanced braces
)* # As many of these as we have
)
)
}
\\n? # Optional newline
/mx';
$css = file_get_contents('php://stdin');
$stdout = fopen('php://stdout', 'w');
$stderr = fopen('php://stderr', 'w');
// combined media queries
$combinedQueries = array();
// function ($match) use ($combined) { ... } doesn't seem to work
$otherCSS = preg_replace_callback($pattern, function ($match) {
global $combinedQueries;
$query = $match[1];
$body = $match[2];
if (!isset($combinedQueries[$query])) {
$combinedQueries[$query] = array();
}
$combinedQueries[$query][] = $body;
// replace media query in CSS with nothing; it's in $combined for now instead
return '';
}, $css);
$lastError = preg_last_error();
if ($lastError === PREG_NO_ERROR) {
fwrite($stdout, $otherCSS . "\n");
foreach ($combinedQueries as $query => $bodies) {
$combinedQuery = $query . '{' . join($bodies, "\n") . '}';
fwrite($stdout, $combinedQuery . "\n");
}
} else {
// http://www.php.net/manual/en/pcre.constants.php
$lastErrorName = array_flip(get_defined_constants(true)['pcre'])[$lastError];
fwrite($stderr, $lastErrorName . "\n");
}
exit($lastError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment