Skip to content

Instantly share code, notes, and snippets.

@fhferreira
Last active December 17, 2015 16:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhferreira/5643073 to your computer and use it in GitHub Desktop.
Save fhferreira/5643073 to your computer and use it in GitHub Desktop.
<?php
class Minify
{
private function _minify($file) {
/* remove comments */
$lines = explode("\n", $file);
$lines = array_map(
function($line) {
return preg_replace("@\s*//.*$@", '', $line);
},
$lines
);
$file = implode("\n", $lines);
/* remove tabs, spaces, newlines, etc. */
$file = str_replace(array("\r\n","\r","\n","\t"," "," "," "), "", $file);
/* remove other spaces before/after ) */
$file = preg_replace(array('(( )+\))','(\)( )+)'), ')', $file);
return $file;
}
public MultipleMinifyJs($files, $filepath = "js/min/")
{
if( !is_array($files) ){
trown new Exception("$files not is an array.");
}
foreach($files as $file) {
$fileName .= str_replace("js/", "",str_replace(".js", "",$file)).'.';
$minified .= $this->_minify(file_get_contents($file));
}
$fileNamePath = $filepath.$fileName.'min.js';
file_exists($fileNamePath) ? $modified = date('M d Y H:i', filemtime($fileNamePath)) : $exists = false ;
if ((isset($modified) && $modified < date('M d Y H:i')) || $exists === false)
{
is_writable($fileNamePath) ? $handle = fopen($fileNamePath, 'w') : return false ;
fwrite($handle, $minified);
fclose($handle);
}
return $fileNamePath;
}
public MultipleMinifyCss($files, $filepath = "css/min/")
{
if( !is_array($files) ){
trown new Exception("$files not is an array.");
}
foreach($files as $file) {
$fileName .= str_replace("css/", "",str_replace(".css", "",$file)).'.';
$minified .= $this->_minify(file_get_contents($file));
}
$fileNamePath = $filepath.$fileName.'min.css';
file_exists($fileNamePath) ? $modified = date('M d Y H:i', filemtime($fileNamePath)) : $exists = false ;
if ((isset($modified) && $modified < date('M d Y H:i')) || $exists === false)
{
is_writable($fileNamePath) ? $handle = fopen($fileNamePath, 'w') : return false ;
fwrite($handle, $minified);
fclose($handle);
}
return $fileNamePath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment