Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to read a LESS file, resolve its @imports and generate a new LESS file
<?php
declare(strict_types=1);
class LessImportParser
{
private $content = '';
public function load(string $fileName)
{
$this->content = $this->resolveImports($fileName);
}
public function save(string $fileName)
{
file_put_contents($fileName, $this->content);
}
private function resolveImports(string $fileName): string
{
$fileContent = file_get_contents($fileName);
$fileDir = dirname($fileName);
if (!preg_match_all('/@import([^\;]+)/mS', $fileContent, $matches)) {
return $fileContent;
}
foreach ($matches[0] as $matchIndex => $match) {
$importedFilename = $matches[1][$matchIndex];
$importedFilename = str_replace('(reference)', '', $importedFilename);
$importedFilename = str_replace('\'', '', $importedFilename);
$importedFilename = trim($importedFilename);
$importedContent = $this->resolveImports($fileDir.'/'.$importedFilename);
$newContent = "\n // Imported file: ".$importedFilename."\n";
$newContent .= $importedContent;
$fileContent = str_replace($match, $newContent, $fileContent);
}
return $fileContent;
}
}
$parser = new LessImportParser;
$parser->load(__DIR__ . '/css/styles-l.less');
$parser->save(__DIR__ . '/css/test-l.less');
$parser->load(__DIR__ . '/css/styles-m.less');
$parser->save(__DIR__ . '/css/test-m.less');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment