/** * Parse a Scss file and convert it into CSS * * @param string $src source file path * @param string $dst destination file path * @param array $options parser options * @return mixed * @throws \Exception */ public function parse($src, $dst, $options) { if (!file_exists($src)) { throw new \Exception("Failed to open file \"{$src}\""); } $this->importPaths = !empty($options['importPaths']) ? $options['importPaths'] : $this->importPaths; $this->lineComments = isset($options['lineComments']) ? $options['lineComments'] : $this->lineComments; $this->outputStyle = isset($options['outputStyle']) ? $options['outputStyle'] : $this->outputStyle; $this->outputStyle = strtolower($this->outputStyle); $parser = new \Leafo\ScssPhp\Compiler(); if (!empty($this->importPaths) && is_array($this->importPaths)) { foreach ($this->importPaths as $path) { $paths[] = Yii::getAlias($path); } $parser->setImportPaths($paths); } else { $parser->setImportPaths([dirname($src)]); } if (in_array($this->outputStyle, $this->formatters)) { if ($this->lineComments && in_array($this->outputStyle, ['compressed', 'crunched'])) { $this->lineComments = false; } $parser->setFormatter('Leafo\\ScssPhp\\Formatter\\' . ucfirst($this->outputStyle)); } if ($this->lineComments) { $content = self::insertLineComments($src, self::getRelativeFilename($src, $dst)); file_put_contents($dst, self::parseLineComments($parser->compile($content, $src))); } else { file_put_contents($dst, $parser->compile(file_get_contents($src), $src)); } }
public function phpProcess($code) { $compiler = new \Leafo\ScssPhp\Compiler(); $compiler->setImportPaths(dirname($code)); $code = $compiler->compile('@import "' . str_replace(dirname($code), '', $code) . '"'); // var_dump($code); return $code; }
/** * @param string $code * @return string * @throws \Athem\Exception\InvalidClass */ protected function phpProcess($code, $data = array()) { if (!class_exists('\\Leafo\\ScssPhp\\Compiler')) { throw new Exception\InvalidClass('Could nod find \\Leafo\\ScssPhp\\Compiler class. If you\'re using ' . 'composer, please add "leafo/scssphp" : "*" to your composer.json and run \'composer update\'.'); } try { $compiler = new \Leafo\ScssPhp\Compiler(); $compiler->setImportPaths(dirname($code)); return $compiler->compile('@import "' . str_replace(dirname($code), '', $code) . '"'); } catch (\Exception $e) { throw new Code\Exception\CompileError('Code processing failed. Please see trace to understand the nature of the error.', 1, $e); } }
/** * scssphp compiler * @link https://github.com/leafo/scssphp * * @param string $file * @return string */ protected function scssphp($file) { if (!class_exists('\\Leafo\\ScssPhp\\Compiler')) { return Result::errorMissingPackage($this, 'scssphp', 'leafo/scssphp'); } $scssCode = file_get_contents($file); $scss = new \Leafo\ScssPhp\Compiler(); // set options for the scssphp compiler if (isset($this->compilerOptions['importDirs'])) { $scss->setImportPaths($this->compilerOptions['importDirs']); } if (isset($this->compilerOptions['formatter'])) { $scss->setFormatter($this->compilerOptions['formatter']); } return $scss->compile($scssCode); }
/** * Create a new css file based on sass file * @param string $sourceFilePath * @param string $targetFilenamePath * @throws Exception */ public function createNewCss($sourceFilePath, $targetFilenamePath, $importFallback = null) { $config = $this->_getConfig(); $targetDir = dirname($targetFilenamePath); $this->_createDir($targetDir); $this->_createDir($config['cache_dir']); if ($config['use_ruby']) { $options = '--cache-location ' . $config['cache_dir'] . ' --style ' . $config['output_style']; if ($config['debug']) { $options .= ' --debug-info --line-numbers'; } $command = $config['sass_command'] . ' ' . $options . ' ' . $sourceFilePath . ':' . $targetFilenamePath; $execResult = exec($command, $output); if ($execResult != '') { throw new Exception("Error while processing sass file with command '{$command}':\n" . implode("\n", $output)); } } else { /** @var \Leafo\ScssPhp\Compiler $compiler */ $compiler = new \Leafo\ScssPhp\Compiler(); switch ($config['output_style']) { case Laurent_Sass_Model_Config_Style::STYLE_COMPACT: default: $formatter = \Leafo\ScssPhp\Formatter\Compact::class; break; case Laurent_Sass_Model_Config_Style::STYLE_NESTED: $formatter = \Leafo\ScssPhp\Formatter\Nested::class; break; case Laurent_Sass_Model_Config_Style::STYLE_COMPRESSED: $formatter = \Leafo\ScssPhp\Formatter\Compressed::class; break; case Laurent_Sass_Model_Config_Style::STYLE_EXPANDED: $formatter = \Leafo\ScssPhp\Formatter\Expanded::class; break; } if (Mage::getIsDeveloperMode()) { $compiler->setLineNumberStyle(Leafo\ScssPhp\Compiler::LINE_COMMENTS); } $compiler->setFormatter($formatter); $compiler->setImportPaths(array(dirname($sourceFilePath), Mage::getBaseDir('lib') . '/scssphp/stylesheets', $importFallback)); file_put_contents($targetFilenamePath, $compiler->compile(sprintf('@import "%s"', basename($sourceFilePath)))); } }
public function init($hi = null) { $this->inject(function ($Params, $Request) { $scss = new \Leafo\ScssPhp\Compiler(); $scss->setImportPaths($this->tipsy()->config()['path'] . 'public/assets/'); $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compressed'); $file = $this->tipsy()->config()['path'] . 'public/' . $Request->path(); $data = $scss->compile(file_get_contents($file)); $mtime = filemtime($file); header('HTTP/1.1 200 OK'); header('Date: ' . date('r')); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT'); header('Accept-Ranges: bytes'); header('Content-Length: ' . strlen($data)); header('Content-type: text/css'); header('Vary: Accept-Encoding'); header('Cache-Control: max-age=290304000, public'); echo $data; }); }
public function run() { include getcwd() . '/vendor/autoload.php'; $config = (include getcwd() . '/config/scss.php'); $source = ''; echo "Loading files...\n"; foreach ($config['scssFiles'] as $file) { echo " {$file}\n"; $source .= file_get_contents(getcwd() . '/' . $file); } $importPaths = []; echo "Setting import paths...\n"; foreach ($config['importPaths'] as $path) { echo " {$path}\n"; $importPaths[] = getcwd() . '/' . $path; } $scss = new \Leafo\ScssPhp\Compiler(); $scss->setImportPaths($importPaths); # build a compressed version first echo "Writing production.css...\n"; $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Crunched'); $result = $scss->compile($source); $prodOutput = getcwd() . '/' . $config['outputPath'] . '/production.css'; if (file_exists($prodOutput) === true) { unlink($prodOutput); } file_put_contents($prodOutput, $result); # now build a debug version echo "Writing debug.css...\n"; $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Expanded'); $scss->setLineNumberStyle(\Leafo\ScssPhp\Compiler::LINE_COMMENTS); $result = $scss->compile($source); $debugOutput = getcwd() . '/' . $config['outputPath'] . '/debug.css'; if (file_exists($debugOutput) === true) { unlink($debugOutput); } file_put_contents($debugOutput, $result); echo "Complete.\n"; }
/** * Returns the compiled CSS from SCSS input * * @param string $scss * @param array $includes (optional) * @return string */ function compile($scss, $includes = array()) { $scss = $this->prependLocalizedVars($scss); try { $css = '/* Silence is golden. */'; // If no SCSS input was passed, prevent file write errors by putting a comment in the CSS output. if ('' !== $scss) { if (extension_loaded('sass')) { // use sassphp extension $scss_file = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile()))); rename($scss_file, $scss_file .= '.scss'); register_shutdown_function(create_function('', "unlink('{$scss_file}');")); file_put_contents($scss_file, $scss); $sass = new \Sass(); $include_paths = implode(':', $includes); $sass->setIncludePath($include_paths); $css = $sass->compileFile($scss_file); } else { // use scssphp library $sass = new \Leafo\ScssPhp\Compiler(); $sass->setImportPaths($includes); $css = $sass->compile($scss); } } } catch (\Exception $e) { $_SESSION['pb_errors'][] = sprintf(__('There was a problem with SASS. Contact your site administrator. Error: %s', 'pressbooks'), $e->getMessage()); $this->logException($e); if (WP_DEBUG) { $this->debug("/* {$e->getMessage()} */", $scss, 'last-thrown-exception'); } return ''; // Return empty string on error } return $css; }
/** Initialize the SASS compiler. */ protected function _initSass() { $this->bootstrap('Config'); $config = Zend_Registry::get('configGlobal'); $logger = Zend_Registry::get('logger'); if ($config->environment == 'development') { $directory = new RecursiveDirectoryIterator(BASE_PATH); $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD); $regex = new RegexIterator($iterator, '#(?:core|(?:modules|privateModules)/.*)/public/scss/(?!mixins).*\\.scss$#', RegexIterator::GET_MATCH); $scssPaths = array(); foreach ($regex as $scssPath) { $scssPaths = array_merge($scssPaths, $scssPath); } $scssc = new Leafo\ScssPhp\Compiler(); $scssc->setImportPaths(array(BASE_PATH . '/core/public/scss/mixins', BASE_PATH . '/core/public/scss/mixins/bourbon')); $scssc->setFormatter('Leafo\\ScssPhp\\Formatter\\Compressed'); foreach ($scssPaths as $scssPath) { $cssPath = preg_replace('#((?:core|(?:modules|privateModules)/.*)/public)/scss/(.*)\\.scss$#', '\\1/css/\\2.css', $scssPath); if (!file_exists($cssPath) || filemtime($cssPath) < filemtime($scssPath)) { $cssDirectoryName = pathinfo($cssPath, PATHINFO_DIRNAME); if (!file_exists($cssDirectoryName)) { $level = error_reporting(0); mkdir($cssDirectoryName, 0755, true); error_reporting($level); } if (is_dir($cssDirectoryName) && is_writable($cssDirectoryName)) { $scss = file_get_contents($scssPath); $css = $scssc->compile($scss) . PHP_EOL; file_put_contents($cssPath, $css); } else { $logger->debug('Could not compile SASS located at ' . $scssPath); } } } } }
/** * Compile SCSS into CSS. * * @param string|array $source_filename * @param string $target_filename * @param array $variables (optional) * @parsm bool $minify (optional) * @return bool */ public static function compileSCSS($source_filename, $target_filename, $variables = array(), $minify = false) { // Get the cleaned and concatenated content. $content = self::concatCSS($source_filename, $target_filename); // Compile! try { $scss_compiler = new \Leafo\ScssPhp\Compiler(); $scss_compiler->setFormatter($minify ? '\\Leafo\\ScssPhp\\Formatter\\Crunched' : '\\Leafo\\ScssPhp\\Formatter\\Expanded'); $scss_compiler->setImportPaths(array(dirname(is_array($source_filename) ? array_first($source_filename) : $source_filename))); if ($variables) { $scss_compiler->setVariables($variables); } $charset = strpos($content, '@charset') === false ? '@charset "UTF-8";' . "\n" : ''; $content = $charset . $scss_compiler->compile($content) . "\n"; $result = true; } catch (\Exception $e) { $content = '/*' . "\n" . 'Error while compiling SCSS:' . "\n" . $e->getMessage() . "\n" . '*/' . "\n"; $result = false; } // Save the result to the target file. Storage::write($target_filename, $content); return $result; }
$path = realpath(__DIR__ . "/" . preg_replace("/(\\.min)(\\.scss)\$/i", "\$2", $url)); if (!is_string($path) || strpos($path, __DIR__) !== 0 || !is_string($content = file_get_contents($path))) { header("HTTP/1.1 404 Not Found"); echo "404 Not Found"; } $debugging = !isset($_GET["debug"]) || $_GET["debug"] == "true" ? true : false; $cache = $debugging === true || !isset($_GET["cache"]) || $_GET["cache"] == "false" ? false : true; $minified = strtolower(substr($url, -9, 4)) == ".min" ? true : false; // Get a cached copy $cachepath = $realpath . "-" . md5($content) . ($minified ? ".min" : "") . ".css"; if ($cache === true && is_string($compiled = file_get_contents($cachepath))) { header("Content-Type: text/css"); echo $compiled; } $scss = new Leafo\ScssPhp\Compiler(); $scss->setImportPaths(array(__DIR__, dirname($path))); if ($minified === true) { // Minified output? $scss->setFormatter("Leafo\\ScssPhp\\Formatter\\Crunched"); } if ($debugging === true) { // Debugging output? $scss->setLineNumberStyle(Leafo\ScssPhp\Compiler::LINE_COMMENTS); } $compiled = $scss->compile($content, $path); if ($cache === true) { file_put_contents($cachepath, $compiled); } // Output the compiled content as css header("Content-Type: text/css"); echo $compiled;