/**
  * Apply JShrink to $content.
  *
  * @param string $filename target filename
  * @param string $content Content to filter.
  * @throws Exception
  * @return string
  */
 public function output($filename, $content)
 {
     if (!class_exists('JShrink\\Minifier')) {
         throw new \Exception(sprintf('Cannot not load filter class "%s".', 'JShrink\\Minifier'));
     }
     return Minifier::minify($content, array('flaggedComments' => $this->_settings['flaggedComments']));
 }
 /**
  * Compresses and minifies a javascript file
  *
  * @param string $filename Source filename, relative to requested page
  * @return string Filename of the compressed file, relative to requested page
  */
 public function compressJsFile($filename)
 {
     // generate the unique name of the file
     $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $this->getFilenameFromMainDir($filename));
     if (@file_exists($filenameAbsolute)) {
         $fileStatus = stat($filenameAbsolute);
         $unique = $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size'];
     } else {
         $unique = $filenameAbsolute;
     }
     $pathinfo = PathUtility::pathinfo($filename);
     $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.js';
     // only create it, if it doesn't exist, yet
     if (!file_exists(PATH_site . $targetFile) || $this->createGzipped && !file_exists(PATH_site . $targetFile . '.gzip')) {
         $contents = file_get_contents($filenameAbsolute);
         try {
             $minifiedContents = Minifier::minify($contents);
         } catch (\Exception $e) {
             // Log error and use un-minified content as fallback
             /** @var $logger Logger */
             $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
             $logger->error($e->getMessage(), ['filename' => $filename]);
             $minifiedContents = $contents;
         }
         $this->writeFileAndCompressed($targetFile, $minifiedContents);
     }
     return $this->relativePath . $this->returnFileReference($targetFile);
 }
Example #3
0
 public static function send($minified = false)
 {
     header('Content-Type: application/javascript');
     $basedir = Icinga::app()->getBootstrapDirecory();
     $js = $out = '';
     $min = $minified ? '.min' : '';
     // TODO: Cache header
     header('Content-Type: application/javascript');
     $cacheFile = '/tmp/cache_icinga' . $min . '.js';
     if (file_exists($cacheFile)) {
         readfile($cacheFile);
         exit;
     }
     // We do not minify vendor files
     foreach (self::$vendorFiles as $file) {
         $out .= file_get_contents($basedir . '/' . $file . $min . '.js');
     }
     foreach (self::$jsFiles as $file) {
         $js .= file_get_contents($basedir . '/' . $file);
     }
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $name => $module) {
         if ($module->hasJs()) {
             $js .= file_get_contents($module->getJsFilename());
         }
     }
     if ($minified) {
         require_once 'IcingaVendor/JShrink/Minifier.php';
         $out .= Minifier::minify($js, array('flaggedComments' => false));
     } else {
         $out .= $js;
     }
     // Not yet, this is for tests only. Waiting for Icinga\Web\Cache
     // file_put_contents($cacheFile, $out);
     echo $out;
 }
 /**
  * Compress code
  * @param string $code - unminified code string
  * @return string - code string minified/processed as requested
  */
 public function compress($code)
 {
     if ($this->isAvailable()) {
         $code = \JShrink\Minifier::minify($code, $this->settings['jshrink']);
     }
     return $code;
 }
Example #5
0
 /**
  * @param Asset[] $assets
  *
  * @return Asset[]
  */
 public static function process($assets)
 {
     if ($directory = self::getOutputDirectory()) {
         $relativeDirectory = self::getRelativeOutputDirectory();
         $filename = '';
         $sourceFiles = array();
         for ($i = 0; $i < count($assets); $i++) {
             $asset = $assets[$i];
             $filename .= $asset->getAssetHashKey();
             $sourceFiles[] = $asset->getAssetURL();
         }
         $filename = sha1($filename);
         $cacheFile = $directory . '/' . $filename . '.js';
         if (!file_exists($cacheFile)) {
             $js = '';
             foreach ($assets as $asset) {
                 $contents = $asset->getAssetContents();
                 if (isset($contents)) {
                     if ($asset->assetSupportsMinification()) {
                         $contents = \JShrink\Minifier::minify($contents);
                     }
                     $js .= $contents . "\n\n";
                 }
             }
             @file_put_contents($cacheFile, $js);
         }
         $asset = new JavascriptAsset();
         $asset->setAssetURL($relativeDirectory . '/' . $filename . '.js');
         $asset->setAssetPath($directory . '/' . $filename . '.js');
         $asset->setCombinedAssetSourceFiles($sourceFiles);
         return array($asset);
     }
     return $assets;
 }
Example #6
0
 /**
  * JavaScript Minification
  *
  * @param string $file
  * @param array $arguments
  * @param array $javaScriptOptions
  *
  * @return void
  */
 public function doFilter($file, $arguments, $javaScriptOptions)
 {
     if (!$arguments['minify']) {
         return;
     }
     file_put_contents($file, Minifier::minify(file_get_contents($file)));
 }
Example #7
0
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
function smarty_block_scripts($params, $content, &$smarty, &$repeat)
{
    if ($repeat == true) {
        Registry::set('runtime.inside_scripts', 1);
        return;
    }
    if (Registry::get('config.tweaks.dev_js')) {
        $content .= smarty_helper_inline_scripts($params, $content, $smarty, $repeat);
        return $content;
    }
    $scripts = array();
    $external_scripts = array();
    $dir_root = Registry::get('config.dir.root');
    $return = '';
    $current_location = Registry::get('config.current_location');
    if (preg_match_all('/\\<script(.*?)\\>(.*?)\\<\\/script\\>/s', $content, $m)) {
        $contents = '';
        foreach ($m[1] as $src) {
            if (!empty($src) && preg_match('/src ?= ?"([^"]+)"/', $src, $_m)) {
                if (strpos($_m[1], $current_location) !== false) {
                    $scripts[] = str_replace($current_location, '', preg_replace('/\\?.*?$/', '', $_m[1]));
                } else {
                    $external_scripts[] = $_m[1];
                }
            }
        }
        // Check file changes in dev mode
        $names = $scripts;
        if (Development::isEnabled('compile_check')) {
            foreach ($names as $index => $name) {
                if (is_file($dir_root . '/' . $name)) {
                    $names[$index] .= filemtime($dir_root . '/' . $name);
                }
            }
        }
        $filename = 'js/tygh/scripts-' . md5(implode(',', $names)) . fn_get_storage_data('cache_id') . '.js';
        if (!Storage::instance('statics')->isExist($filename)) {
            foreach ($scripts as $src) {
                $contents .= fn_get_contents(Registry::get('config.dir.root') . $src);
            }
            $contents = str_replace('[files]', implode("\n", $scripts), Registry::get('config.js_css_cache_msg')) . $contents;
            $contents = Minifier::minify($contents, array('flaggedComments' => false));
            Storage::instance('statics')->put($filename, array('contents' => $contents, 'compress' => false, 'caching' => true));
        }
        $return = '<script type="text/javascript" src="' . Storage::instance('statics')->getUrl($filename) . '?ver=' . PRODUCT_VERSION . '"></script>' . "\n";
        if (!empty($external_scripts)) {
            foreach ($external_scripts as $sc) {
                $return .= '<script type="text/javascript" src="' . $sc . '"></script>' . "\n";
            }
        }
        foreach ($m[2] as $sc) {
            if (!empty($sc)) {
                $return .= '<script type="text/javascript">' . $sc . '</script>' . "\n";
            }
        }
        $return .= smarty_helper_inline_scripts($params, $content, $smarty, $repeat);
    }
    return $return;
}
Example #8
0
 /**
  * Send the client side script code to the client
  *
  * Does not cache the client side script code if the HTTP header Cache-Control or Pragma is set to no-cache.
  *
  * @param   bool    $minified   Whether to compress the client side script code
  */
 public static function send($minified = false)
 {
     header('Content-Type: application/javascript');
     $basedir = Icinga::app()->getBootstrapDirectory();
     $js = $out = '';
     $min = $minified ? '.min' : '';
     // Prepare vendor file list
     $vendorFiles = array();
     foreach (self::$vendorFiles as $file) {
         $vendorFiles[] = $basedir . '/' . $file . $min . '.js';
     }
     // Prepare Icinga JS file list
     $jsFiles = array();
     foreach (self::$jsFiles as $file) {
         $jsFiles[] = $basedir . '/' . $file;
     }
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $name => $module) {
         if ($module->hasJs()) {
             foreach ($module->getJsFiles() as $path) {
                 if (file_exists($path)) {
                     $jsFiles[] = $path;
                 }
             }
         }
     }
     $files = array_merge($vendorFiles, $jsFiles);
     $request = Icinga::app()->getRequest();
     $noCache = $request->getHeader('Cache-Control') === 'no-cache' || $request->getHeader('Pragma') === 'no-cache';
     if (!$noCache && FileCache::etagMatchesFiles($files)) {
         header("HTTP/1.1 304 Not Modified");
         return;
     } else {
         $etag = FileCache::etagForFiles($files);
     }
     header('Cache-Control: public');
     header('ETag: "' . $etag . '"');
     header('Content-Type: application/javascript');
     $cacheFile = 'icinga-' . $etag . $min . '.js';
     $cache = FileCache::instance();
     if (!$noCache && $cache->has($cacheFile)) {
         $cache->send($cacheFile);
         return;
     }
     // We do not minify vendor files
     foreach ($vendorFiles as $file) {
         $out .= ';' . ltrim(trim(file_get_contents($file)), ';') . "\n";
     }
     foreach ($jsFiles as $file) {
         $js .= file_get_contents($file) . "\n\n\n";
     }
     if ($minified) {
         require_once 'JShrink/Minifier.php';
         $out .= Minifier::minify($js, array('flaggedComments' => false));
     } else {
         $out .= $js;
     }
     $cache->store($cacheFile, $out);
     echo $out;
 }
 /**
  * @return \Salva\JshrinkBundle\Cache\CacheInterface
  */
 private function getCacheMock()
 {
     $mock = $this->getMock('\\Salva\\JshrinkBundle\\Cache\\CacheInterface');
     $mock->expects($this->any())->method('minify')->willReturnCallback(function ($arg) {
         return \JShrink\Minifier::minify($arg);
     });
     return $mock;
 }
Example #10
0
 /**
  * {@inheritDoc}
  */
 public function compact($contents)
 {
     try {
         return Minifier::minify($contents);
     } catch (\Exception $e) {
         return $contents;
     }
 }
Example #11
0
 function wad_selection_box($jsOnCall, $placeholder = 'Type to search for WADs...')
 {
     $boxid = mt_rand();
     $wboxid = 'wsb' . $boxid;
     echo "<!-- autogenerated WAD search form | {$boxid} -->\n<div id='g{$boxid}'>";
     echo "<input type='text' name='n{$wboxid}' id='{$wboxid}' placeholder='{$placeholder}' />\n\t\t\t<script>";
     echo \JShrink\Minifier::minify("\n\tvar _{$boxid} = {\n\t\tselected: -1,\n\t\tresults: 0,\n\t\tres: [],\n\t\tsrc: false,\n\t\toriginal: '',\n\t\tevlock: false,\n\t\tdoreset: false,\n\n\t\tfocused: function() {\n\t\t\tif (\$('#{$wboxid}').is(':focus'))\n\t\t\t\treturn true;\n\n\t\t\tif (\$('#dbx').is(':focus'))\n\t\t\t\treturn true;\n\n\t\t\tif (_{$boxid}.src)\n\t\t\t\tfor (var i = 0; i < _{$boxid}.results; i++)\n\t\t\t\t\tif (\$('#dbx-c' + i).is(':focus'))\n\t\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t},\n\n\t\tfocusCheckLoop: function() {\n\t\t\tif (!_{$boxid}.focused()) {\n\t\t\t\t_{$boxid}.destroyBox();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tsetTimeout(function() {\n\t\t\t\t_{$boxid}.focusCheckLoop();\n\t\t\t}, 100);\n\t\t},\n\n\t\tinit: function() {\n\t\t\t\$('#{$wboxid}').on('keyup', function(e) {\n\t    \t\tswitch(e.which) {\n\t\t\t\t\tcase 13:\n\t\t\t\t\t\t_{$boxid}.submit(-1);\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\tbreak;\n\n\t\t\t        case 38:\n\t\t\t\t\t\t_{$boxid}.evlock = true;\n\t\t\t\t\t\t_{$boxid}.handleUpdate(1);\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t_{$boxid}.evlock = false;\n\t\t\t        \tbreak;\n\n\t\t\t        case 40:\n\t\t\t\t\t\t_{$boxid}.evlock = true;\n\t\t\t\t\t\t_{$boxid}.handleUpdate(2);\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t_{$boxid}.evlock = false;\n\t\t\t        \tbreak;\n\n\t\t\t        default:\n\t\t\t\t\t\t_{$boxid}.handleUpdate();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\n\n\t\t\t\$('#{$wboxid}').on('focusin', function() {\n\t\t\t\t_{$boxid}.focusCheckLoop();\n\t\t\t\t_{$boxid}.handleUpdate();\n\t\t\t});\n\n\t\t\t\$(window).on('scroll', function() {\n\t\t\t\t_{$boxid}.destroyBox();\n\t\t\t})\n\t\t},\n\n\t\thandleUpdate: function(x) {\n\t\t\tvar q = \$('#{$wboxid}').val();\n\n\t\t\tif (x === 1 || x === 2) {\n\t\t\t\t_{$boxid}.original = q;\n\t\t\t\t_{$boxid}.doreset = true;\n\t\t\t\t\$('#{$wboxid}').val(q);\n\t\t\t}\n\t\t\tif (x === 1) {\n\t\t\t\t_{$boxid}.handleUp();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (x === 2) {\n\t\t\t\t_{$boxid}.handleDown();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_{$boxid}.doreset) {\n\t\t\t\t\$('#{$wboxid}').val(_{$boxid}.original);\n\t\t\t}\n\n\t\t\tif (q == '') {\n\t\t\t\tsrc = false;\n\t\t\t\t_{$boxid}.destroyBox();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\$.post('/api/wads.php', {\n\t\t\t\t'fn':\t'search',\n\t\t\t\t'q':\tq\n\t\t\t})\n\t\t\t.done(function(d) {\n\t\t\t\t_{$boxid}.displayBox(d);\n\t\t\t})\n\t\t\t.fail(function(d) {\n\t\t\t\t_{$boxid}.reset();\n\t\t\t});\n\t\t},\n\n\t\tdisplayBox: function(results) {\n\t\t\t_{$boxid}.destroyBox();\n\n\t\t\tif (results.length == 0) {\n\t\t\t\t_{$boxid}.reset();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t_{$boxid}.src = true;\n\t\t\t_{$boxid}.results = results.length;\n\n\t\t\t\$('#g{$boxid}').append('<div id=\\'dbx{$boxid}\\' class=\\'wadbox\\'></div>');\n\t\t\tvar dbx = \$('#dbx{$boxid}');\n\n\t\t\tdbx.css({\n\t\t\t\t'width':\t\$('#{$wboxid}').width(),\n\t\t\t\t'height':\t'250px',\n\t\t\t\t'position':\t'absolute',\n\t\t\t\t'top':\t\t\$('#{$wboxid}').offset().top - 37,\n\t\t\t\t'left':\t\t\$('#{$wboxid}').offset().left\n\t\t\t});\n\n\t\t\tfor (var i = 0; i < results.length; i++) {\n\t\t\t\tvar extras = '';\n\t\t\t\tvar id = 'dbx-c' + i;\n\n\t\t\t\tdbx.append('<a href=\\'javascript:_{$boxid}.submit(' + results[i].id + ');\\' id=\\'' + id + '\\' ' + extras + '>' + results[i].html + '</a>');\n\t\t\t}\n\n\t\t\t_{$boxid}.res = results;\n\n\t\t\t_{$boxid}.selectItem(0);\n\t\t},\n\n\t\treset: function() {\n\t\t\t_{$boxid}.src = false;\n\t\t\t_{$boxid}.selected = 0;\n\t\t\t_{$boxid}.results = 0;\n\t\t},\n\n\t\tdestroyBox: function() {\n\t\t\t\$('#dbx{$boxid}').remove();\n\t\t},\n\n\t\tselectItem: function(index) {\n\t\t\tif (_{$boxid}.selected != -1) {\n\t\t\t\t\$('#dbx-c' + _{$boxid}.selected).attr('class', '');\n\t\t\t}\n\n\t\t\t\$('#dbx-c' + index).attr('class', 'selected');\n\t\t\t_{$boxid}.selected = index;\n\t\t},\n\n\t\thandleDown: function() {\n\t\t\tconsole.log('Handling down');\n\t\t\tif (!_{$boxid}.src) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_{$boxid}.selected == _{$boxid}.results - 1) {\n\t\t\t\t_{$boxid}.selectItem(0);\n\t\t\t} else {\n\t\t\t\t_{$boxid}.selectItem(_{$boxid}.selected + 1);\n\t\t\t}\n\t\t},\n\n\t\thandleUp: function() {\n\t\t\tconsole.log('Handling up');\n\t\t\tif (!_{$boxid}.src) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_{$boxid}.selected == 0) {\n\t\t\t\t_{$boxid}.selectItem(_{$boxid}.results - 1);\n\t\t\t} else {\n\t\t\t\t_{$boxid}.selectItem(_{$boxid}.selected - 1);\n\t\t\t}\n\t\t},\n\n\t\tsubmit: function(x) {\n\t\t\t\$('#{$wboxid}').val('');\n\n\t\t\tif (x > 0) {\n\t\t\t\t_{$boxid}.selectItem(x);\n\t\t\t}\n\n\t\t\tvar found = false;\n\t\t\tvar i = 0;\n\t\t\tvar sel;\n\t\t\twhile (!found && i < _{$boxid}.res.length) {\n\t\t\t\tif (_{$boxid}.res[i].id == _{$boxid}.selected) {\n\t\t\t\t\tfound = false;\n\t\t\t\t\tsel = _{$boxid}.res[i];\n\t\t\t\t}\n\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t{$jsOnCall}({\n\t\t\t\tid:\t\t\tsel.id,\n\t\t\t\tfilename:\tsel.plain\n\t\t\t});\n\t\t\t_{$boxid}.destroyBox();\n\t\t}\n\t};\n\n\t\$(window).on('load', function() {\n\t\t_{$boxid}.init();\n\t});\n</script>\n", array('flaggedComments' => false));
     echo "</div>";
 }
Example #12
0
 /**
  * This method minimies js code to the minimum.
  *
  * @param string js code before minimizing as string
  * @return string minified js code as string
  */
 public static function minifyJs($js)
 {
     $lib = BASEDIR . "../sources/minifier/Minifier.php";
     if (!file_exists($lib)) {
         throw new Exception("Minifier library could not be loaded (" . $lib . ").");
     }
     require_once $lib;
     return \JShrink\Minifier::minify($js);
 }
 /**
  * Przetwórz zawartość złączonych plików
  * 
  * @param string $content
  * 
  * @return string
  */
 protected function processFiles(&$content)
 {
     try {
         $minify = Minifier::minify($content);
     } catch (\Exception $e) {
         $this->setException($e);
         $minify = $content;
     }
     return $minify;
 }
 /**
  * @var string $sContent
  * @return string
  * @throws \LogicException
  * @throws \InvalidArgumentException
  */
 protected function minifyJsContent($sContent)
 {
     if (!is_string($sContent)) {
         throw new \InvalidArgumentException('Argument "$sContent" expects a string, "' . (is_object($sContent) ? get_class($sContent) : gettype($sContent)) . '" given');
     }
     if (!class_exists('JShrink\\Minifier')) {
         throw new \LogicException('"JShrink\\Minifier" class does not exist');
     }
     return \JShrink\Minifier::minify($sContent);
 }
Example #15
0
 /**
  * New resource file update handler.
  *
  * @param string $resource  Resource full path
  * @param string $extension Resource extension
  * @param string $content   Compiled output resource content
  */
 public function renderer($resource, &$extension, &$content)
 {
     // If CSS resource has been updated
     if ($extension === 'css') {
         // Read updated CSS resource file and compile it
         $content = \CssMin::minify($content);
     } elseif ($extension === 'js') {
         $content = \JShrink\Minifier::minify($content);
     }
 }
Example #16
0
function GenerateScript()
{
    global $JS_FILES, $JS_OUT;
    if (!OutOfDate($JS_FILES, $JS_OUT)) {
        return;
    }
    $js = MergeContents($JS_FILES);
    $js = \JShrink\Minifier::Minify($js);
    file_put_contents($JS_OUT, $js);
}
Example #17
0
function print_minified($data)
{
    $name = $data['name'];
    $minified = $_GET['minified'];
    //$data['minified'];
    $code = $data['component_code'];
    if ($minified) {
        // Basic (default) usage.
        $code = \JShrink\Minifier::minify($code);
    }
    return $code;
}
Example #18
0
 /**
  * Generate a JS lang file from all language files.
  *
  * @param string $target The target directory.
  * @param array $options Array of options.
  * @return int
  */
 public function generate($target, $options)
 {
     $messages = $this->getMessages();
     $this->prepareTarget($target);
     $template = $this->file->get(__DIR__ . '/Templates/langjs_with_messages.js');
     $langjs = $this->file->get(__DIR__ . '/../Lang.js/dist/lang.min.js');
     $template = str_replace('\'{ messages }\'', json_encode($messages), $template);
     $template = str_replace('\'{ langjs }\';', $langjs, $template);
     if ($options['compress']) {
         $template = Minifier::minify($template);
     }
     return $this->file->put($target, $template);
 }
 /**
  * Modify the file content - compress Foundation scripts with YUI or JShrink
  * @param string
  * @param string
  * @param string
  * @param array
  * @return string
  */
 public function run($content, $strKey, $strMode, $arrFile)
 {
     if (in_array($arrFile['name'], $GLOBALS['FOUNDATION_JS']) && !\Config::get('debugMode')) {
         try {
             //Try YUI
             $yui = new \YUI\Compressor();
             $yui->setType(\YUI\Compressor::TYPE_JS);
             $content = $yui->compress($content);
         } catch (\Exception $e) {
             //Fall back to JShrink if Java not available
             $content = \JShrink\Minifier::minify($content);
         }
     }
     return $content;
 }
 /**
  * {@inheritdoc}
  */
 public function minify($content, $options)
 {
     if ($this->cacheDir) {
         if (!file_exists($this->cacheDir)) {
             mkdir($this->cacheDir, 0777, true);
         }
         $hash = md5($content);
         $file = implode(DIRECTORY_SEPARATOR, array($this->cacheDir, $hash));
         if (!file_exists($file)) {
             file_put_contents($file, \JShrink\Minifier::minify($content, $options));
         }
         return file_get_contents($file);
     } else {
         return \JShrink\Minifier::minify($content, $options);
     }
 }
Example #21
0
 /**
  * Compress/Minification
  *
  * @param string $sContents
  *
  * @return bool|mixed|string
  * @throws Exception
  */
 public function Compress($sContents)
 {
     if (strpos($sContents, $this->sMarker)) {
         $sContents = preg_replace_callback('|\\/\\*\\[' . preg_quote($this->sMarker) . '\\s(?P<file>[\\w\\-\\.\\/]+)\\sbegin\\]\\*\\/(?P<content>.+)\\/\\*\\[' . preg_quote($this->sMarker) . '\\send\\]\\*\\/\\s*|sU', function ($aMatches) {
             if (substr($aMatches['file'], -7) != '.min.js') {
                 $sResult = \JShrink\Minifier::minify($aMatches['content']);
             } else {
                 $sResult = $aMatches['content'];
             }
             return $sResult;
         }, $sContents);
     } else {
         $sContents = \JShrink\Minifier::minify($sContents);
     }
     return $sContents;
 }
Example #22
0
function minify_dir($dir) {
    foreach ($dir as $file) {
        if (preg_match('/([^\/].*)\/(.*)\.js$/', $file, $matches)) {
            if (strstr($file, '.min.js')) {
                continue;
            }
            $filename = $matches[2];
            $directory = $matches[1];
            try {
                echo "minifying $directory/$filename.js...\n";
                file_put_contents("$directory/$filename.min.js", \JShrink\Minifier::minify(file_get_contents($file)));
            } catch (\Exception $e) {
                echo $file . " could not be minified, please check its syntax\n";
            }
        }
    }
}
Example #23
0
 public function getContent()
 {
     $data = parent::getContent();
     //Return the raw content if minification has been disabled
     if (!ValueAs::bool($this->getOption('minify', true))) {
         return $data;
     }
     //Do not minify scripts containing the @do-not-minify
     if (strpos($data, '@' . 'do-not-minify') !== false) {
         return $data;
     }
     try {
         return Minifier::minify($data);
     } catch (\Exception $e) {
         return $data;
     }
 }
Example #24
0
 public function minify()
 {
     ///TODO: handle errors... at all.
     /// Compile less files
     Module::Requires("extern.JShrink");
     Module::Requires("extern.lessphp");
     $buffer = file_get_contents($this->path);
     switch ($this->getExtension()) {
         case "less":
             $less = new lessc();
             $less->setFormatter("compressed");
             $buffer = $less->compile($buffer);
             break;
         case "js":
             $buffer = \JShrink\Minifier::minify($buffer, array('flaggedComments' => false));
             break;
     }
     return $buffer;
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function run(OutputInterface $output)
 {
     $destination = $this->getParameter('dest');
     /** @var SplFileInfo[] $files */
     $files = $this->getFiles($this->getParameter('src'));
     $code = '';
     foreach ($files as $file) {
         $code .= rtrim($file->getContents());
         if (substr($code, -1) !== ';') {
             $code .= ';';
         }
     }
     if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) {
         $output->writeln("Writing to " . $destination);
     }
     $fs = new Filesystem();
     $fs->mkdir(dirname($destination));
     $fs->dumpFile($destination, Minifier::minify($code, ['flaggedComments' => false]));
 }
Example #26
0
 /**
  *
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $path = $this->getContainer()->getParameter('kernel.root_dir') . '/' . $input->getArgument('path') . "";
     if (!is_dir($path)) {
         $io->error(sprintf('The given document directory "%s" does not exist', $path));
         return 1;
     }
     $io->success(sprintf('Found sources here here: %s', $path));
     $io->comment('Quit the process with CONTROL-C.');
     $files = scandir($path);
     foreach ($files as $file) {
         if (substr($file, -3) == ".js") {
             $jsoutput = \JShrink\Minifier::minify(file_get_contents($path . '/' . $file), array('flaggedComments' => false));
             file_put_contents($path . '/' . $file, $jsoutput);
             $io->success(sprintf('Shrunk: ' . $path . '/' . $file));
         }
     }
     $io->success(sprintf('Success!'));
 }
Example #27
0
 function print_js($data)
 {
     //minimify js files
     require_once APPPATH . 'front/compilers/' . $data . '_js.php';
     if (ENVIRONMENT != 'development') {
         if (!file_exists(APPPATH . 'front/cache/' . $data . '_combined.js')) {
             require_once SYSDIR . '/third_party/minifier.php';
             $js = "";
             foreach ($files as $file) {
                 //$js .= \JShrink\Minifier::minify(file_get_contents($file));
                 $js .= file_get_contents($file);
             }
             $js = \JShrink\Minifier::minify($js);
             file_put_contents(APPPATH . 'front/cache/' . $data . '_combined.js', $js);
         }
         echo '<script src="/' . APPPATH . 'front/cache/' . $data . '_combined.js" type="text/javascript"></script>';
     } else {
         foreach ($files as $file) {
             echo '<script src="/' . $file . '" type="text/javascript"></script>';
         }
     }
 }
Example #28
0
function CompileScripts($compile = true)
{
    global $RootPath;
    $ResourceBundles = GetResourceBundles();
    $FilePaths = array();
    $lesstext = "";
    foreach ($ResourceBundles as $bundle) {
        $lesstext .= $bundle->CompileScripts();
    }
    if ($compile) {
        try {
            $jstext = \JShrink\Minifier::minify($lesstext, array('flaggedComments' => false));
            echo "/* compiled with JShrink v0.5.2 - BSD 3-clause - https://github.com/tedivm/JShrink */\n";
            echo "/* for human-readable source of this file, append ?compile=false to the file name */\n";
            echo $jstext;
        } catch (\Exception $e) {
            echo "/* " . $e->getMessage() . " */\n";
        }
    } else {
        echo $lesstext;
    }
}
Example #29
0
 /**
  * Filters the content using JSMIN
  *
  * @param string $content
  * @return null|string
  * @throws Exception
  */
 public function filter($content)
 {
     if (is_string($content) === false) {
         throw new Exception('Script must be a string');
     }
     if (empty($content) === true) {
         return '';
     }
     try {
         return PHP_EOL . Minifier::minify($content);
     } catch (\Exception $e) {
         $msg = $e->getMessage();
         if (strpos($msg, 'Unclosed multiline comment at position') === 0) {
             throw new Exception('Unterminated comment.');
         } elseif (strpos($msg, 'Unclosed string at position') === 0) {
             throw new Exception('Unterminated string literal.');
         } elseif (strpos($msg, 'Unclosed regex pattern at position') === 0) {
             throw new Exception('Unterminated Regular Expression literal.');
         } else {
             throw new Exception($e->getMessage());
         }
     }
 }
Example #30
0
 public function minify($format, $content, $compression_option = "remote")
 {
     if ($format == "js") {
         if ($compression_option == "remote") {
             return $this->getMinified($this->urlJS, $content);
             // remote compression
         } else {
             require "vendor/JShrink/Minifier.php";
             return \JShrink\Minifier::minify($content);
             // local compression
         }
     }
     if ($format == "css") {
         if ($compression_option == "remote") {
             return $this->getMinified($this->urlCSS, $content);
             // remote compression
         } else {
             require "vendor/cssmin/cssmin-v3.0.1-minified.php";
             return CssMin::minify($content);
             // local compression
         }
     }
 }