Skip to content

Instantly share code, notes, and snippets.

@willyarisky
Created October 18, 2024 23:58
Show Gist options
  • Save willyarisky/a1ac8c70d147236894c123f4fe0352e8 to your computer and use it in GitHub Desktop.
Save willyarisky/a1ac8c70d147236894c123f4fe0352e8 to your computer and use it in GitHub Desktop.
Compile SCSS files with PHP / SCSS PHP Compiler
<?php
require 'resources/vendor/autoload.php';
use ScssPhp\ScssPhp\Compiler;
$scss = new Compiler();
// Set the import paths for Bootstrap SCSS and other directories
$scss->setImportPaths('resources/scss');
// Define the paths to the SCSS files
$scssFiles = [
'resources/scss/main.scss',
'resources/scss/style.scss',
];
// Define the target directory for the compiled CSS files
$targetDir = 'assets/css/';
// Function to get the last modified time of a file
function getLastModifiedTime($file) {
return file_exists($file) ? filemtime($file) : 0;
}
// Function to get the file size in a human-readable format
function humanFileSize($size) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
// Get the initial last modified times of all SCSS files
$lastModifiedTimes = [];
foreach ($scssFiles as $file) {
$lastModifiedTimes[$file] = getLastModifiedTime($file);
}
// Infinite loop to watch for file changes
while (true) {
clearstatcache(); // Clears the file status cache
foreach ($scssFiles as $file) {
$newModifiedTime = getLastModifiedTime($file);
// If the file has been modified, recompile it
if ($newModifiedTime > $lastModifiedTimes[$file]) {
echo "Detected changes in {$file}, recompiling...\n";
// Start timing the compilation
$startTime = microtime(true);
// Get the content of the SCSS file
$scssCode = file_get_contents($file);
// Compile the SCSS into CSS
try {
$cssCode = $scss->compile($scssCode);
// Get the filename without the extension (e.g., main, style)
$fileName = basename($file, '.scss');
// Define the full path to the target CSS file
$cssFilePath = $targetDir . $fileName . '.css';
// Write the compiled CSS to the target file
file_put_contents($cssFilePath, $cssCode);
// Calculate the compilation time
$compilationTime = microtime(true) - $startTime;
// Get the size of the SCSS and compiled CSS files
$scssFileSize = filesize($file);
$cssFileSize = filesize($cssFilePath);
echo "Compiled and saved {$file} to {$cssFilePath} in " . round($compilationTime, 4) . " seconds.\n";
echo "SCSS file size: " . humanFileSize($scssFileSize) . "\n";
echo "CSS file size: " . humanFileSize($cssFileSize) . "\n";
// Update the last modified time after successful compilation
$lastModifiedTimes[$file] = $newModifiedTime;
} catch (Exception $e) {
echo "Error compiling SCSS: " . $e->getMessage() . "\n";
}
}
}
// Sleep for 2 seconds before checking again
sleep(2);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment