/** * 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) { $this->importPaths = !empty($options['importPaths']) ? $options['importPaths'] : $this->importPaths; $this->enableCompass = isset($options['enableCompass']) ? $options['enableCompass'] : $this->enableCompass; $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)) { $paths = ['']; foreach ($this->importPaths as $path) { $paths[] = Yii::getAlias($path); } $parser->setImportPaths($paths); } 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->enableCompass) { new \scss_compass($parser); } if (!file_exists($src)) { throw new \Exception("Failed to open file \"{$src}\""); } 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)); } }
function sassCss($inputFilename, $outputFilename, $inputPath) { $compiler = new Leafo\ScssPhp\Compiler(); $compiler->addImportPath($inputPath); $input = file_get_contents($inputFilename); $output = $compiler->compile($input); file_put_contents($outputFilename, $output); }
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); } }
/** * 変換処理の実行 * @param object $px Picklesオブジェクト */ public static function exec($px) { foreach ($px->bowl()->get_keys() as $key) { $src = $px->bowl()->pull($key); $tmp_current_dir = realpath('./'); chdir(dirname($_SERVER['SCRIPT_FILENAME'])); $scss = new \Leafo\ScssPhp\Compiler(); $src = $scss->compile($src); chdir($tmp_current_dir); $px->bowl()->replace($src, $key); } return true; }
public function processContent(File $asset) { $path = $asset->getPath(); try { $scssIn = $this->assetSource->getContent($asset); $compiler = new \Leafo\ScssPhp\Compiler(); $cssOut = $compiler->compile($scssIn); return $cssOut; } catch (\Exception $e) { $errorMessage = PHP_EOL . self::ERROR_MESSAGE_PREFIX . PHP_EOL . $path . PHP_EOL . $e->getMessage(); $this->logger->critical($errorMessage); } }
/** * 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 css file from one or more scss files * */ public static function ParseScss(&$scss_files) { global $dataDir; $compiler = new \Leafo\ScssPhp\Compiler(); $compiled = false; $combined = array(); //add variables for url paths $combined[] = '$icon-font-path: "../../include/thirdparty/Bootstrap3/fonts/";'; try { foreach ($scss_files as $file) { //treat as scss markup if there are newline characters if (strpos($file, "\n") !== false) { $combined[] = $file; continue; } // handle relative and absolute paths if (!empty($dataDir) && strpos($file, $dataDir) === false) { $file = $dataDir . '/' . ltrim($file, '/'); } $combined[] = '@import "' . $file . '";'; } $compiler->addImportPath($dataDir); $compiled = $compiler->compile(implode("\n", $combined)); } catch (\Exception $e) { if (\gp\tool::LoggedIn()) { msg('SCSS Compile Failed: ' . $e->getMessage()); } return false; } $scss_files = $compiler->allParsedFiles(); $scss_files = array_keys($scss_files); return $compiled; }
/** * 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"; }
function nebula_render_scss($specific_scss = null, $child = false) { $override = apply_filters('pre_nebula_render_scss', false, $specific_scss, $child); if ($override !== false) { return $override; } if (nebula_option('nebula_scss', 'enabled') && (isset($_GET['sass']) || isset($_GET['scss']) || $_GET['settings-updated'] == 'true') && (is_dev() || is_client())) { $specific_scss = 'all'; } $theme_directory = get_template_directory(); $theme_directory_uri = get_template_directory_uri(); if ($child) { $theme_directory = get_stylesheet_directory(); $theme_directory_uri = get_stylesheet_directory_uri(); } $stylesheets_directory = $theme_directory . '/stylesheets'; $stylesheets_directory_uri = $theme_directory_uri . '/stylesheets'; require_once get_template_directory() . '/includes/libs/scssphp/scss.inc.php'; //SCSSPHP is a compiler for SCSS 3.x $scss = new \Leafo\ScssPhp\Compiler(); $scss->addImportPath($stylesheets_directory . '/scss/partials/'); if (nebula_option('nebula_minify_css', 'enabled') && !is_debug()) { $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compressed'); //Minify CSS (while leaving "/*!" comments for WordPress). } else { $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compact'); //Compact, but readable, CSS lines if (is_debug()) { $scss->setLineNumberStyle(\Leafo\ScssPhp\Compiler::LINE_COMMENTS); //Adds line number reference comments in the rendered CSS file for debugging. } } if (empty($specific_scss) || $specific_scss == 'all') { //Partials $latest_partial = 0; foreach (glob($stylesheets_directory . '/scss/partials/*') as $partial_file) { if (filemtime($partial_file) > $latest_partial) { $latest_partial = filemtime($partial_file); } } //Combine Developer Stylesheets if (nebula_option('nebula_dev_stylesheets')) { nebula_combine_dev_stylesheets($stylesheets_directory, $stylesheets_directory_uri); } //Compile each SCSS file foreach (glob($stylesheets_directory . '/scss/*.scss') as $file) { //@TODO "Nebula" 0: Change to glob_r() but will need to create subdirectories if they don't exist. $file_path_info = pathinfo($file); if (is_file($file) && $file_path_info['extension'] == 'scss' && $file_path_info['filename'][0] != '_') { //If file exists, and has .scss extension, and doesn't begin with "_". $file_counter++; $css_filepath = $file_path_info['filename'] == 'style' ? $theme_directory . '/style.css' : $stylesheets_directory . '/css/' . $file_path_info['filename'] . '.css'; if (!file_exists($css_filepath) || filemtime($file) > filemtime($css_filepath) || $latest_partial > filemtime($css_filepath) || is_debug() || $specific_scss == 'all') { //If .css file doesn't exist, or is older than .scss file (or any partial), or is debug mode, or forced ini_set('memory_limit', '512M'); //Increase memory limit for this script. //@TODO "Nebula" 0: Is this the best thing to do here? Other options? WP_Filesystem(); global $wp_filesystem; $existing_css_contents = file_exists($css_filepath) ? $wp_filesystem->get_contents($css_filepath) : ''; if (!strpos(strtolower($existing_css_contents), 'scss disabled')) { //If the correlating .css file doesn't contain a comment to prevent overwriting $this_scss_contents = $wp_filesystem->get_contents($file); //Copy SCSS file contents $compiled_css = $scss->compile($this_scss_contents); //Compile the SCSS $enhanced_css = nebula_scss_variables($compiled_css); //Compile server-side variables into SCSS $wp_filesystem->put_contents($css_filepath, $enhanced_css); //Save the rendered CSS. } } } } if (!$child && is_child_theme()) { //If not in the second (child) pass, and is a child theme. nebula_render_scss($specific_scss, true); //Re-run on child theme stylesheets } } else { if (file_exists($specific_scss)) { //If $specific_scss is a filepath WP_Filesystem(); global $wp_filesystem; $scss_contents = $wp_filesystem->get_contents($specific_scss); $compiled_css = $scss->compile($scss_contents); //Compile the SCSS $enhanced_css = nebula_scss_variables($compiled_css); //Compile server-side variables into SCSS $wp_filesystem->put_contents(str_replace('.scss', '.css', $specific_scss), $enhanced_css); //Save the rendered CSS in the same directory. } else { //If $scss_file is raw SCSS string $compiled_css = $scss->compile($specific_scss); return nebula_scss_variables($compiled_css); //Return the rendered CSS } } }
/** * 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; }
/** * 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; }
/** 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); } } } } }
function nebula_render_scss($specific_scss = null) { require_once get_template_directory() . '/includes/libs/scssphp/scss.inc.php'; //SCSSPHP is a compiler for SCSS 3.x $scss = new \Leafo\ScssPhp\Compiler(); $scss->addImportPath(get_template_directory() . '/stylesheets/scss/partials/'); if (nebula_option('nebula_minify_css', 'enabled') && !is_debug()) { $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compressed'); //Minify CSS (while leaving "/*!" comments for WordPress). } else { $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compact'); //Compact, but readable, CSS lines if (is_debug()) { //$scss->setLineNumberStyle(\Leafo\ScssPhp\Compiler::LINE_COMMENTS); //Adds line number reference comments in the rendered CSS file for debugging. //@TODO: "Nebula" 0: This is broken!! This line was working at one point and has not been changed since... However, it's just choking up on login.scss and tinymce.scss and style.scss for some reason- it compiles others before that... //$scss->setLineNumberStyle(\Leafo\ScssPhp\Compiler::LINE_COMMENTS); //Using this one for testing... } } if (empty($specific_scss) || $specific_scss == 'all') { //Partials $latest_partial = 0; foreach (glob(get_template_directory() . '/stylesheets/scss/partials/*') as $partial_file) { if (filemtime($partial_file) > $latest_partial) { $latest_partial = filemtime($partial_file); } } //Combine Developer Stylesheets if (nebula_option('nebula_dev_stylesheets')) { $file_counter = 0; $partials = array('variables', 'mixins', 'helpers'); $automation_warning = "/**** Warning: This is an automated file! Anything added to this file manually will be removed! ****/\r\n\r\n"; $dev_stylesheet_files = glob(get_template_directory() . '/stylesheets/scss/dev/*css'); $dev_scss_file = get_template_directory() . '/stylesheets/scss/dev.scss'; if (!empty($dev_stylesheet_files) || strlen($dev_scss_file) > strlen($automation_warning) + 10) { //If there are dev SCSS (or CSS) files -or- if dev.scss needs to be reset file_put_contents(get_template_directory() . '/stylesheets/scss/dev.scss', $automation_warning); //Empty /stylesheets/scss/dev.scss } foreach ($dev_stylesheet_files as $file) { $file_path_info = pathinfo($file); if (is_file($file) && in_array($file_path_info['extension'], array('css', 'scss'))) { $file_counter++; //Include partials in dev.scss if ($file_counter == 1) { $import_partials = ''; foreach ($partials as $partial) { $import_partials .= "@import '" . $partial . "';\r\n"; } file_put_contents($dev_scss_file, $automation_warning . $import_partials . "\r\n"); } $this_scss_contents = file_get_contents($file); //Copy file contents $empty_scss = $this_scss_contents == '' ? ' (empty)' : ''; $dev_scss_contents = file_get_contents(get_template_directory() . '/stylesheets/scss/dev.scss'); $dev_scss_contents .= "\r\n/* ==========================================================================\r\n " . 'File #' . $file_counter . ': ' . get_template_directory_uri() . "/stylesheets/scss/dev/" . $file_path_info['filename'] . '.' . $file_path_info['extension'] . $empty_scss . "\r\n ========================================================================== */\r\n\r\n" . $this_scss_contents . "\r\n\r\n/* End of " . $file_path_info['filename'] . '.' . $file_path_info['extension'] . " */\r\n\r\n\r\n"; file_put_contents(get_template_directory() . '/stylesheets/scss/dev.scss', $dev_scss_contents); } } if ($file_counter > 0) { add_action('wp_enqueue_scripts', 'enqueue_dev_styles'); function enqueue_dev_styles() { wp_enqueue_style('nebula-dev_styles', get_template_directory_uri() . '/stylesheets/css/dev.css?c=' . rand(1, 99999), array('nebula-main'), null); } } } //Compile each SCSS file foreach (glob(get_template_directory() . '/stylesheets/scss/*.scss') as $file) { //@TODO "Nebula" 0: Change to glob_r() but will need to create subdirectories if they don't exist. $file_path_info = pathinfo($file); if (is_file($file) && $file_path_info['extension'] == 'scss' && $file_path_info['filename'][0] != '_') { //If file exists, and has .scss extension, and doesn't begin with "_". $file_counter++; $css_filepath = $file_path_info['filename'] == 'style' ? get_template_directory() . '/style.css' : get_template_directory() . '/stylesheets/css/' . $file_path_info['filename'] . '.css'; if (!file_exists($css_filepath) || filemtime($file) > filemtime($css_filepath) || $latest_partial > filemtime($css_filepath) || is_debug() || $specific_scss == 'all') { //If .css file doesn't exist, or is older than .scss file (or any partial), or is debug mode, or forced ini_set('memory_limit', '512M'); //Increase memory limit for this script. //@TODO "Nebula" 0: Is this the best thing to do here? Other options? $existing_css_contents = file_exists($css_filepath) ? file_get_contents($css_filepath) : ''; if (!strpos(strtolower($existing_css_contents), 'scss disabled')) { //If the correlating .css file doesn't contain a comment to prevent overwriting $this_scss_contents = file_get_contents($file); //Copy SCSS file contents $compiled_css = $scss->compile($this_scss_contents); //Compile the SCSS $enhanced_css = nebula_scss_variables($compiled_css); //Compile server-side variables into SCSS file_put_contents($css_filepath, $enhanced_css); //Save the rendered CSS } } } } } else { if (file_exists($specific_scss)) { //If $specific_scss is a filepath $scss_contents = file_get_contents($specific_scss); //Copy SCSS file contents $compiled_css = $scss->compile($scss_contents); //Compile the SCSS $enhanced_css = nebula_scss_variables($compiled_css); //Compile server-side variables into SCSS file_put_contents(str_replace('.scss', '.css', $specific_scss), $enhanced_css); //Save the rendered CSS in the same directory } else { //If $scss_file is raw SCSS string $compiled_css = $scss->compile($specific_scss); return nebula_scss_variables($compiled_css); //Return the rendered CSS } } }
<?php include_once '../vendor/autoload.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> <?php $scss = new Leafo\ScssPhp\Compiler(); //$scss->setFormatter('Leafo\ScssPhp\Formatter\Crunched'); echo $scss->compile(file_get_contents('magazine.scss')); ?> </style> </head> <body> <div class="magazine modo2"> <input name="mag_option" class="mag_back" type="radio" id="mag_option_back" checked> <div class="mag_title_back_wrap"><label for="mag_option_back" class="mag_title_back">Back</label></div> <div class="mag_title_main_wrap"><span class="mag_title_main">Opciones</span></div> <input name="mag_option" class="mag_option" type="radio" id="mag_option_1"> <div class="mag_title_wrap" data-mag-order="1"><label for="mag_option_1" class="mag_title">Titulo 1</label></div> <div class="mag_content_wrap"> <div class="mag_content"> Este es el contenido del cuadro 1 </div> </div>
/** * ドキュメントモジュール定義のスタイルを統合 * * モジュール定義の情報から、スタイルシートを生成します。 * * スタイルシートファイル(例: `/common/styles/contents.css` など)に、下記のようにコードを記述します。 * * ``` * <?php * print (new \tomk79\pickles2\px2dthelper\main($px))->document_modules()->build_css(); * ?> * ``` * * @return string CSSコード */ public function build_css() { $conf = $this->main->get_px2dtconfig(); $array_files = array(); foreach ($conf->paths_module_template as $key => $row) { $array_files[$key] = array(); $array_files[$key] = array_merge($array_files[$key], glob($row . "**/**/module.css")); $array_files[$key] = array_merge($array_files[$key], glob($row . "**/**/module.css.scss")); } $rtn = ''; foreach ($array_files as $packageId => $array_files_row) { foreach ($array_files_row as $path) { preg_match('/\\/([a-zA-Z0-9\\.\\-\\_]+?)\\/([a-zA-Z0-9\\.\\-\\_]+?)\\/[a-zA-Z0-9\\.\\-\\_]+?$/i', $path, $matched); $rtn .= '/**' . "\n"; $rtn .= ' * module: ' . $packageId . ':' . $matched[1] . '/' . $matched[2] . "\n"; $rtn .= ' */' . "\n"; $tmp_bin = $this->px->fs()->read_file($path); if ($this->px->fs()->get_extension($path) == 'scss') { $tmp_current_dir = realpath('./'); chdir(dirname($path)); $scss = new \Leafo\ScssPhp\Compiler(); $tmp_bin = $scss->compile($tmp_bin); chdir($tmp_current_dir); } $tmp_bin = $this->build_css_resources($path, $tmp_bin); $rtn .= $tmp_bin; $rtn .= "\n" . "\n"; unset($tmp_bin); } } return trim($rtn); }
$realpath = realpath(__DIR__ . "/" . $url); $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");
/** * Compiles the SASS content to CSS * * @param Node $node the node to be compiled * @param string $indent the indentation to use on each child * @param string $newLine the new-line to append after each line * * @return string the wrapped SASS-CSS-string * @throws Compiler\Exception when the Stylus package is not installed */ public static function filterSass(Node $node, $indent, $newLine) { if (!class_exists('Leafo\\ScssPhp\\Compiler')) { throw new Compiler\Exception("Failed to compile SASS: " . "Please install the leafo/scssphp composer package"); } $sass = new \Leafo\ScssPhp\Compiler(); $css = $sass->compile($node->text()); return '<style>' . $newLine . $indent . $css . $newLine . $indent . '</style>'; }
/** * * @param type $variables * @param type $functions * @return \Leafo\ScssPhp\Server|boolean */ function get_scss_parser($variables, $functions) { if (!(include_once SCSSPHP_INC . 'scss.inc.php')) { trigger_error('Unable to process .scss file -- SCSSPHP not configured correctly on your server. Check the SCSSPHP_INC setting in settings/package_settings.php.'); return false; } $scss = new Leafo\ScssPhp\Compiler(); $scss->setFormatter('Leafo\\ScssPhp\\Formatter\\Compressed'); $scss->setVariables($variables); foreach ($functions as $name => $func) { $scss->registerFunction($name, $func); } return new \Leafo\ScssPhp\Server('.', '.', $scss); }
/** * SCSSify the stylesheet and return the href of the compiled file * * @param string $src Source URL of the file to be parsed * @param string $handle An identifier for the file used to create the file name in the cache * @return string URL of the compiled stylesheet */ public function parse_stylesheet($src, $handle) { // we only want to handle .scss files if (!preg_match('/\\.scss(\\.php)?$/', preg_replace('/\\?.*$/', '', $src))) { return $src; } // get file path from $src if (!strstr($src, '?')) { $src .= '?'; } // prevent non-existent index warning when using list() & explode() // vars to pass into the compiler - default @themeurl var for image urls etc... $this->add_vars(array('theme-url' => '"' . get_template_directory_uri() . '"')); // Lets get the paths we need $scss_directory = str_replace(get_template_directory_uri() . "/", "", $src); $scss_directory = substr($scss_directory, 0, strrpos($scss_directory, '/')); $scss_directory = get_template_directory() . "/{$scss_directory}"; $scss_filename = substr(basename($src), 0, strrpos(basename($src), '?')); $css_filename = str_replace("scss", "css", $scss_filename); $css_directory_uri = wp_upload_dir()['baseurl'] . "/wp-scss-cache"; $this->set_scss_directory($scss_directory); $this->set_handle($handle); $this->set_src_path("{$scss_directory}/{$scss_filename}"); $this->add_vars(apply_filters('scss_vars', $this->get_vars(), $handle)); $scss_is_changed = $this->scss_is_changed(); $is_changed = $scss_is_changed['changed']; $hash = $scss_is_changed['hash']; $this->add_vars(array('color-map' => array("blue" => "green", "yellow" => "purple"))); // Don't recompile if the neither the vars nor the source have changed if (!$is_changed && !WP_DEBUG) { return "{$css_directory_uri}/{$css_filename}"; } // Do recompile if either the vars or soure have changed try { $scss = new \Leafo\ScssPhp\Compiler(); $scss->setVariables($this->vars); $scss->addImportPath($scss_directory); $compiled_css = $scss->compile(file_get_contents("{$scss_directory}/{$scss_filename}")); $this->save_parsed_css($this->get_css_directory() . "/{$css_filename}", $compiled_css); } catch (Exception $ex) { wp_die($ex->getMessage()); } return "{$css_directory_uri}/{$css_filename}?ver={$hash}"; }