public function filterLoad(AssetInterface $asset) { $sass = new \Sass(); $includePaths = array_merge(array($asset->getSourceDirectory()), $this->includePaths); $sass->setIncludePath(implode(':', $includePaths)); if ($this->outputStyle) { $sass->setStyle($this->outputStyle); } $css = $sass->compile($asset->getContent()); $asset->setContent($css); }
public function parseSCSS($_cleanDuplicates = false, $_useIncludes = true) { $sass = new Sass(); $source = $_cleanDuplicates ? $this->cleanDuplicate($this->sourceCSS) : $this->sourceCSS; $sass->setPrecision($this->precisionValue); $sass->setSyntax($this->useSyntax); try { if ($_useIncludes) { $sass->setIncludePath("/opt/moresass/"); } $css = $sass->compile($source); } catch (Exception $e) { $this->_setError($e->getMessage()); return false; } $this->compiled($css); return true; }
/** * 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; }
/** * [assets description] * @param Array $assets * @return String js or css */ public function compile($assets, $type) { $self = $this; $rewriteCssUrls = function ($content, $asset) use($self) { $source_dir = dirname($asset["file"]); $root_dir = $self->app['docs_root']; $csspath = ""; if (strlen($root_dir) < strlen($source_dir)) { $csspath = '/' . trim(str_replace($root_dir, '', $source_dir), "/") . "/"; } else { // todo } $offset = 0; while (($pos = strpos($content, 'url(', $offset)) !== false) { if (($urlend = strpos($content, ')', $pos)) !== false) { $path = trim(str_replace(array('"', "'"), "", substr($content, $pos + 4, $urlend - ($pos + 4)))); if (!preg_match("#^(http|/|data\\:)#", trim($path))) { $content = str_replace($path, $csspath . $path, $content); } } $offset = $pos + 1; } return $content; }; $output = array(); foreach ((array) $assets as $file) { $asset = array("ext" => pathinfo($file, PATHINFO_EXTENSION), "file" => $file); $ext = $asset['ext'] == "scss" || $asset['ext'] == "less" ? "css" : $asset['ext']; $content = ''; if (strpos($file, ':') !== false && ($____file = $this->app->path($file))) { $asset['file'] = $file = $____file; } if ($ext != $type) { continue; } switch ($asset['ext']) { case 'js': $content = @file_get_contents($file); break; case 'scss': case 'less': case 'css': switch ($asset['ext']) { case 'scss': $content = \Sass::parse($file); break; case 'less': $content = \Less::parse($file); break; default: $content = @file_get_contents($file); } $content = $rewriteCssUrls($content, $asset); break; default: continue; } $output[] = $content; } return implode("", $output); }
<?php // директория со стилями (в конце слэш обязателен) $style_dir = MODX_BASE_PATH . 'assets/components/modxsite/templates/skins/wood/css/'; // сканирование содержимого $files = scandir(rtrim($style_dir, '/')); $scss = new Sass(); $scss->setStyle(Sass::STYLE_COMPRESSED); // выбор файлов с расширением scss foreach ($files as $scss_file) { if (is_file($style_dir . $scss_file) && strtolower(pathinfo($style_dir . $scss_file, PATHINFO_EXTENSION)) == 'scss') { // вычисление проверочного md5 хэша содержимого .scss файла $scss_hash = hash('md5', file_get_contents($style_dir . $scss_file)); // при отсутствии записанного (в .scsshash файл) хэша или его несовпадении с записанным - генерация css if (!file_exists($style_dir . $scss_file . 'hash') || $scss_hash != file_get_contents($style_dir . $scss_file . 'hash')) { //file_put_contents( $style_dir.substr($scss_file,0,-4).'css', $scss->compile($style_dir.$scss_file) ); file_put_contents($style_dir . substr($scss_file, 0, -4) . 'css', $scss->compileFile($style_dir . $scss_file)); // запись хэша file_put_contents($style_dir . $scss_file . 'hash', $scss_hash); } } }
static function compile($file, $load_path) { $sass = new \Sass(); $sass->setIncludePath(implode(':', $load_path)); return $sass->compile_file($file); }
/** * Обработка запроса, разбитие на: module/controller/action * @throws Boot_Exception */ private function getQuery() { $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : $_SERVER['REQUEST_URI']; if (preg_match("/^(\\/[^\\/\\.]+)\\.+\$/", $path_info, $match) && count($match) > 1) { $this->_redirect($match[1]); } //Если страница пытается загрузкить из асетов файл if (APPLICATION_ENV == 'development' && preg_match("/^\\/assets\\/(css|js)\\/.*?\\.(css|js)\$/", $path_info, $matches)) { switch ($matches[1]) { case "css": header("Content-Type: text/css"); break; case "js": header("Content-Type: application/javascript"); break; default: throw new Boot_Exception('Unknown file extension'); } //Если расширение css и файл найден if (file_exists(APPLICATION_PATH . $path_info) || $matches[1] == 'js') { echo file_get_contents(APPLICATION_PATH . $path_info); } else { //Если файл не найден, пробуем найти scss $filename = pathinfo(APPLICATION_PATH . $path_info, PATHINFO_FILENAME); $scss = pathinfo(APPLICATION_PATH . $path_info, PATHINFO_DIRNAME) . '/' . $filename . '.scss'; //Если файл существует if (file_exists($scss)) { //Компилируем SASS файл $sass = new Sass(); $sass->setStyle(Sass::STYLE_EXPANDED); $sass->setIncludePath(APPLICATION_ROOT); $sass->setComments(true); file_put_contents('/tmp/' . $filename . '.css', $sass->compileFile($scss)); //Добавляем префиксы $result = system('postcss --use autoprefixer -o /tmp/' . $filename . '.out.css /tmp/' . $filename . '.css', $r); if ($result) { throw new Boot_Exception($result); } else { echo file_get_contents('/tmp/' . $filename . '.out.css'); unlink('/tmp/' . $filename . '.out.css'); unlink('/tmp/' . $filename . '.css'); } // $autoprefixer = new Autoprefixer(['ff > 2', '> 2%', 'ie 8']); // echo $autoprefixer->compile($css); //Ruby Sass // //Компилируем sass // $return = system('sass -l -t expanded --sourcemap=none ' . escapeshellarg($scss) . ' ' . escapeshellarg('/tmp/' . $filename . '.css') . ' 2>&1'); // if( $return ) { // throw new Boot_Exception('sass error: ' . $return); // } // // //Добавляем префиксы // $return = system('postcss --use autoprefixer /tmp/' . $filename . '.css -o /tmp/' . $filename . '_out.css 2>&1'); // if( $return ) { // throw new Boot_Exception('autoprefixer error: ' . $return); // } // // //Выводим данные // readfile('/tmp/' . $filename . '_out.css'); } else { throw new Boot_Exception('File ' . $path_info . ' not found', 404); } } exit; } //Получаем строку запроса if ($_SERVER['QUERY_STRING']) { parse_str($_SERVER['QUERY_STRING'], $this->_request); } $query = $path_info; if (preg_match("/^(.*?)\\?/", $path_info, $match)) { $query = $match[1]; } //Сохраняем параметры запроса $this->_param = Boot_Routes::getInstance()->getParam(substr($query, 1, strlen($query))); }
<?php // -------------------------------------------------------------------------------------------------------------------- // Sanity check // -------------------------------------------------------------------------------------------------------------------- $script_name = basename($argv[0]); if ($argc < 3) { echo "Error: {$script_name} expects at least 2 parameters.\n"; echo "Usage: `php {$script_name} /path/to/input.scss /path/to/output.css`\n"; die; } $input_file_name = $argv[1]; $output_file_name = $argv[2]; if (!file_exists($input_file_name)) { die("Error: The file {$input_file_name} was not found.\n"); } // -------------------------------------------------------------------------------------------------------------------- // Sassify // -------------------------------------------------------------------------------------------------------------------- $includePaths = [__DIR__ . '/../assets/scss/partials', __DIR__ . '/../assets/scss/fonts', dirname(realpath($input_file_name))]; try { // Requires: https://github.com/sensational/sassphp $sass = new \Sass(); $sass->setStyle(Sass::STYLE_EXPANDED); $sass->setIncludePath(implode(':', $includePaths)); $css = $sass->compileFile($input_file_name); } catch (Exception $e) { die($e->getMessage()); } file_put_contents($output_file_name, $css); echo "{$output_file_name} was created successfully!\n";
/** * Чтение данных файла * @param $path * @throws Exception * @return string */ public function readfile($path) { //Получаем расширение файла $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION)); //Если расширение входим в массив if (in_array($ext, [$this->ext, 'scss'])) { if ($this->compile) { //SASS if ($ext == 'scss') { //Компилируем SASS файл $sass = new Sass(); $sass->setStyle(Sass::STYLE_COMPRESSED); $sass->setIncludePath(APPLICATION_ROOT); $sass->setComments(false); $filename = pathinfo(APPLICATION_PATH . $path, PATHINFO_FILENAME); file_put_contents('/tmp/' . $filename . '.css', $sass->compileFile($path)); //Добавляем префиксы $result = system('postcss --use autoprefixer -o /tmp/' . $filename . '.out.css /tmp/' . $filename . '.css 2>&1', $r); if ($result) { throw new Boot_Exception($result); } else { $css = file_get_contents('/tmp/' . $filename . '.out.css'); unlink('/tmp/' . $filename . '.out.css'); unlink('/tmp/' . $filename . '.css'); return $css; } //Ruby SASS // //Компилируем sass // $filename = pathinfo(APPLICATION_PATH . $path, PATHINFO_FILENAME); // $return = system('sass -t compressed --sourcemap=none ' . escapeshellarg($path) . ' ' . escapeshellarg('/tmp/' . $filename . '.css') . ' 2>&1'); // if( $return ) { // throw new Boot_Exception('sass error: ' . $return); // } // // //Добавляем префиксы // $return = system('postcss --use autoprefixer /tmp/' . $filename . '.css -o /tmp/' . $filename . '_out.css 2>&1'); // if( $return ) { // throw new Boot_Exception('autoprefixer error: ' . $return); // } // // //Выводим данные // return file_get_contents('/tmp/' . $filename . '_out.css'); } //Выполняем для обычных css файлов return $this->compress(file_get_contents($path)); } else { switch ($this->ext) { case "css": return "<link href='" . str_replace(APPLICATION_PATH, "", preg_replace('/\\.scss$/i', '.css', $path)) . "' rel='stylesheet' type='text/css'>" . PHP_EOL; break; case "js": return "<script src='" . str_replace(APPLICATION_PATH, "", $path) . "' type=\"text/javascript\"></script>" . PHP_EOL; break; default: throw new Exception("Wrong file extension"); } } } return null; }