/** * @test */ public function add() { $path1 = __DIR__ . '/sample/source/script1.js'; $path2 = __DIR__ . '/sample/source/script2.js'; $content1 = file_get_contents($path1); $content2 = file_get_contents($path2); // 1 source in add $minifier = new Minify\JS(); $minifier->add($content1); $result = $minifier->minify(); $this->assertEquals($content1, $result); // multiple sources in add $minifier = new Minify\JS(); $minifier->add($content1); $minifier->add($content2); $result = $minifier->minify(); $this->assertEquals($content1 . ';' . $content2, $result); // file in add $minifier = new Minify\JS(); $minifier->add($path1); $result = $minifier->minify(); $this->assertEquals($content1, $result); // multiple files in add $minifier = new Minify\JS(); $minifier->add($path1); $minifier->add($path2); $result = $minifier->minify(); $this->assertEquals($content1 . ';' . $content2, $result); }
/** * Test JS minifier rules, provided by dataProvider * * @test * @dataProvider dataProvider */ public function minify($input, $expected) { $input = (array) $input; foreach ($input as $js) { $this->minifier->add($js); } $result = $this->minifier->minify(); $this->assertEquals($expected, $result); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { if ('development' != $input->getArgument('environment') && 'production' != $input->getArgument('environment')) { return $output->writeln($input->getArgument('environment') . ' environment not found'); } $jsMinifier = new JS(); $cssMinifier = new CSS(); $output->writeln('Building environment: ' . $input->getArgument('environment')); $output->write('Generating JavaScript build file...'); $jsFiles = FileSystem::listDirectoryRecursive(Application::webRoot() . '/js', '/^.+\\.js$/i'); $buildFile = fopen(Application::webRoot() . '/min/build.js', 'w'); foreach ($jsFiles as $filePath) { fwrite($buildFile, file_get_contents($filePath) . "\n\n"); } fclose($buildFile); $output->writeln('done'); $output->write('Shrinking JavaScript...'); $jsMinifier->add(Application::webRoot() . '/min/build.js'); $jsMinifier->minify(Application::webRoot() . '/min/build.min.js'); $output->writeln('done'); $output->write('Compiling less files...'); $less = new \lessc(); $less->compileFile(Application::webRoot() . '/media/importer.less', Application::webRoot() . '/min/build.css'); $output->writeln('done'); $output->write('Shrinking css files...'); $cssMinifier->add(Application::webRoot() . '/min/build.css'); $cssMinifier->minify(Application::webRoot() . '/min/build.min.css'); $output->writeln('done'); return null; }
/** * Minify javascript code * * @param string $sJsFile The javascript file to be minified * @param string $sMinFile The minified javascript file * * @return boolean True if the file was minified */ public function minify($sJsFile, $sMinFile) { $xJsMinifier = new JsMinifier(); $xJsMinifier->add($sJsFile); $xJsMinifier->minify($sMinFile); return is_file($sMinFile); }
private static function minifyJs() { $sourcePathConfig = tr::config()->get("app.minify"); $minifier = new Minify\JS(); if ($sourcePathConfig['js']) { foreach ($sourcePathConfig['js'] as $v) { if (isCli()) { $v = ROOT_PATH . "/public/" . $v; } $minifier->add($v); } } $minifier->minify(ROOT_PATH . "/public/asset/global.js"); return true; }
/** * @inheritdoc */ public function execute(Source $src) { $min = new JS(); foreach ($src->getDistFiles() as $key => $file) { if (preg_match('/js$/', $file->getName()) || preg_match('/js$/', $file->getDistpathname())) { if (!$this->options['join']) { $min = new JS(); } $min->add($file->getContent()); if (!$this->options['join']) { $file->setContent($min->minify()); } else { $src->removeDistFile($key); } } } if ($this->options['join']) { $src->addDistFile(new DistFile($min->minify(), md5(uniqid(microtime())) . '.js')); } }
/** * @param SplFileInfo[] $sources * @param SplFileInfo[] $destinations * @return SplFileInfo[] */ public function run(array $sources, array $destinations) { $cssMinifier = new CSS(); $jsMinifier = new JS(); $hasJs = false; $hasCss = false; // add source files to the minifier foreach ($sources as $source) { if ($source->getExtension() == 'js') { $this->addNotification('Add ' . $source . ' to js minification'); $jsMinifier->add($source); $hasJs = true; } if ($source->getExtension() == 'css') { $this->addNotification('add ' . $source . ' to css minification'); $cssMinifier->add($source); $hasCss = true; } } $cssMinified = $this->getCacheDir() . 'minified.css'; $jsMinified = $this->getCacheDir() . 'minified.js'; $updatedSources = []; // js minification if required if ($hasJs) { $this->addNotification($jsMinified . ' js minification'); $jsMinifier->minify($jsMinified); $updatedSources[] = $jsMinified; } // css minification if required if ($hasCss) { $this->addNotification($cssMinified . ' css minification'); $cssMinifier->minify($cssMinified); $updatedSources[] = $cssMinified; } return $updatedSources; }
/** * Minify the HTML markup preserving pre, script, style and textarea tags * * @param string $strHtml The HTML markup * * @return string The minified HTML markup */ public function minifyHtml($strHtml) { // The feature has been disabled if (!\Config::get('minifyMarkup') || \Config::get('debugMode')) { return $strHtml; } // Split the markup based on the tags that shall be preserved $arrChunks = preg_split('@(</?pre[^>]*>)|(</?script[^>]*>)|(</?style[^>]*>)|( ?</?textarea[^>]*>)@i', $strHtml, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $strHtml = ''; $blnPreserveNext = false; $blnOptimizeNext = false; $strType = null; // Check for valid JavaScript types (see #7927) $isJavaScript = function ($strChunk) { $typeMatch = array(); if (preg_match('/\\stype\\s*=\\s*(?:(?J)(["\'])\\s*(?<type>.*?)\\s*\\1|(?<type>[^\\s>]+))/i', $strChunk, $typeMatch) && !in_array(strtolower($typeMatch['type']), static::$validJavaScriptTypes)) { return false; } if (preg_match('/\\slanguage\\s*=\\s*(?:(?J)(["\'])\\s*(?<type>.*?)\\s*\\1|(?<type>[^\\s>]+))/i', $strChunk, $typeMatch) && !in_array('text/' . strtolower($typeMatch['type']), static::$validJavaScriptTypes)) { return false; } return true; }; // Recombine the markup foreach ($arrChunks as $strChunk) { if (strncasecmp($strChunk, '<pre', 4) === 0 || strncasecmp(ltrim($strChunk), '<textarea', 9) === 0) { $blnPreserveNext = true; } elseif (strncasecmp($strChunk, '<script', 7) === 0) { if ($isJavaScript($strChunk)) { $blnOptimizeNext = true; $strType = 'js'; } else { $blnPreserveNext = true; } } elseif (strncasecmp($strChunk, '<style', 6) === 0) { $blnOptimizeNext = true; $strType = 'css'; } elseif ($blnPreserveNext) { $blnPreserveNext = false; } elseif ($blnOptimizeNext) { $blnOptimizeNext = false; // Minify inline scripts if ($strType == 'js') { $objMinify = new Minify\JS(); $objMinify->add($strChunk); $strChunk = $objMinify->minify(); } elseif ($strType == 'css') { $objMinify = new Minify\CSS(); $objMinify->add($strChunk); $strChunk = $objMinify->minify(); } } else { // Remove line indentations and trailing spaces $strChunk = str_replace("\r", '', $strChunk); $strChunk = preg_replace(array('/^[\\t ]+/m', '/[\\t ]+$/m', '/\\n\\n+/'), array('', '', "\n"), $strChunk); } $strHtml .= $strChunk; } return trim($strHtml); }
/** * @param array $assets * @param string $saveFile * @param string $webPath * @return string * @throws FileNotFoundException * @throws FileSystemException */ public function compressAndMerge(array $assets, $saveFile, $webPath = '') { $saveDir = dirname($saveFile); $oldKey = ''; // create path. if (!Directory::create($saveDir)) { throw new FileSystemException("Create dir path [{$saveDir}] failure!!"); } // check target file exists if (file_exists($saveFile)) { $oldKey = md5(file_get_contents($saveFile)); } if ($this->assetType === self::TYPE_CSS) { $minifier = new Minify\CSS(); } else { $minifier = new Minify\JS(); } $basePath = $this->getBasePath(); foreach ($assets as $url) { // is full url, have http ... if (!UrlHelper::isRelative($url)) { $this->compressedAssets[] = $url; continue; } $sourceFile = $basePath . '/' . $url; if (!is_file($sourceFile)) { throw new FileNotFoundException("File [{$sourceFile}] don't exists! please check it."); } $minifier->add($sourceFile); } // check file content has changed. if ($oldKey) { $newContent = $minifier->minify(); $newKey = md5($newContent); if ($newKey !== $oldKey) { File::write($newContent, $saveFile); } } else { $minifier->minify($saveFile); } return $this->baseUrl . str_replace($webPath ?: $basePath, '', $saveFile); }
<?php ini_set("max_execution_time", 190); require_once 'config/_definitions.php'; //load main node config require_once CORE_REPOSITORY_REAL_PATH . 'vendor/autoload.php'; use MatthiasMullie\Minify; $minifier = new Minify\CSS(); $sourcePathArray = ['css/bootstrap.min.css', 'css/core.css', 'css/jquery-ui.css', 'js/jquery-timepicker/jquery-ui-timepicker-addon.css', 'css/jquery.timepicker.css', 'css/jquery.fancybox.css', 'css/bootstrap-switch.min.css', 'css/search/search.css', 'css/fullcalendar.css', 'js/notify/css/bootstrap-notify.css', 'css/custom-menu.css']; foreach ($sourcePathArray as $cssPath) { $minifier->add(CORE_REPOSITORY_REAL_PATH . $cssPath); } // save minified file to disk $minifier->minify(CORE_REPOSITORY_REAL_PATH . 'css/build/core.css'); $minifier = new Minify\JS(); $sourcePathArrayJS = ['js/jquery/jquery-1.11.0.min.js', 'js/support/support.js', 'js/jquery/jquery-ui-1.10.3.custom.js', 'js/jquery-timepicker/jquery-ui-timepicker-addon.js', 'js/jquery/jquery.timepicker.min.js', 'js/bootstrap.js', 'js/modals/Modal.class.js', 'js/search/core.class.js', 'js/search/clicker.js', 'js/core.js', "js/notify/js/soundmanager2-nodebug-jsmin.js", "js/notify/js/bootstrap-notify.js", "js/production/fancybox/source/jquery.fancybox.pack.js", "js/bootstrap-switch.min.js", "js/jquery.fancybox.js", "js/lib/moment.min.js", "js/fullcalendar.js", "js/ru.js", 'js/jquery/spinner.js', 'js/jquery/spin.jquery.plugin.js']; foreach ($sourcePathArrayJS as $jsPath) { $minifier->add(CORE_REPOSITORY_REAL_PATH . $jsPath); } // save minified file to disk $minifier->minify(CORE_REPOSITORY_REAL_PATH . 'js/build/core.js');
/** * Add components javascript file to minifier if component is enabled * * @param \MatthiasMullie\Minify\JS $minify minifier instance * @param string $componentName valid component name * @param string|null $fileName file name (if not set component name is used) * * @return void */ protected function addJsToMinifier(Minify\JS $minify, $componentName, $fileName = null) { if ($fileName === null) { $fileName = $componentName; } // Add component data to minifier if it is enabled if ($this->components[$componentName] === true) { $minify->add(base_path("vendor/twbs/bootstrap/js/{$fileName}.js")); } }
public function _minify($code = NULL) { if (is_null($code)) { $code = $this->code; } //---------------------------------------------------------- //init var //---------------------------------------------------------- $chk = array("bool" => true, 'traceID' => "minJs"); //---------------------------------------------------------- if ($this->type == "js" || strpos($this->fileName, "js") !== false) { //krumo($this->type); //krumo($this->code); //print_r($code." ||||||||||||||||||||||| "); //$code = StringUtil::removeAllJSComments($code); $minifier = new Minify\JS(); $minifier->add($code); $content = $minifier->minify(); } else { if ($this->type == "css" || strpos($this->fileName, "css") !== false) { $minifier = new Minify\CSS(); $minifier->add($code); $content = $minifier->minify(); } else { if (strpos($this->fileName, "html") !== false) { $content = $code; } } } //---------------------------------------------------------- $chk['result'] = $content; //---------------------------------------------------------- if (is_null($fileLocation)) { $chk['message'] = "code has been successfully minified!!!!!"; } //---------------------------------------------------------- //$chk = CreateFile_v0::go($this->fileName, $content, $this->fileLocation, true); //---------------------------------------------------------- //Minifier_v0::createDependantFiles($content); //---------------------------------------------------------- return $chk; }
<?php defined('_JEXEC') or die; require_once '_define.php'; require_once 'vendor/autoload.php'; use Antfuentes\Titan\Joomla; use Antfuentes\Titan\Framework; //use Pelago\Emogrifier; use MatthiasMullie\Minify; $minifier = new Minify\JS(__DIR__ . '/bower/jquery/dist/jquery.min.js'); $minifier->add(__DIR__ . '/bower/matchHeight/jquery.matchHeight-min.js'); $minifier->add(__DIR__ . '/bower/jquery.tap/jquery.tap.min.js'); $minifier->add(__DIR__ . '/bower/gsap/src/minified/jquery.gsap.min.js'); $minifier->add(__DIR__ . '/bower/gsap/src/minified/easing/EasePack.min.js'); $minifier->add(__DIR__ . '/bower/gsap/src/minified/plugins/CSSPlugin.min.js'); $minifier->add(__DIR__ . '/bower/gsap/src/minified/TweenLite.min.js'); $minifier->add(__DIR__ . '/bower/wallop/js/Wallop.min.js'); $minifier->add(__DIR__ . '/bower/leviathan/src/js/init.js'); $minifier->add(__DIR__ . '/bower/leviathan/src/js/accordion.js'); $minifier->add(__DIR__ . '/bower/leviathan/src/js/facebook.js'); $minifier->add(__DIR__ . '/scripts/app.js'); $minifier->minify(__DIR__ . '/scripts/load.js'); $router = new Joomla\Router(); $menu = new Joomla\Menu(); $db = new Joomla\Database(); //$emogrifier = new Pelago\Emogrifier(); $string = new Framework\String(); $h = new Framework\Html(); $module = new Joomla\Module(); $article = new Joomla\Article(); $router->load(JRequest::getVar('id'), ROUTE, JRequest::getVar('option'), JRequest::getVar('view'), JRequest::getVar('layout'), JFactory::getConfig(), JUri::getInstance(), JURI::base());
<?php use MatthiasMullie\Minify; $minifier = new Minify\JS(); foreach (scandir(get_template_directory() . '/assets/js/libs') as $key => $value) { if (strpos($value, '.js')) { $minifier->add(get_template_directory() . '/assets/js/libs/' . $value); } } $minifiedPath = get_template_directory() . '/assets/js/libs.min.js'; $minifier->minify($minifiedPath);
/** * Creates the asset * @return string * @throws InternalErrorException * @uses $asset * @uses $paths * @uses $type */ public function create() { if (!is_readable($this->asset)) { switch ($this->type) { case 'css': $minifier = new Minify\CSS(); break; case 'js': $minifier = new Minify\JS(); break; } foreach ($this->paths as $path) { $minifier->add($path); } //Writes the file if (!(new File($this->asset, false, 0755))->write($minifier->minify())) { throw new InternalErrorException(__d('assets', 'Failed to create file {0}', str_replace(APP, null, $this->asset))); } } return pathinfo($this->asset, PATHINFO_FILENAME); }
public function __destruct() { // API if (substr($_SERVER['HTTP_ACCEPT'], 0, 6) == 'api://') { header('Content-Type: application/json'); die((new Exec(substr($_SERVER['HTTP_ACCEPT'], 6), file_get_contents('php://input')))->json()); } // API[FILE] if (substr($_SERVER['HTTP_ACCEPT'], 0, 12) == 'api[file]://') { $file = file_get_contents('php://input'); $fileTmp = tempnam(sys_get_temp_dir(), microtime(1)); file_put_contents($fileTmp, $file); File::add($fileTmp); die((new Exec(substr($_SERVER['HTTP_ACCEPT'], 12)))->json()); } // VIEW if (substr($_SERVER['HTTP_ACCEPT'], 0, 7) == 'view://') { header('Content-Type: application/json'); $path = substr($_SERVER['HTTP_ACCEPT'], 7); $html = explode('/', $path); foreach ($html as $key => $value) { $value = trim($value); if (empty($value)) { unset($html[$key]); } } $output = []; ob_start(); $view = new View(); if (empty($html)) { $html = ['index']; } while ($name = array_shift($html)) { if (count($html) == 0) { $view->{$name}(); } else { $view = $view->{$name}; } } $html = ob_get_clean(); $html = preg_replace('/\\>\\s+\\</Uui', '><', $html); $html = preg_replace('/\\s/Uui', ' ', $html); $html = preg_replace('/[ ]+/Uui', ' ', $html); $output['html'] = $html; $path = Path::$view . '' . $path; $css = $path . '/index.css'; if (is_file($css)) { $output['css'] = file_get_contents($css); } $js = $path . '/index.js'; if (is_file($js)) { $output['js'] = file_get_contents($js); } die(json_encode($output, JSON_UNESCAPED_UNICODE)); } // Json $json = function ($path) { $json = $path . '/index.json'; if (is_file($json)) { $json = file_get_contents($json); $json = json_decode($json, true); } return $json; }; // Save get $save = Save::get(); // Type Content switch (Path::$path) { case "js": $type = 'js'; break; case "css": $type = 'css'; break; default: $type = 'page'; } // Js if ($type == 'js') { header("Content-Type: text/javascript"); $config = $json(Path::$page . '/' . $_GET['path']); $content = ''; // Config if (isset($config['js']) && is_array($config['js'])) { foreach ($config['js'] as $value) { $file = Path::$js . '/' . $value . '.js'; if (is_file($file)) { $content .= file_get_contents($file); } } } // Slave $slave = Path::$page . '/' . $_GET['path'] . '/index.js'; if (is_file($slave)) { $content .= file_get_contents($slave); } // Slave js if (isset($save['view'])) { foreach ($save['view'] as $path) { $config = $json(Path::$view . '/' . $path); if (isset($config['js']) && is_array($config['js'])) { foreach ($config['js'] as $value) { $file = Path::$js . '/' . $value . '.js'; if (is_file($file)) { $content .= file_get_contents($file); } } } $file = Path::$view . $path . '/index.js'; if (!is_file($file)) { continue; } $content .= file_get_contents($file); } } // Minify if (!empty($content)) { $minifier = new JS(); $minifier->add($content); $content = $minifier->minify(); } die($content); } // Css if ($type == 'css') { header("Content-Type: text/css"); $config = $json(Path::$page . '/' . $_GET['path']); $content = ''; // Config if (isset($config['css']) && is_array($config['css'])) { foreach ($config['css'] as $value) { $file = Path::$css . '/' . $value . '.css'; if (is_file($file)) { $content .= file_get_contents($file); } } } // Slave $slave = Path::$page . '/' . $_GET['path'] . '/index.css'; if (is_file($slave)) { $content .= file_get_contents($slave); } // Slave view if (isset($save['view'])) { foreach ($save['view'] as $path) { $config = $json(Path::$view . '/' . $path); if (isset($config['css']) && is_array($config['css'])) { foreach ($config['css'] as $value) { $file = Path::$css . '/' . $value . '.css'; if (is_file($file)) { $content .= file_get_contents($file); } } } $file = Path::$view . $path . '/index.css'; if (!is_file($file)) { continue; } $content .= file_get_contents($file); } } // Minify if (!empty($content)) { $minifier = new CSS(); $minifier->add($content); $content = $minifier->minify(); } die($content); } // Page $content = ''; ob_start(); new Page(); $content = ob_get_clean(); $save = Save::get(); $save['view'] = Info::$view; Save::set($save); $title = Meta::$title; $title = implode(' – ', $title); $description = Meta::$description; $keywords = Meta::$keywords; $keywords = implode(', ', $keywords); $content = '<!DOCTYPE html>' . '<html>' . '<head>' . '<title>' . $title . '</title>' . '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . '<link rel="icon" type="image/x-icon" sizes="16x16" href="/favicon.ico">' . '<meta name ="Generator" Content="LiveSugare">' . '<meta name="description" Content="' . $description . '">' . '<meta name="keywords" Content="' . $keywords . '">' . '<meta name="robots" content="Index,follow">' . '<meta charset="utf-8">' . '<meta name="viewport" content="width=device-width, initial-scale=1">' . '<link rel="stylesheet" type="text/css" href="/css?path=' . Path::$path . '">' . '<script src="/js?path=' . Path::$path . '" type="text/javascript"></script>' . '</head>' . '<body>' . $content . '</body></html>'; $content = preg_replace('/\\>\\s+\\</Uui', '><', $content); $content = preg_replace('/\\s/Uui', ' ', $content); $content = preg_replace('/[ ]+/Uui', ' ', $content); die($content); }
/** * Test JS minifier rules, provided by dataProvider * * @test * @dataProvider dataProvider */ public function minify($input, $expected) { $this->minifier->add($input); $result = $this->minifier->minify(); $this->assertEquals($expected, $result); }
public static function minifyScript($script) { $minifier = new Minify\JS(); $minifier->add($script); return $minifier->minify(); }
public function performMinification($script) { $minifier = new JS(); $minifier->add($script); return $minifier->minify(); }
/** * * * @return string */ public function __toString() { $result = ''; try { // If we want to minify if ($this->isMinify()) { $hash = ''; $contents = []; // manage remote or local file foreach ($this->container as $content) { list($t, $c) = $content; if ($t == static::TYPE_FILE) { // scheme case if (preg_match('#^//.+$#', $c)) { $c = 'http:' . $c; $contents[] = ['remote', $c]; $hash .= md5($c); // url case } elseif (preg_match('#^https?//.+$#', $c)) { $contents[] = ['remote', $c]; $hash .= md5($c); // local file } else { $c = public_path($c); $hash .= md5_file($c); $contents[] = ['local', $c]; } } elseif ($t == static::TYPE_INLINE) { $hash .= md5($c); $contents[] = ['inline', $c]; } } // destination file $target = public_path($this->getTargetPath()); if (substr($target, -1) != '/') { $target .= '/'; } $target .= md5($hash) . '.js'; // add css to minifier if (!file_exists($target)) { $minifier = new MiniJs(); // Remote file management foreach ($contents as $content) { list($t, $c) = $content; // we get remote file content if ($t == 'remote') { $c = file_get_contents($c); } $minifier->add($c); } // minify $minifier->minify($target); } // set $file $result .= html('script', ['src' => str_replace(public_path(), '', $target), 'type' => 'text/javascript']) . PHP_EOL; } else { foreach ($this->container as $content) { list($t, $c) = $content; // render file if ($t == static::TYPE_FILE) { $result .= html('script', ['src' => $c, 'type' => 'text/javascript']) . PHP_EOL; // render style } elseif ($t == static::TYPE_INLINE) { $result .= $c . $this->getGlue(); } } } } catch (\Exception $e) { $result = '<!--' . PHP_EOL . 'Error on css generation' . PHP_EOL; // stack trace if in debug mode if (debug()) { $result .= $e->getMessage() . ' : ' . PHP_EOL . $e->getTraceAsString() . PHP_EOL; } $result .= '-->'; } return $result; }
public function minifyJs($s) { $oMinifier = new Minify\JS(); $oMinifier->add($s); return $oMinifier->minify(); }