Created
March 28, 2023 04:18
-
-
Save pakjiddat/02e7cdd79a66363e7527d20d9147cbc3 to your computer and use it in GitHub Desktop.
Recursively scans folder for CSS files. Compresses the CSS code in place using Toptal CSS compressor webservice
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 | |
$dir = '{absolute path to css folder}'; | |
$files_and_dirs = ListAllFiles($dir); | |
$files = GetFiles($files_and_dirs); | |
CompressFiles($files); | |
function CompressFiles($files) { | |
for ($count = 0; $count < count($files); $count++) { | |
$contents = file_get_contents($files[$count]); | |
$url = 'https://www.toptal.com/developers/cssminifier/api/raw'; | |
// init the request, set various options, and send it | |
$ch = curl_init(); | |
curl_setopt_array($ch, [ | |
CURLOPT_URL => $url, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_POST => true, | |
CURLOPT_HTTPHEADER => ["Content-Type: application/x-www-form-urlencoded"], | |
CURLOPT_POSTFIELDS => http_build_query([ "input" => $contents ]) | |
]); | |
$minified = curl_exec($ch); | |
// finally, close the request | |
curl_close($ch); | |
$fh = fopen($files[$count], "w"); | |
fwrite($fh, $minified); | |
fclose($fh); | |
echo "Updated file: " . $files[$count] . "\r\n"; | |
sleep(2); | |
} | |
} | |
function GetFiles($items) { | |
$data = array(); | |
for ($count = 0; $count < count($items); $count++) { | |
$item = $items[$count]; | |
if(strpos($item, "top.css") !== false || strpos($item, "middle.css") !== false) { | |
$data[] = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $item); | |
} | |
} | |
return $data; | |
} | |
function ListAllFiles($dir) { | |
$array = array_diff(scandir($dir), array('.', '..')); | |
foreach ($array as &$item) { | |
$item = $dir . DIRECTORY_SEPARATOR . $item; | |
} | |
unset($item); | |
foreach ($array as $item) { | |
if (is_dir($item)) { | |
$array = array_merge($array, ListAllFiles($item . DIRECTORY_SEPARATOR)); | |
} | |
} | |
return $array; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment