Created
December 7, 2012 19:32
Css Minification on the Fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once('../includes/utils.php'); | |
/** | |
* minify | |
* | |
* Class that handles the minification of all required CSS files | |
*/ | |
class minify | |
{ | |
public $css = ''; | |
public $changed = false; | |
public $fileLastModified; | |
private $RequestedFiles = array(); | |
/** | |
* __constructor() | |
* | |
* Builds the minified string | |
* | |
* @param array $GET | |
*/ | |
function __construct($GET) | |
{ | |
foreach($GET as $key => $val) { | |
if(util::strContains($key, 'css_')) { | |
$fileName = urldecode($val); | |
$this->RequestedFiles[] = $fileName; | |
if(!empty($_SESSION['lastRequestedCSS']) && !in_array($fileName, $_SESSION['lastRequestedCSS'])) { | |
$this->changed = true; | |
} | |
} | |
} | |
$_SESSION['lastRequestedCSS'] = $this->RequestedFiles; | |
foreach($GET as $key => $val) { | |
if(util::strContains($key, 'css_')) { | |
$fileName = urldecode($val) . '.css'; | |
$fileModified = filemtime($fileName); | |
if(empty($this->lastModified) || $fileModified > $this->lastModified) { | |
$this->lastModified = $fileModified; | |
} | |
$strFileContents = file_get_contents($fileName); | |
if($strFileContents) { | |
$this->css .= $this->doMinify($strFileContents) . "\r\n"; | |
} | |
} | |
} | |
} | |
/** | |
* doMinify() | |
* | |
* Perform the minification on the passed in string | |
* | |
* @param string $strFile | |
* | |
* @return string | |
*/ | |
private function doMinify($strFile) | |
{ | |
/* Strips Comments */ | |
$strFile = preg_replace('!/\*.*?\*/!s','', $strFile); | |
$strFile = preg_replace('/\n\s*\n/',"\n", $strFile); | |
/* Minifies */ | |
$strFile = preg_replace('/[\n\r \t]/',' ', $strFile); | |
$strFile = preg_replace('/ +/',' ', $strFile); | |
$strFile = preg_replace('/ ?([,:;{}]) ?/','$1',$strFile); | |
/* Kill Trailing Semicolon */ | |
$strFile = preg_replace('/;}/','}',$strFile); | |
/* Return Minified CSS */ | |
return $strFile; | |
} | |
} | |
session_start(); | |
$minifier = new minify($_GET); | |
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $minifier->lastModified) . " GMT"); | |
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $minifier->lastModified) { | |
header("HTTP/1.1 304 Not Modified"); | |
exit; | |
} | |
header('Content-type: text/css'); | |
echo $minifier->css; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment