This source file can be used to minify Javascript files. The class is documented in the file itself. If you find any bugs help me out and report them. Reporting can be done by sending an email to minify@mullie.eu. If you report a bug, make sure you give me enough information (include your code). License Copyright (c) 2012, Matthias Mullie. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the author "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the author be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
Автор: Matthias Mullie (minify@mullie.eu)
Автор: Tijs Verkoyen (minify@verkoyen.eu)
Наследование: extends Minify
Пример #1
0
 /**
  * @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;
 }
Пример #2
0
 /**
  * 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);
 }
 /**
  * @test
  */
 public function save()
 {
     $path1 = __DIR__ . '/sample/source/script1.js';
     $content1 = file_get_contents($path1);
     $savePath = __DIR__ . '/sample/target/script1.js';
     $minifier = new Minify\JS($path1);
     $minifier->minify($savePath);
     $this->assertEquals(file_get_contents($savePath), $content1);
 }
Пример #4
0
 /**
  * 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);
 }
Пример #5
0
 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;
 }
Пример #6
0
 /**
  * @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'));
     }
 }
Пример #7
0
 /**
  * @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;
 }
Пример #8
0
<?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());
Пример #9
0
<?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);
Пример #10
0
<?php

require __DIR__ . '/../vendor/autoload.php';
use MatthiasMullie\Minify;
$minifier = new Minify\JS(__DIR__ . '/../src/adsGlobalFunctions.js');
$minifier->compile(__DIR__ . '/../dist/js/adsGlobalFunctions.js');
$minifier->minify(__DIR__ . '/../dist/js/adsGlobalFunctions.min.js');
Пример #11
0
 /**
  * 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);
 }
Пример #12
0
 private function ProcessSiteFolder($source, $dest, $folderPermissions, $filePermissions, $ignoreFiles = null, $ignoreMasks = null)
 {
     // Check for symlinks
     if (is_link($source)) {
         // No support for symlinks
         return true;
         //            return symlink(readlink($source), $dest);
     }
     // If it truly is a file
     if (is_file($source)) {
         // Check file is a Blueprint, ignore if it is and add it to the views, else copy it.
         $check = strpos(file_get_contents($source), TAG_START . TAG_BLUEPRINT);
         if ($check !== false) {
             $this->views[] = new View($this, $source);
             return true;
         }
         // Is this file a compress-ible file?
         if ($this->getGlobalCompression()) {
             // Copy / Return the already minimized versions of libraries
             if (strpos($source, ".min.") || strpos($source, "-min.")) {
                 Core::Output(INFO, "Not Compressing " . $source);
                 return copy($source, $dest);
             }
             switch (strtolower(pathinfo($dest, PATHINFO_EXTENSION))) {
                 case 'js':
                     $minifier = new Minify\JS($source);
                     Core::Output(INFO, "Compressing " . $source);
                     return file_put_contents($dest, $minifier->minify());
                 case 'css':
                     $minifier = new Minify\CSS($source);
                     Core::Output(INFO, "Compressing " . $source);
                     return file_put_contents($dest, $minifier->minify());
                 default:
                     return copy($source, $dest);
             }
         } else {
             return copy($source, $dest);
         }
     }
     // Make destination directory
     if (!is_dir($dest)) {
         mkdir($dest, $folderPermissions, true);
     }
     // Loop through the folder
     $dir = dir($source);
     while (false !== ($entry = $dir->read())) {
         // Skip pointers
         if ($entry == '.' || $entry == '..' || in_array($entry, $ignoreFiles) || \StringHelper::MaskCheck($entry, $ignoreMasks)) {
             continue;
         }
         // Deep copy directories
         $this->ProcessSiteFolder("{$source}/{$entry}", "{$dest}/{$entry}", $folderPermissions, $filePermissions, $ignoreFiles, $ignoreMasks);
     }
     // Clean up
     $dir->close();
     return true;
 }
Пример #13
0
 /**
  * @param string $source
  * @return string
  */
 protected function minifyWithFallback($source)
 {
     $minifier = new Minify\JS($source);
     return $minifier->minify();
 }
Пример #14
0
 /**
  * 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"));
     }
 }
Пример #15
0
 /**
  * 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);
 }
Пример #16
0
 /**
  * Minify JS.
  *
  * @param $value
  *
  * @return string
  */
 public function minifyJs($value)
 {
     $minifier = new Minify\JS($value);
     return $minifier->minify();
 }
Пример #17
0
 public static function minifyScript($script)
 {
     $minifier = new Minify\JS();
     $minifier->add($script);
     return $minifier->minify();
 }
Пример #18
0
<?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');
Пример #19
0
 public function performMinification($script)
 {
     $minifier = new JS();
     $minifier->add($script);
     return $minifier->minify();
 }
Пример #20
0
 /**
  * Minify a JS-file
  *
  * @param string $file The file to be minified.
  * @return string
  */
 private function minifyJS($file)
 {
     // create unique filename
     $fileName = md5($file) . '.js';
     $finalURL = BACKEND_CACHE_URL . '/MinifiedJs/' . $fileName;
     $finalPath = BACKEND_CACHE_PATH . '/MinifiedJs/' . $fileName;
     // check that file does not yet exist or has been updated already
     if (!is_file($finalPath) || filemtime(PATH_WWW . $file) > filemtime($finalPath)) {
         // minify the file
         $js = new Minify\JS(PATH_WWW . $file);
         $js->minify($finalPath);
     }
     return $finalURL;
 }
Пример #21
0
 /**
  * Minify a javascript-file
  *
  * @param string $file The file to be minified.
  * @return string
  */
 private function minifyJS($file)
 {
     $fileName = md5($file) . '.js';
     $finalURL = FRONTEND_CACHE_URL . '/MinifiedJs/' . $fileName;
     $finalPath = FRONTEND_CACHE_PATH . '/MinifiedJs/' . $fileName;
     // check that file does not yet exist or has been updated already
     $fs = new Filesystem();
     if (!$fs->exists($finalPath) || filemtime(PATH_WWW . $file) > filemtime($finalPath)) {
         // create directory if it does not exist
         if (!$fs->exists(dirname($finalPath))) {
             $fs->mkdir(dirname($finalPath));
         }
         // minify the file
         $js = new Minify\JS(PATH_WWW . $file);
         $js->minify($finalPath);
     }
     return $finalURL;
 }
Пример #22
0
 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(' &ndash; ', $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);
 }
Пример #23
0
 /**
  * @test
  */
 public function cache()
 {
     $path = __DIR__ . '/sample/source/script1.js';
     $content = file_get_contents($path);
     $cache = new MemoryStore();
     $pool = new Pool($cache);
     $item = $pool->getItem('cache-script1');
     $minifier = new Minify\JS($path);
     $item = $minifier->cache($item);
     $this->assertEquals($item->get(), $content);
 }
Пример #24
0
 /**
  * Adds script to DOM with unique hash based on the md5_file
  *
  * At least for the active development it's useful as makes browser
  * ignrore script caching on script file changed.
  * TODO Consider to skip this md5_file for production, as md5 is known to be slow
  * But production will be developed intensively anyway. So I assum this function should
  * stay as is
  *
  * @param   string  $url                Locally placed script
  * @param   bool    $includeMinified    Wether to include full or minified
  * @param   bool    $regenrateMinified  Force minifed file regeneration from full files
  *
  * @return   void
  */
 public static function _addJSorCSS($url, $includeMinified = true, $regenrateMinified = false)
 {
     if (static::$debug) {
         $regenrateMinified = true;
         $includeMinified = false;
     }
     // Get file path
     $file_path = JPATH_ROOT . '/' . $url;
     // Just in case the web-site is not in the root of the domain name, like localhost/noble/index.php
     $uribase = JUri::base(true);
     if (!empty($uribase)) {
         $file_path = JPath::clean(str_replace(JPATH_ROOT . '/' . JUri::base(true), JPATH_ROOT . '/', $file_path));
         $url = JPath::clean(JUri::root(true) . '/' . $url);
     }
     // If the file is a local one, then add it's md5_file hash to the link
     if (!JFile::exists($file_path)) {
         return;
     }
     $file_path = JPath::clean($file_path);
     $type = JFile::getExt($file_path);
     if ($regenrateMinified || $includeMinified) {
         $file_path_mnified = dirname($file_path) . '/' . basename($file_path, '.' . $type) . '.min.' . $type;
         $file_path_mnified = JPath::clean($file_path_mnified);
         $url_minified = dirname($url) . '/' . basename($url, '.' . $type) . '.min.' . $type;
         $url_minified = JPath::clean($url_minified);
     }
     if ($regenrateMinified || $includeMinified && !JFile::exists($file_path_mnified)) {
         $sourcePath = $file_path;
         $minifier = new Minify\JS($sourcePath);
         // Save minified file to disk
         $minifiedPath = $file_path_mnified;
         $minifier->minify($minifiedPath);
     }
     if ($includeMinified) {
         $url = $url_minified;
         // $file_path = md5_file($file_path);
     } else {
         // $file_path = md5_file($file_path);
     }
     $doc = JFactory::getDocument();
     if ($type == 'js') {
         $doc->addScriptVersion($url);
     } else {
         $doc->addStyleSheet($url);
     }
 }
Пример #25
0
 /**
  * @param string $url
  * @param string $saveFile If is empty, will save to old file dir.
  * @param string $webPath
  * @return string
  * @throws FileNotFoundException
  * @throws FileSystemException
  */
 public function compressAndSave($url, $saveFile = '', $webPath = '')
 {
     // is full url, have http ...
     if (!UrlHelper::isRelative($url)) {
         return $url;
     }
     $oldKey = null;
     $basePath = $this->getBasePath();
     $sourceFile = $basePath . '/' . $url;
     if (!is_file($sourceFile)) {
         throw new FileNotFoundException("File [{$sourceFile}] don't exists!!");
     }
     // maybe need create directory.
     if ($saveFile) {
         $saveDir = dirname($saveFile);
         // create path.
         if (!Directory::create($saveDir)) {
             throw new FileSystemException("Create dir path [{$saveDir}] failure!!");
         }
     } else {
         $saveFile = substr($sourceFile, 0, -strlen($this->assetType)) . 'min.' . $this->assetType;
     }
     // check target file exists
     if (file_exists($saveFile)) {
         $oldKey = md5(file_get_contents($saveFile));
     }
     if ($this->assetType === self::TYPE_CSS) {
         $minifier = new Minify\CSS($sourceFile);
     } else {
         $minifier = new Minify\JS($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);
 }
Пример #26
0
 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;
 }
Пример #27
0
 /**
  * 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);
 }
Пример #28
0
 /**
  *
  *
  * @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;
 }
Пример #29
0
 public function minify($src)
 {
     $minifier = new Minify\JS($src);
     return $minifier->minify();
 }
Пример #30
0
 public function minifyJs($s)
 {
     $oMinifier = new Minify\JS();
     $oMinifier->add($s);
     return $oMinifier->minify();
 }