Stolz/Assets

Easily extend with pre-processors like Less/SASS/CoffeeScript/...

justb81 opened this issue · 1 comments

It would be great if one can hook on file-extensions with callbacks. This way you can extend this great and simply asset manager.

The library doesn't support prepocessors out of the box. Indeed, the main reason I developed this library is beacuse I don't compile my assets so I wanted something really simple for my really simple scenarios.

However, if you are using the pipeline you can still get your assets pre-processed. If you take a look at the API docs you'll see there is the fetch_command config option which accepts a closure that receives as first parameter the path of the asset to be pipelined.

Simply add all your pre-processing logic in that closure and make sure it returns the result of the processing.

$config = [
    /*...*/
    'fetch_command' = function ($asset) {
        $unprocessed = file_get_contents($asset);
        $processed = process($unprocessed);
        return $processed;
    },
    /*...*/
];

For instance, to rewrite relative CSS URLs using a non greedy PHP regex you could use

'fetch_command' => function ($asset) {

    $content = file_get_contents($asset);
    $regex = '~url\(\s?[\'"]?(.*?)[\'"]?\s?\)~';
    $filter = function ($match) {

        // Do not process absolute URLs
        if('http://' === substr($match[1], 0, 7) or 'https://' === substr($match[1], 0, 8) or '//' === substr($match[1], 0, 2))
            return $match[0];

        // Add your filter logic here
        return 'url("../'. $match[1] . '")';
    };

    // Apply filter
    return preg_replace_callback($regex, $filter, $content);
},