SeedsManager.php in Seeds Toolbar 8
File
src/SeedsManager.php
View source
<?php
namespace Drupal\seeds_toolbar;
use Drupal\Core\Link;
use Drupal\Core\Url;
class SeedsManager {
protected $languageManager;
protected $currentUser;
protected $entityTypeManager;
protected $blockContentPermissionsModule;
protected $module_handler;
public function __construct($language_manager, $current_user, $entity_type_manager, $module_handler) {
$this->languageManager = $language_manager;
$this->currentUser = $current_user;
$this->entityTypeManager = $entity_type_manager;
$this->module_handler = $module_handler;
$this->blockContentPermissionsModule = $module_handler
->moduleExists('block_content_permissions');
}
public function buildMenu($entity_type, $route) {
if ($this->entityTypeManager
->hasDefinition($entity_type)) {
$entities = $this->entityTypeManager
->getStorage($entity_type)
->loadMultiple();
}
else {
return [];
}
$items = [];
foreach ($entities as $entity) {
$id = $entity
->id();
$url = Url::fromRoute($route, [
$entity_type => $id,
]);
if ($entity_type == 'block_content_type') {
$access = $this
->handleBlockPermission($entity);
}
else {
$access = $this
->userHasAccess($url);
}
if ($access) {
$items[$id] = Link::fromTextAndUrl($entity
->label(), $url);
}
}
if (empty($items)) {
return [];
}
else {
return [
'#menu_name' => $entity_type . '-add-menu',
'#items' => $items,
'#theme' => 'seeds_add_menu',
];
}
}
private function userHasAccess($url) {
return $url
->access($this->currentUser);
}
private function handleBlockPermission($block_type) {
if ($this->blockContentPermissionsModule) {
$type_id = $block_type
->id();
return $this->currentUser
->hasPermission("create {$type_id} block content");
}
else {
return $this->currentUser
->hasPermission("administer blocks");
}
}
public function getDirection() {
$dir = $this->languageManager
->getCurrentLanguage()
->getDirection();
return $dir == 'ltr' ? 'left' : 'right';
}
public static function sortTabs(array $items, array $first_tabs) {
$additonal_items = [];
foreach ($items as $id => &$item) {
if (in_array($id, $first_tabs)) {
$item['#weight'] = array_search($id, $first_tabs);
}
elseif ($id == 'admin_toolbar_tools') {
$item['#weight'] = 1000;
}
else {
$item['temp_id'] = $id;
if (!isset($item['#weight'])) {
$item['#weight'] = 0;
}
$additonal_items[] = $item;
unset($items[$id]);
}
}
usort($additonal_items, function ($a, $b) {
if ($a['#weight'] == $b['#weight']) {
return 0;
}
return (int) $a['#weight'] > (int) $b['#weight'] ? 1 : -1;
});
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;
}
}