You are here

function advagg_bundler_advagg_build_aggregate_plans_alter in Advanced CSS/JS Aggregation 7.2

Implements hook_advagg_build_aggregate_plans_alter().

Related topics

File

advagg_bundler/advagg_bundler.advagg.inc, line 16
Advanced aggregation bundler module.

Code

function advagg_bundler_advagg_build_aggregate_plans_alter(&$files, &$modified, $type) {

  // Get max number of sub aggregates to create.
  if ($type === 'css') {
    $max = variable_get('advagg_bundler_max_css', ADVAGG_BUNDLER_MAX_CSS);
  }
  if ($type === 'js') {
    $max = variable_get('advagg_bundler_max_js', ADVAGG_BUNDLER_MAX_JS);
  }

  // If bundles are disabled then do not do any more processing.
  if (empty($max)) {
    return;
  }

  // If bundler is disabled then do not do any more processing.
  if (!advagg_bundler_enabled()) {
    return;
  }
  $final_groupings = array();
  $total_count = 0;
  foreach ($files as $data) {

    // Preserve the order while grouping.
    $last_group = '';
    $counter = 0;
    $groupings = array();
    foreach ($data['files'] as $fileinfo) {

      // Assign each file to their group.
      $group = advagg_bundler_analysis($fileinfo['data']);
      $fileinfo['bundler'] = $group;
      if (!empty($group['group_hash'])) {

        // Set $last_group if this is the first run of this foreach loop.
        if (empty($last_group)) {
          $last_group = $group['group_hash'];
        }
        if ($last_group != $group['group_hash']) {

          // Bump Counter if group has changed from the last one.
          ++$counter;
          $last_group = $group['group_hash'];
          $modified = TRUE;
        }
      }
      $groupings[$counter][] = $fileinfo;
    }

    // Make sure we didn't go over the max; if we did merge the smallest bundles
    // together.
    advagg_bundler_merge($groupings, $max);
    $total_count += count($groupings);

    // Add to the final groupings array.
    $final_groupings[] = $groupings;
  }

  // Try to shrink bundles if they are still too big.
  while ($total_count > $max) {
    $remerge_candidate = NULL;
    $remerge_key = NULL;
    $total_count = 0;
    foreach ($final_groupings as $key => $groupings) {
      if (count($groupings) > 1) {
        if (is_null($remerge_candidate)) {
          $remerge_candidate = $groupings;
          $remerge_key = $key;
        }
        elseif (count($remerge_candidate) > count($groupings)) {
          $remerge_candidate = $groupings;
          $remerge_key = $key;
        }
      }
    }
    if (is_null($remerge_candidate)) {
      break;
    }
    advagg_bundler_merge($remerge_candidate, count($remerge_candidate) - 1);
    $final_groupings[$remerge_key] = $remerge_candidate;
    $total_count = 0;
    foreach ($final_groupings as $key => $groupings) {
      $total_count += count($groupings);
    }
  }

  // Replace $files array with new aggregate filenames.
  $files = advagg_generate_filenames($final_groupings, $type);
}