seeds_toolbar-8.x-1.11/src/SeedsManager.php

src/SeedsManager.php
<?php

namespace Drupal\seeds_toolbar;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;

/**
 * Helper function for SeedsToolbar.
 */
class SeedsManager {

  /**
   * Language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Current user.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Indicates if the "block_content_permissions" module exists.
   *
   * @var bool
   */
  protected $blockContentPermissionsModule;

  /**
   * Module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Constructs a new SeedsManager object.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Session\AccountProxy $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(
    LanguageManagerInterface $language_manager,
    AccountProxy $current_user,
    EntityTypeManagerInterface $entity_type_manager,
    ModuleHandlerInterface $module_handler,
    ConfigFactoryInterface $config_factory
  ) {
    $this->languageManager = $language_manager;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->moduleHandler = $module_handler;
    $this->blockContentPermissionsModule = $module_handler->moduleExists('block_content_permissions');
    $this->configFactory = $config_factory;
  }

  /**
   * Tries to get the relevant url of an entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
   * @return \Drupal\Core\Url|null
   *   The useful url of the entity, NULL if no url fonud.
   */
  protected function getUsefulLink(EntityInterface $entity) {
    $url = NULL;
    if ($entity->hasLinkTemplate('overview-form')) {
      $url = $entity->toUrl('overview-form');
    }
    elseif ($entity->hasLinkTemplate('edit-form')) {
      $url = $entity->toUrl('edit-form');
    }

    if ($url && $url->access()) {
      $url->setOption('attributes', [
        'class' => ['useful-link'],
      ]);
      $style = $this->configFactory->get('seeds_toolbar.settings')->get('style') ?? 'dark';
      $icon = '/' . $this->moduleHandler->getModule('seeds_toolbar')->getPath() . "/assets/icons/$style/seeds-add-config.svg";
      return Link::fromTextAndUrl(Markup::create("<img src=\"$icon\"/>"), $url)->toRenderable();
    }

    return NULL;
  }

  /**
   * Build "Add" menu item.
   */
  public function buildMenu($entity_type, $route) {
    // Seeds toolbar should not depend on any entity type,
    // we check if the entity type exists or not.
    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], [
        'attributes' => [
          'data-search-tags' => [
            strtolower($entity->label()), str_replace([' '], '', strtolower($entity->label())), $entity->id(),
          ],
        ],
      ]);
      // Block content are a special case, so we want to handle it.
      if ($entity_type == 'block_content_type') {
        $access = $this->handleBlockPermission($entity);
      }
      else {
        $access = $this->userHasAccess($url);
      }

      // Add settings url.
      $useful_link = $this->getUsefulLink($entity);

      if ($access) {
        $items[$id] = [
          'link' => Link::fromTextAndUrl($entity->label(), $url)->toRenderable(),
          'useful_link' => $useful_link,
        ];
      }
    }
    if (empty($items)) {
      return [];
    }
    else {
      return [
        '#menu_name' => $entity_type . '-add-menu',
        '#items' => $items,
        '#theme' => 'seeds_add_menu',
      ];
    }
  }

  /**
   * Check if the user has access to internal link.
   */
  private function userHasAccess($url) {
    return $url->access($this->currentUser);
  }

  /**
   * Check if block_content_permission enabled.
   */
  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");
    }
  }

  /**
   * Get current language direction.
   */
  public function getDirection() {
    $dir = $this->languageManager->getCurrentLanguage()->getDirection();
    return ($dir == 'ltr') ? 'left' : 'right';
  }

  /**
   * Sort main toolbar links.
   */
  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;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc