You are here

public static function SeedsManager::sortTabs in Seeds Toolbar 8

Sort main toolbar links.

File

src/SeedsManager.php, line 129

Class

SeedsManager
Helper function for SeedsToolbar.

Namespace

Drupal\seeds_toolbar

Code

public static function sortTabs(array $items, array $first_tabs) {
  $additonal_items = [];
  foreach ($items as $id => &$item) {
    if (in_array($id, $first_tabs)) {

      // Always put the defined tabs first.
      $item['#weight'] = array_search($id, $first_tabs);
    }
    elseif ($id == 'admin_toolbar_tools') {

      // Always put admin_toolbar_tools at the last tab.
      $item['#weight'] = 1000;
    }
    else {

      // Add additonal toolbar items which are added using hook_toolbar
      // Add a temp id to use it later.
      $item['temp_id'] = $id;

      // If the item doesn't have weight, assume it is 0.
      if (!isset($item['#weight'])) {
        $item['#weight'] = 0;
      }
      $additonal_items[] = $item;
      unset($items[$id]);
    }
  }

  // Sort the additional items by weight, then normalize them to be positive numbers.
  usort($additonal_items, function ($a, $b) {
    if ($a['#weight'] == $b['#weight']) {
      return 0;
    }
    return (int) $a['#weight'] > (int) $b['#weight'] ? 1 : -1;
  });

  // Add them to the items array.
  foreach ($additonal_items as $sorted_id => $additonal_item) {
    $additonal_item['#weight'] = min(count($first_tabs) + $sorted_id, 999);
    $id = $additonal_item['temp_id'];
    unset($additonal_item['temp_id']);
    $items[$id] = $additonal_item;
  }
  return $items;
}