Created
August 7, 2018 06:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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