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