3 namespace Drupal\Core\Asset;
6 * Groups JavaScript assets.
8 class JsCollectionGrouper implements AssetCollectionGrouperInterface {
13 * Puts multiple items into the same group if they are groupable and if they
14 * are for the same browsers. Items of the 'file' type are groupable if their
15 * 'preprocess' flag is TRUE. Items of the 'external' type are not groupable.
17 * Also ensures that the process of grouping items does not change their
18 * relative order. This requirement may result in multiple groups for the same
19 * type and browsers, if needed to accommodate other items in between.
21 public function group(array $js_assets) {
23 // If a group can contain multiple items, we track the information that must
24 // be the same for each item in the group, so that when we iterate the next
25 // item, we can determine if it can be put into the current group, or if a
26 // new group needs to be made for it.
27 $current_group_keys = NULL;
29 foreach ($js_assets as $item) {
30 // The browsers for which the JavaScript item needs to be loaded is part
31 // of the information that determines when a new group is needed, but the
32 // order of keys in the array doesn't matter, and we don't want a new
33 // group if all that's different is that order.
34 ksort($item['browsers']);
36 switch ($item['type']) {
38 // Group file items if their 'preprocess' flag is TRUE.
39 // Help ensure maximum reuse of aggregate files by only grouping
40 // together items that share the same 'group' value.
41 $group_keys = $item['preprocess'] ? [$item['type'], $item['group'], $item['browsers']] : FALSE;
45 // Do not group external items.
50 // If the group keys don't match the most recent group we're working with,
51 // then a new group must be made.
52 if ($group_keys !== $current_group_keys) {
54 // Initialize the new group with the same properties as the first item
55 // being placed into it. The item's 'data' and 'weight' properties are
56 // unique to the item and should not be carried over to the group.
57 $groups[$index] = $item;
58 unset($groups[$index]['data'], $groups[$index]['weight']);
59 $groups[$index]['items'] = [];
60 $current_group_keys = $group_keys ? $group_keys : NULL;
63 // Add the item to the current group.
64 $groups[$index]['items'][] = $item;