You are here

public static function AssetOptimizer::sortStable in Advanced CSS/JS Aggregation 8.3

Same name and namespace in other branches
  1. 8.4 src/Asset/AssetOptimizer.php \Drupal\advagg\Asset\AssetOptimizer::sortStable()

Stable sort for CSS and JS items.

Preserves the order of items with equal sort criteria.

The function will sort by:

  • $item['group'], integer, ascending
  • $item['weight'], integer, ascending

Parameters

array &$assets: Array of JS or CSS items, as in hook_alter_js() and hook_alter_css(). The array keys can be integers or strings. The items are arrays.

See also

hook_alter_js()

hook_alter_css()

1 call to AssetOptimizer::sortStable()
advagg_mod_sort_css_js in advagg_mod/advagg_mod.module
Rearrange CSS/JS so that aggregates are better grouped.

File

src/Asset/AssetOptimizer.php, line 417

Class

AssetOptimizer
Defines the base AdvAgg optimizer.

Namespace

Drupal\advagg\Asset

Code

public static function sortStable(array &$assets) {
  $nested = [];
  foreach ($assets as $key => $item) {

    // Weight cast to string to preserve float.
    $weight = (string) $item['weight'];
    $nested[$item['group']][$weight][$key] = $item;
  }

  // First order by group, so that, for example, all items in the CSS_SYSTEM
  // group appear before items in the CSS_DEFAULT group, which appear before
  // all items in the CSS_THEME group. Modules may create additional groups by
  // defining their own constants.
  $sorted = [];

  // Sort group; then iterate over it.
  ksort($nested);
  foreach ($nested as &$group_items) {

    // Order by weight and iterate over it.
    ksort($group_items);
    foreach ($group_items as &$weight_items) {
      foreach ($weight_items as $key => &$item) {
        $sorted[$key] = $item;
      }
      unset($item);
    }
    unset($weight_items);
  }
  unset($group_items);
  $assets = $sorted;
}