| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Less; |
| 4 |
|
| 5 |
use Less_Exception_Parser; |
| 6 |
use Less_Parser; |
| 7 |
use RuntimeException; |
| 8 |
|
| 9 |
/** |
| 10 |
* Less compiler backed by the wikimedia/less.php library |
| 11 |
*/ |
| 12 |
class WikimediaLessCompiler |
| 13 |
{ |
| 14 |
/** |
| 15 |
* Create a new WikimediaLessCompiler |
| 16 |
* |
| 17 |
* @param array<string, mixed> $parserOptions Options forwarded verbatim to {@see Less_Parser} |
| 18 |
*/ |
| 19 |
public function __construct(protected array $parserOptions = []) |
| 20 |
{ |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Compile Less source to CSS |
| 25 |
* |
| 26 |
* @param string $less Less source code to compile |
| 27 |
* @param bool|null $minify Controls whether the CSS output is minified: |
| 28 |
* - `null` (default): use the `compress` option from the constructor |
| 29 |
* - `true`/`false`: override the constructor option for this call |
| 30 |
* |
| 31 |
* @return string The compiled CSS |
| 32 |
* |
| 33 |
* @throws RuntimeException If Less compilation fails |
| 34 |
*/ |
| 35 |
public function compile(string $less, ?bool $minify = null): string |
| 36 |
{ |
| 37 |
$parserOptions = []; |
| 38 |
if ($minify !== null) { |
| 39 |
$parserOptions['compress'] = $minify; |
| 40 |
} |
| 41 |
|
| 42 |
try { |
| 43 |
return (new Less_Parser($parserOptions + $this->parserOptions)) |
| 44 |
->parse($less) |
| 45 |
->getCss(); |
| 46 |
} catch (Less_Exception_Parser $e) { |
| 47 |
throw new RuntimeException('Less compilation failed: ' . $e->getMessage(), $e->getCode(), $e); |
| 48 |
} |
| 49 |
} |
| 50 |
} |