Wednesday 17 October 2012

LessCSS Auto-compile in PHP

I don't have the attributions for where this comes from but it works perfectly for me.

Include this code in your main template file, so it gets run every time.

PseudoCode: If we're on a development server, re-compile the css.


// Auto versioning using PHP, only when on localhost and debugging
if ($this->debug) {
    include($_SERVER['DOCUMENT_ROOT'].'/includes/autoCompileLess.php');  
    auto_compile_less($_SERVER['DOCUMENT_ROOT'].'/css/less/style.less', $_SERVER['DOCUMENT_ROOT'].'/css/styleCompiled.css');
}

This is the code for the autoCompileLess.php. It checks a cache file, and if that file is newer than my main LessCSS file it'll use the cache rather than re-compiling.

PseudoCode: Check the modified times of the cached compiled css, and if that is newer than the main less css file use the cache. Otherwise recompile all the less.


require 'lessc.inc.php';

function auto_compile_less($less_fname, $css_fname) {  
    $cache = $less_fname;
   
    // We may want to load from the cache
    $cache_fname = $less_fname.".cache";
    if (file_exists($cache_fname)) {      
        // Use the cache if the filetime is newer
        $cacheTime = filemtime($cache_fname);
        $fileTime = filemtime($less_fname);
        // If I managed to read both and the cache is still relevant, use it
        if ($cacheTime && $fileTime && $fileTime < $cacheTime) {
            $cache = unserialize(file_get_contents($cache_fname));
        }
    }

    $new_cache = lessc::cexecute($cache);
    if (!is_array($cache) || $new_cache['updated'] > $cache['updated']) {      
        file_put_contents($css_fname, $new_cache['compiled']);
        file_put_contents($cache_fname, serialize($new_cache));
    }
}

A bit of googling should get you all the necessary files you need. Perhaps this site, http://leafo.net/lessphp/, would be a good place to start.

Happy coding!