/** * @param $sources * @param $extension * @param $use_cache * @param $options * @return array */ public function filter($sources, $extension, $use_cache, $options) { $files = array(); // handle request if (!$options['combine']) { foreach ($sources as $file) { $cache_filename = basename($file) . '.' . md5($file) . '.' . $extension; $destination_file = $this->cache_path . $cache_filename; if (!file_exists($destination_file) || !$use_cache) { $this->cache->write($destination_file, \Minify::combine($file, array('minifiers' => array('application/x-javascript' => '')))); } if (file_exists($destination_file)) { $files[] = $this->host . $this->fileUtility->getRelativePath($this->storeRootDir, $destination_file); } } } else { $cache_filename = md5(serialize($sources)) . '.' . $extension; $destination_file = $this->cache_path . $cache_filename; if (($cache_file = $this->cache->exists($destination_file)) === false || !$use_cache) { // Todo: what to do if we do not turn on the minify? $cache_file = $this->cache->write($destination_file, \Minify::combine($sources, $options)); } if (file_exists($destination_file)) { $files[] = $this->fileUtility->getRelativePath($this->storeRootDir, $destination_file); } } return $files; }
/** * 处理单条数据 * * @param string $path 路径 * @param array $files 文件列表 */ protected function _showSource($path, $files) { $extension = pathinfo($path, PATHINFO_EXTENSION); $type_constant = 'Minify::TYPE_' . strtoupper($extension); if (defined($type_constant)) { $content_type = constant($type_constant); } else { $content_type = Minify::TYPE_HTML; } $sources = array(); foreach ($files as $value) { $source_path = str_replace('//', ROOT_PATH, $value); if (!is_file($source_path)) { echo "[Not Found] {$source_path}<br />\r\n"; continue; } $content = file_get_contents($source_path); $sources[] = new Minify_Source(array('id' => $value, 'contentType' => $content_type, 'filepath' => $source_path)); } $minify = new Minify(new Minify_Cache_Null()); $combined = $minify->combine($sources, $this->_minify_config); $to_file_path = ROOT_PATH . "static/{$extension}/{$path}"; $to_dir = dirname($to_file_path); if (!is_dir($to_dir)) { mkdir($to_dir, 0775, true); } file_put_contents($to_file_path, $combined); chmod($to_file_path, 0777); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $assetHelper = $container->get('mautic.helper.assetgeneration'); $factory = $container->get('mautic.factory'); // Combine and minify bundle assets $assetHelper->getAssets(true); // Minify Mautic Form SDK file_put_contents($factory->getSystemPath('assets') . '/js/mautic-form.js', \Minify::combine(array($factory->getSystemPath('assets') . '/js/mautic-form-src.js'))); /** @var \Symfony\Bundle\FrameworkBundle\Translation\Translator $translator */ $translator = $this->getContainer()->get('translator'); $translator->setLocale($this->getContainer()->get('mautic.factory')->getParameter('locale')); // Update successful $output->writeln('<info>' . $translator->trans('mautic.core.command.asset_generate_success') . '</info>'); return 0; }
/** * @param string $id * @param string $script * @param bool|string $cacheKey * @param null $position * @param array $htmlOptions * @return MinifyClientScript */ public function registerScriptCache($id, $script, $cacheKey = false, $position = null, array $htmlOptions = array()) { $script = self::registerScript($id, $script, $position, $htmlOptions); if (!$cacheKey) { return $script; } $files = array(); $path = Yii::getPathOfAlias('webroot.assets') . '/' . $cacheKey; @mkdir($path); @chmod($path, 0777); foreach ($script->scripts as $scriptKey => $scriptVal) { foreach ($scriptVal as $scriptItemKey => $scriptItem) { $file = $id . '.js'; file_put_contents($path . '/' . $file, $scriptItem); @chmod($file, 0777); $files[] = $path . '/' . $file; } } $file = $cacheKey . '.js'; file_put_contents($path . '/' . $file, Minify::combine($files)); return self::registerScriptFile('/assets/' . $cacheKey . '/' . $file); }
/** * Generates and returns assets * * @param bool $forceRegeneration * * @return array */ public function getAssets($forceRegeneration = false) { static $assets = array(); if (empty($assets)) { $loadAll = true; $env = $forceRegeneration ? 'prod' : $this->factory->getEnvironment(); $rootPath = $this->factory->getSystemPath('assets_root'); $assetsPath = $this->factory->getSystemPath('assets'); $assetsFullPath = "{$rootPath}/{$assetsPath}"; if ($env == 'prod') { $loadAll = false; //by default, loading should not be required //check for libraries and app files and generate them if they don't exist if in prod environment $prodFiles = array('css/libraries.css', 'css/app.css', 'js/libraries.js', 'js/app.js'); foreach ($prodFiles as $file) { if (!file_exists("{$assetsFullPath}/{$file}")) { $loadAll = true; //it's missing so compile it break; } } } if ($loadAll || $forceRegeneration) { if ($env == 'prod') { ini_set('max_execution_time', 300); $inProgressFile = "{$assetsFullPath}/generation_in_progress.txt"; if (!$forceRegeneration) { while (file_exists($inProgressFile)) { //dummy loop to prevent conflicts if one process is actively regenerating assets } } file_put_contents($inProgressFile, date('r')); } $modifiedLast = array(); //get a list of all core asset files $bundles = $this->factory->getParameter('bundles'); $fileTypes = array('css', 'js'); foreach ($bundles as $bundle) { foreach ($fileTypes as $ft) { if (!isset($modifiedLast[$ft])) { $modifiedLast[$ft] = array(); } $dir = "{$bundle['directory']}/Assets/{$ft}"; if (file_exists($dir)) { $modifiedLast[$ft] = array_merge($modifiedLast[$ft], $this->findAssets($dir, $ft, $env, $assets)); } } } $modifiedLast = array_merge($modifiedLast, $this->findOverrides($env, $assets)); //combine the files into their corresponding name and put in the root media folder if ($env == "prod") { $checkPaths = array($assetsFullPath, "{$assetsFullPath}/css", "{$assetsFullPath}/js"); array_walk($checkPaths, function ($path) { if (!file_exists($path)) { mkdir($path); } }); $useMinify = class_exists('\\Minify'); foreach ($assets as $type => $groups) { foreach ($groups as $group => $files) { $assetFile = "{$assetsFullPath}/{$type}/{$group}.{$type}"; //only refresh if a change has occurred $modified = $forceRegeneration || !file_exists($assetFile) ? true : filemtime($assetFile) < $modifiedLast[$type][$group]; if ($modified) { if (file_exists($assetFile)) { //delete it unlink($assetFile); } if ($type == 'css') { $out = fopen($assetFile, 'w'); foreach ($files as $relPath => $details) { $cssRel = '../../' . dirname($relPath) . '/'; if ($useMinify) { $content = \Minify::combine(array($details['fullPath']), array('rewriteCssUris' => false, 'minifierOptions' => array('text/css' => array('currentDir' => '', 'prependRelativePath' => $cssRel)))); } else { $content = file_get_contents($details['fullPath']); $search = '#url\\((?!\\s*([\'"]?(((?:https?:)?//)|(?:data\\:?:))))\\s*([\'"])?#'; $replace = "url(\$4{$cssRel}"; $content = preg_replace($search, $replace, $content); } fwrite($out, $content); } fclose($out); } else { array_walk($files, function (&$file) { $file = $file['fullPath']; }); file_put_contents($assetFile, \Minify::combine($files)); } } } } unlink($inProgressFile); } } if ($env == 'prod') { //return prod generated assets $assets = array('css' => array("{$assetsPath}/css/libraries.css?v{$this->version}", "{$assetsPath}/css/app.css?v{$this->version}"), 'js' => array("{$assetsPath}/js/libraries.js?v{$this->version}", "{$assetsPath}/js/app.js?v{$this->version}")); } else { foreach ($assets as $type => &$typeAssets) { $typeAssets = array_keys($typeAssets); } } } return $assets; }
/** * Combines, minifies, and outputs the requested files. * * Inspects the $_GET array for a 'files' entry containing a comma-separated * list and uses this as the set of files to be combined and minified. */ public static function handleRequest() { // 404 if no files were requested. if (!isset($_GET['files'])) { header('HTTP/1.0 404 Not Found'); exit; } $files = array_map('trim', explode(',', $_GET['files'], MINIFY_MAX_FILES)); // 404 if the $files array is empty for some weird reason. if (!count($files)) { header('HTTP/1.0 404 Not Found'); exit; } // Determine the content type based on the extension of the first file // requested. $type = preg_match('/\\.js$/iD', $files[0]) ? self::TYPE_JS : self::TYPE_CSS; // Minify and spit out the result. try { $minify = new Minify($type, $files); header("Content-Type: {$type};charset=" . MINIFY_ENCODING); $minify->browserCache(); echo $minify->combine(); exit; } catch (MinifyException $e) { header('HTTP/1.0 404 Not Found'); echo htmlentities($e->getMessage()); exit; } }
echo "USAGE: ./rewrite-uris.php [-t] -d DOC_ROOT [-o OUTFILE] file ...\n"; if ($cli->isHelpRequest) { echo $cli->getArgumentsListing(); } echo "EXAMPLE: ./rewrite-uris.php -v -d../.. ../../min_unit_tests/_test_files/css/paths_rewrite.css ../../min_unit_tests/_test_files/css/comments.css\n \n"; exit(0); } $outfile = $cli->values['o']; $testRun = $cli->values['t']; $docRoot = $cli->values['d']; $pathRewriter = function ($css, $options) { return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot']); }; $paths = $cli->getPathArgs(); $sources = array(); foreach ($paths as $path) { if (is_file($path)) { $sources[] = new Minify_Source(array('filepath' => $path, 'minifier' => $pathRewriter, 'minifyOptions' => array('docRoot' => $docRoot))); } else { $sources[] = new Minify_Source(array('id' => $path, 'content' => "/*** {$path} not found ***/\n", 'minifier' => '')); } } $combined = Minify::combine($sources) . "\n"; if ($testRun) { echo $combined; echo Minify_CSS_UriRewriter::$debugText . "\n"; } else { $fp = $cli->openOutput(); fwrite($fp, $combined); $cli->closeOutput(); }
/** * Combines, minifies, and outputs the requested files. * * Inspects the $_GET array for a 'files' entry containing a comma-separated * list and uses this as the set of files to be combined and minified. */ function handleRequest() { // 404 if no files were requested. if (!isset($_GET['files'])) { header('HTTP/1.0 404 Not Found'); exit; } $files = array_map('trim', explode(',', $_GET['files'], MINIFY_MAX_FILES)); // 404 if the $files array is empty for some weird reason. if (!count($files)) { header('HTTP/1.0 404 Not Found'); exit; } // Determine the content type based on the extension of the first file // requested. $type = preg_match('/\\.js$/iD', $files[0]) ? TYPE_JS : TYPE_CSS; // Minify and spit out the result. $minify = new Minify($type); $minify->addFile($files); ob_start("ob_gzhandler"); header("Content-Type: {$type};charset=" . MINIFY_ENCODING); $minify->browserCache(); echo $minify->combine(); }
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSS', 'minify'); } } $source = new Minify_Source($sourceSpec); $sendType = 'text/plain'; if ($type['minify'] === 'text/html' && !isset($_POST['asText'])) { $sendType = $type['sent']; } if ($type['charset']) { $sendType .= ';charset=' . $type['charset']; } header('Content-Type: ' . $sendType); // using combine instead of serve because it allows us to specify a // Content-Type like application/xhtml+xml IF we need to try { echo Minify::combine(array($source), array('contentType' => $type['minify'])); } catch (Exception $e) { header('Content-Type: text/html;charset=utf-8'); echo htmlspecialchars($e->getMessage()); } exit; } header('Content-Type: text/html; charset=utf-8'); $ua = get_magic_quotes_gpc() ? stripslashes($_SERVER['HTTP_USER_AGENT']) : $_SERVER['HTTP_USER_AGENT']; ?> <!DOCTYPE html><head><title>Minify URL</title></head> <p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p> <h1>Fetch and Minify a URL</h1>
/** * @param array $files * @param string $path */ protected function saveMinifiedAsset(array $files, $path) { $options = []; $options['minifiers']['text/css'] = ['Minify_CSSmin', 'minify']; $content = \Minify::combine($files, $options); if (!is_dir($this->appPath->getUploadsDir() . 'assets')) { @mkdir($this->appPath->getUploadsDir() . 'assets', 0755); } // Write the contents of the file to the uploads folder file_put_contents($path, $content, LOCK_EX); }
// MINIFY JS and CSS // Create new Minify objects. $minifyCSS = new Minify(TYPE_CSS); $minifyJS = new Minify(TYPE_JS); // Specify the files to be minified. $cssFiles = array('css/mediabrowser.css'); // Only load skin if $_GET["skin"] is set. if (isset($_GET["skin"])) { $cssFiles[count($cssFiles)] = 'skins/' . $_GET["skin"] . '/skin.css'; } $minifyCSS->addFile($cssFiles); $minifyJS->addFile(array('js/jquery.js', 'js/jquery.mediabrowser.js', 'js/jquery.plugins.js', 'swfupload/swfupload.min.js', 'swfupload/plugins/swfupload.queue.js', 'swfupload/fileprogress.js', 'swfupload/handlers.js', 'js/tiny_mce_popup.js')); // JAVASCRIPT echo '<script type="text/javascript">' . "\n"; echo '//<![CDATA[' . "\n"; echo $minifyJS->combine(); echo '//]]>' . "\n"; echo '</script>' . "\n"; // CSS echo '<style type="text/css">' . "\n"; echo $minifyCSS->combine(); echo '</style>' . "\n"; ?> <script type="text/javascript"> //<![CDATA[ var swfu; var foldercmenu; var filecmenu; var imagecmenu; var cmenu;
/** * Get minified CSS path. * * @param array $files * @return string */ public function getMinifyCss($files) { $basedir = 'cache/'; $target = $basedir . sha1(serialize($files)) . '.css'; // create basedir if it doesnt exist if (!is_dir($basedir)) { @mkdir($basedir, 0777, true); } // if minified file already exists, make sure it's up to date if (file_exists($target)) { $data = self::readMinificationHeader($target); if (self::getLastModified($data['files']) == $data['modified']) { trace_notice('Using cached css minification file'); return $target . '?' . $data['modified']; } trace_notice('Updating css minification file'); } // Combine files (and process imports) $imports = array(); $content = ""; foreach ($files as $file) { $processor = new CssProcessor($file['source']); $relative = Curry_Util::getRelativePath($basedir, dirname($file['source'])); $content .= $processor->getContent($file['media'], $relative); $imports = array_merge($imports, $processor->getImportedFiles()); } // Minify $source = new Minify_Source(array('id' => $target, 'content' => $content, 'contentType' => Minify::TYPE_CSS)); $content = Minify::combine(array($source)); // Add header $header = array('files' => $imports, 'modified' => self::getLastModified($imports)); $content = "/* " . json_encode($header) . " */\n" . $content; // Write content file_put_contents($target, $content); return $target . '?' . $header['modified']; }
#!/usr/bin/php <?php define('MINIFY_MIN_DIR', dirname(__FILE__)); // load config require MINIFY_MIN_DIR . '/config.php'; // setup include path set_include_path($min_libPath . PATH_SEPARATOR . get_include_path()); require_once 'Minify.php'; array_shift($argv); $out = Minify::combine($argv); // file_put_contents($outputPath, $out); echo $out;
public function rebuild() { if ($this->type == 'php') { $contents = array(); // Проходим по списку файлов и объединяем все в один большой кусок // TODO — обработка «?php в начале файла без закрывающего тега foreach ($this->list as $f) { if (file_exists($f)) { $content = trim(file_get_contents($f)); $content = str_replace('__DI' . 'R__', "'" . dirname(realpath($f)) . "'", $content); $content = str_replace('__FI' . 'LE__', "'" . realpath($f) . "'", $content); $contents[] = $content; } } $contents = implode('', $contents); } else { $contents = Minify::combine($this->list); } // записываем сборку в файл file_put_contents($this->file, $contents); // устанавливаем дату @touch($this->file, $this->dateActual); }
/** * Use PHP Minify to do the minification of passed SRCs. * @param array $srcs asset paths relative to site root * @return string minified & concatenated files. */ public function do_minify($srcs) { if (!class_exists('Minify_Loader')) { require 'PHP-Minify-Lib/Minify/Loader.php'; } if (!class_exists('Minify')) { require 'PHP-Minify-Lib/Minify.php'; } foreach ($srcs as &$src) { $src = $this->site_root . $src; } Minify_Loader::register(); $data = Minify::combine($srcs); return $data; }
} } $source = new Minify_Source($sourceSpec); $sendType = 'text/plain'; if ($type['minify'] === 'text/html' && !isset($_POST['asText'])) { $sendType = $type['sent']; } if ($type['charset']) { $sendType .= ';charset=' . $type['charset']; } header('Content-Type: ' . $sendType); // using combine instead of serve because it allows us to specify a // Content-Type like application/xhtml+xml IF we need to $minify = new Minify(new Minify_Cache_Null()); try { echo $minify->combine(array($source)); } catch (Exception $e) { header('Content-Type: text/html;charset=utf-8'); echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'); } exit; } header('Content-Type: text/html; charset=utf-8'); $ua = get_magic_quotes_gpc() ? stripslashes($_SERVER['HTTP_USER_AGENT']) : $_SERVER['HTTP_USER_AGENT']; ?> <!DOCTYPE html><head><title>Minify URL</title></head> <p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p> <h1>Fetch and Minify a URL</h1> <p>This tool will retrieve the contents of a URL and minify it.