You are here

function advagg_js_compress_jsminplus in Advanced CSS/JS Aggregation 6

Same name and namespace in other branches
  1. 7.2 advagg_js_compress/advagg_js_compress.advagg.inc \advagg_js_compress_jsminplus()
  2. 7 advagg_js_compress/advagg_js_compress.module \advagg_js_compress_jsminplus()

Compress a JS string using jsmin+

Parameters

$contents: Javascript string.

Return value

array with the size before and after.

3 calls to advagg_js_compress_jsminplus()
advagg_js_compress_advagg_js_inline_alter in advagg_js_compress/advagg_js_compress.module
Implement hook_advagg_js_inline_alter.
advagg_js_compress_prep in advagg_js_compress/advagg_js_compress.module
Compress a JS string
advagg_js_compress_test_file in advagg_js_compress/advagg_js_compress.module
Run various theme functions so the cache is primed.

File

advagg_js_compress/advagg_js_compress.module, line 297
Advanced CSS/JS aggregation js compression module.

Code

function advagg_js_compress_jsminplus(&$contents) {

  // Try to allocate enough time to run JSMin+.
  if (function_exists('set_time_limit')) {
    @set_time_limit(variable_get('advagg_set_time_limit', ADVAGG_SET_TIME_LIMIT));
  }

  // Only include jsminplus.inc if the JSMinPlus class doesn't exist.
  if (!class_exists('JSMinPlus')) {
    include drupal_get_path('module', 'advagg_js_compress') . '/jsminplus.inc';
  }

  // Get the JS string length before the compression operation.
  $before = strlen($contents);
  $original_contents = $contents;
  try {

    // Strip Byte Order Marks (BOM's) from the file, JSMin+ cannot parse these.
    $contents = str_replace(pack("CCC", 0xef, 0xbb, 0xbf), "", $contents);
    ob_start();

    // JSMin+ the contents of the aggregated file.
    $contents = JSMinPlus::minify($contents);
    $error = trim(ob_get_contents());
    if (!empty($error)) {
      throw new Exception($error);
    }

    // Ensure that $contents ends with ; or }.
    if (strpbrk(substr(trim($contents), -1), ';}') === FALSE) {

      // ; or } not found, add in ; to the end of $contents.
      $contents = trim($contents) . ';';
    }

    // Get the JS string length after the compression operation.
    $after = strlen($contents);
  } catch (Exception $e) {

    // Log the exception thrown by JSMin+ and roll back to uncompressed content.
    watchdog('advagg', $e
      ->getMessage() . '<pre>' . $original_contents . '</pre>', NULL, WATCHDOG_WARNING);
    $contents = $original_contents;
    $after = $before;
  }
  ob_end_clean();
  return array(
    $before,
    $after,
  );
}