Esempio n. 1
0
 /**
  * Function that will merge & minify the provided files
  *
  * @param   array   $files      - array with relative paths to js files
  * @param   string  $cachePath  - where to save the new merged & minified file
  *
  * @return string
  */
 public static function shrink(array $files, $cachePath)
 {
     $times = array();
     $md5 = md5(json_encode($files));
     $url = $cachePath . '/' . $md5 . '.min.js';
     $minFile = JPATH_ROOT . '/' . $url;
     // Lets read the times of the files we need to merge
     foreach ($files as $file) {
         if (file_exists(JPATH_ROOT . '/' . $file)) {
             $times[] = filemtime(JPATH_ROOT . '/' . $file);
         }
     }
     // If the minFile doesn't exist or the minFile time is older than any of the times, let's do our job!
     if (!file_exists($minFile) || max($times) > filemtime($minFile)) {
         $js = '';
         foreach ($files as $file) {
             if (file_exists(JPATH_ROOT . '/' . $file)) {
                 $js[] = file_get_contents(JPATH_ROOT . '/' . $file);
             }
         }
         // Do the actual minifying
         $minJs = CompojoomMinifier::minify(implode($js));
         JFile::write($minFile, $minJs);
     }
     return $url;
 }
Esempio n. 2
0
 /**
  * Takes a string containing javascript and removes unneeded characters in
  * order to shrink the code without altering it's functionality.
  *
  * @param   string  $js       The raw javascript to be minified
  * @param   array   $options  Various runtime options in an associative array
  *
  * @throws \Exception
  * @return bool|string
  */
 public static function minify($js, $options = array())
 {
     try {
         ob_start();
         $jshrink = new CompojoomMinifier();
         $js = $jshrink->lock($js);
         $jshrink->minifyDirectToOutput($js, $options);
         // Sometimes there's a leading new line, so we trim that out here.
         $js = ltrim(ob_get_clean());
         $js = $jshrink->unlock($js);
         unset($jshrink);
         return $js;
     } catch (\Exception $e) {
         if (isset($jshrink)) {
             // Since the breakdownScript function probably wasn't finished
             // we clean it out before discarding it.
             $jshrink->clean();
             unset($jshrink);
         }
         // Without this call things get weird, with partially outputted js.
         ob_end_clean();
         throw $e;
     }
 }