LessParserService.php
86 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * @copyright © TMS-Plugins. All rights reserved. |
| 5 | * @licence See LICENCE.md for license details. |
| 6 | */ |
| 7 | |
| 8 | namespace AmeliaBooking\Infrastructure\Services\Frontend; |
| 9 | |
| 10 | use AmeliaBooking\Domain\Services\Settings\SettingsService; |
| 11 | use Exception; |
| 12 | use Less_Exception_Parser; |
| 13 | use Less_Parser; |
| 14 | |
| 15 | /** |
| 16 | * Class LessParserService |
| 17 | */ |
| 18 | class LessParserService |
| 19 | { |
| 20 | /** @var string */ |
| 21 | private $inputCssScript; |
| 22 | |
| 23 | /** @var string */ |
| 24 | private $outputPath; |
| 25 | |
| 26 | /** @var SettingsService */ |
| 27 | private $settingsService; |
| 28 | |
| 29 | /** |
| 30 | * LessParserService constructor. |
| 31 | * |
| 32 | * @param string $inputCssScript |
| 33 | * @param string $outputPath |
| 34 | * @param SettingsService $settingsService |
| 35 | */ |
| 36 | public function __construct($inputCssScript, $outputPath, $settingsService) |
| 37 | { |
| 38 | $this->inputCssScript = $inputCssScript; |
| 39 | $this->outputPath = $outputPath; |
| 40 | $this->settingsService = $settingsService; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * @param array $data |
| 45 | * |
| 46 | * @return string |
| 47 | * @throws Exception |
| 48 | * @throws Less_Exception_Parser |
| 49 | */ |
| 50 | public function compileAndSave($data) |
| 51 | { |
| 52 | $parser = new Less_Parser(); |
| 53 | |
| 54 | $parser->parseFile($this->inputCssScript); |
| 55 | |
| 56 | $parser->ModifyVars($data); |
| 57 | |
| 58 | !is_dir($this->outputPath) && !mkdir($this->outputPath, 0755, true) && !is_dir($this->outputPath); |
| 59 | |
| 60 | $hash = $this->generateRandomString(); |
| 61 | |
| 62 | file_put_contents($this->outputPath . '/amelia-booking.' . $hash . '.css', $parser->getCss()); |
| 63 | |
| 64 | return $hash; |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * @param int $length |
| 69 | * |
| 70 | * @return false|string |
| 71 | */ |
| 72 | public function generateRandomString($length = 10) |
| 73 | { |
| 74 | return substr( |
| 75 | str_shuffle( |
| 76 | str_repeat( |
| 77 | $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', |
| 78 | ceil($length / strlen($x)) |
| 79 | ) |
| 80 | ), |
| 81 | 1, |
| 82 | $length |
| 83 | ); |
| 84 | } |
| 85 | } |
| 86 |