Last active
July 31, 2020 03:31
-
-
Save janstieler/977dd89a33b1cd7ddece015eb7021dd1 to your computer and use it in GitHub Desktop.
PHP function for compress .css or .js files with a timestamp.
This file contains hidden or 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 | |
function compressFiles(array $files){ | |
$debug = false; | |
$buffer = ''; | |
$firstFile = $files[0]; | |
if($debug === true){ | |
switch(pathinfo($firstFile)['extension']){ | |
case 'css': | |
foreach ($files as $file) { | |
if (!$ftime = filemtime($file)) { | |
return $file; | |
} | |
$outputTime = $file.'?time='.$ftime; | |
echo '<link rel="stylesheet" type="text/css" href="' . $outputTime . '" media="screen">'; | |
} | |
break; | |
case 'js': | |
foreach ($files as $file) { | |
if (!$ftime = filemtime($file)) { | |
return $file; | |
} | |
$outputTime = $file.'?time='.$ftime; | |
echo '<script src="' . $outputTime . '" type="text/javascript"></script>'; | |
} | |
break; | |
} | |
} | |
else { | |
switch(pathinfo($firstFile)['extension']){ | |
case 'css': | |
$outputFile = '../../assets/css/style.min.css'; | |
break; | |
case 'js': | |
$outputFile = '../../assets/js/script.min.js'; | |
break; | |
} | |
foreach ($files as $file) { | |
$buffer .= file_get_contents($file); | |
} | |
// Remove comments | |
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); | |
// Remove space after colons | |
$buffer = str_replace(': ', ':', $buffer); | |
// Remove whitespace | |
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); | |
// Write everything out | |
file_put_contents($outputFile, $buffer); | |
if (!$ftime = filemtime($outputFile)) { | |
return $outputFile; | |
} | |
$outputTime = $outputFile.'?time='.$ftime; | |
switch(pathinfo($outputFile)['extension']){ | |
case 'css': | |
echo '<link rel="stylesheet" type="text/css" href="' . $outputTime . '" media="screen">'; | |
break; | |
case 'js': | |
echo '<script src="' . $outputTime . '" type="text/javascript"></script>'; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment