JsCollectionGrouper.php 2.6 KB

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