You are here

function minifyjs_js_alter in Minify JS 8

Same name and namespace in other branches
  1. 8.2 minifyjs.module \minifyjs_js_alter()
  2. 7 minifyjs.module \minifyjs_js_alter()

Implements hook_js_alter().

Parameters

array $javascript:

AttachedAssetsInterface $assets:

File

./minifyjs.module, line 68

Code

function minifyjs_js_alter(&$scripts, $assets) {

  // Determine if the replacement needs to be performed.
  $do_replace = FALSE;
  if (\Drupal::config('minifyjs.config')
    ->get('use_minified')) {
    if (\Drupal::config('minifyjs.config')
      ->get('disable_admin')) {
      if (!\Drupal::service('router.admin_context')
        ->isAdminRoute()) {
        $do_replace = TRUE;
      }
    }
    else {
      $do_replace = TRUE;
    }
  }
  if ($do_replace) {

    // Files array is keyed by file id. To make this operation as fast as
    // possible, the array should be keyed by file uri. Also, shorten the
    // array by removing files that are not minified.
    $files = minifyjs_load_all_files();
    $minified_files = [];
    foreach ($files as $file) {
      if (!empty($file->minified_uri)) {
        $minified_files[$file->uri] = $file;
      }
    }

    // Update the scripts array with new file info.
    foreach ($scripts as $path => $file) {
      if (isset($minified_files[$path])) {
        $scripts[$path]['data'] = $minified_files[$path]->minified_uri;
        minifyjs_update_scripts($scripts, $path, $minified_files[$path]->minified_uri);
      }
    }
  }
}