Skip to content

Instantly share code, notes, and snippets.

@jissereitsma
Created August 7, 2018 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jissereitsma/27a1406586b4e5bba0cfdb05ba2ada0a to your computer and use it in GitHub Desktop.
Save jissereitsma/27a1406586b4e5bba0cfdb05ba2ada0a to your computer and use it in GitHub Desktop.
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