You are here

class SiteHeaderBlock in Opigno dashboard 3.x

The site header block.

@Block( id = "opigno_site_header_block", admin_label = @Translation("Opigno Site header block"), category = @Translation("Opigno"), )

@package Drupal\opigno_dashboard\Plugin\Block

Hierarchy

Expanded class hierarchy of SiteHeaderBlock

File

src/Plugin/Block/SiteHeaderBlock.php, line 34

Namespace

Drupal\opigno_dashboard\Plugin\Block
View source
class SiteHeaderBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Entity\EntityInterface|null
   */
  protected $user = NULL;

  /**
   * If the current page is a user page.
   *
   * @var bool
   */
  protected $isUserPage;

  /**
   * The user statistics manager.
   *
   * @var \Drupal\opigno_statistics\Services\UserStatisticsManager
   */
  protected $statsManager;

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;

  /**
   * Notifications manager service.
   *
   * @var \Drupal\opigno_notification\Services\OpignoNotificationManager
   */
  protected $notificationsManager;

  /**
   * The private messages manager service.
   *
   * @var \Drupal\private_message\Service\PrivateMessageServiceInterface
   */
  protected $pmService;

  /**
   * {@inheritdoc}
   */
  public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager, RouteMatchInterface $route_match, UserStatisticsManager $user_stats_manager, MenuLinkTreeInterface $menu_tree, OpignoNotificationManager $notification_manager, PrivateMessageServiceInterface $pm_service, ...$default) {
    parent::__construct(...$default);
    $uid = (int) $account
      ->id();
    $this->isUserPage = $route_match
      ->getRouteName() === 'entity.user.canonical' && (int) $route_match
      ->getRawParameter('user') === $uid;
    $this->statsManager = $user_stats_manager;
    $this->menuTree = $menu_tree;
    $this->notificationsManager = $notification_manager;
    $this->pmService = $pm_service;
    try {
      $this->user = $entity_type_manager
        ->getStorage('user')
        ->load($uid);
    } catch (PluginNotFoundException|InvalidPluginDefinitionException $e) {
      watchdog_exception('opigno_dashboard_exception', $e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($container
      ->get('current_user'), $container
      ->get('entity_type.manager'), $container
      ->get('current_route_match'), $container
      ->get('opigno_statistics.user_stats_manager'), $container
      ->get('menu.link_tree'), $container
      ->get('opigno_notification.manager'), $container
      ->get('private_message.service'), $configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() : array {
    return [
      'label_display' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Don't cache if the user can't be loaded.
    if (!$this->user instanceof UserInterface) {
      return [
        '#cache' => [
          'max-age' => 0,
        ],
      ];
    }

    // Get the logo path and the main menu.
    $role = $this->statsManager
      ->getUserRole();
    $logo = theme_get_setting('logo.url');
    $parameters = $this->menuTree
      ->getCurrentRouteMenuTreeParameters('main');
    $tree = $this->menuTree
      ->load('main', $parameters);
    $manipulators = [
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
    ];
    $menu = $this->menuTree
      ->transform($tree, $manipulators);

    // Notifications.
    try {
      $notifications = $this->notificationsManager
        ->getUserHeaderNotifications();
    } catch (InvalidPluginDefinitionException|PluginNotFoundException $e) {
      watchdog_exception('opigno_dashboard_exception', $e);
      $notifications = [];
    }
    return [
      '#theme' => 'opigno_site_header',
      '#logo' => $logo,
      '#menu' => $this->menuTree
        ->build($menu),
      '#is_anonymous' => $this->user
        ->isAnonymous(),
      '#is_user_page' => $this->isUserPage,
      '#user_name' => $this->user
        ->getDisplayName(),
      '#user_url' => Url::fromRoute('entity.user.canonical', [
        'user' => (int) $this->user
          ->id(),
      ])
        ->toString(),
      '#user_picture' => UserStatisticsManager::getUserPicture($this->user),
      '#notifications_count' => count($notifications),
      '#notifications' => $this->notificationsManager
        ->renderUserHeaderNotifications($notifications),
      '#messages_count' => $this->pmService
        ->getUnreadThreadCount(),
      '#dropdown_menu' => $this
        ->buildUserDropdownMenu($role),
      '#cache' => [
        'contexts' => $this
          ->getCacheContexts(),
        'tags' => $this
          ->getCacheTags(),
      ],
      '#attached' => [
        'library' => [
          'opigno_notification/opigno_notification',
        ],
        'drupalSettings' => [
          'opignoNotifications' => [
            'updateUrl' => Url::fromRoute('opigno_notification.get_messages')
              ->toString(),
          ],
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = Cache::mergeContexts(parent::getCacheContexts(), [
      'url.path.is_current_user_page',
      'url.path',
    ]);
    if ($this->user instanceof UserInterface) {
      $contexts = Cache::mergeContexts($contexts, [
        'user',
      ]);
    }
    return $contexts;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags(), [
      'opigno_notification_list',
      'private_message_list',
    ]);
  }

  /**
   * Prepare the user dropdown menu.
   *
   * @param \Drupal\Core\StringTranslation\TranslatableMarkup $role
   *   The user role.
   *
   * @return array
   *   The array to build the user dropdown menu.
   */
  private function buildUserDropdownMenu(TranslatableMarkup $role) : array {
    if (!$this->user instanceof UserInterface) {
      return [];
    }
    return [
      'name' => Link::createFromRoute($this->user
        ->getDisplayName(), 'entity.user.canonical', [
        'user' => (int) $this->user
          ->id(),
      ]),
      'role' => $role,
      'is_admin' => $this->user
        ->hasPermission('access administration pages'),
      'links' => [
        'help' => [
          'title' => $this
            ->t('Help'),
          'path' => 'https://www.opigno.org/contact',
          'external' => TRUE,
          'icon_class' => 'fi-rr-interrogation',
        ],
        'review' => [
          'title' => $this
            ->t('Review Opigno'),
          'path' => 'https://reviews.capterra.com/new/135113?utm_source=vp&utm_medium=none&utm_term=&utm_content=&utm_campaign=vendor_request',
          'external' => TRUE,
          'icon_class' => 'fi-rr-comment',
        ],
        'logout' => [
          'title' => $this
            ->t('Logout'),
          'path' => Url::fromRoute('user.logout')
            ->toString(),
          'icon_class' => 'fi-rr-sign-out',
        ],
      ],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockForm public function 16
BlockPluginTrait::blockSubmit public function 13
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. Aliased as: traitBuildConfigurationForm
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginTrait::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginTrait::$initializedContextConfig protected property Tracks whether the context has been initialized from configuration.
ContextAwarePluginTrait::getCacheMaxAge public function 7
ContextAwarePluginTrait::getContext public function
ContextAwarePluginTrait::getContextDefinition public function
ContextAwarePluginTrait::getContextDefinitions public function
ContextAwarePluginTrait::getContextMapping public function
ContextAwarePluginTrait::getContexts public function
ContextAwarePluginTrait::getContextValue public function
ContextAwarePluginTrait::getContextValues public function
ContextAwarePluginTrait::getPluginDefinition abstract protected function 1
ContextAwarePluginTrait::setContext public function 1
ContextAwarePluginTrait::setContextMapping public function
ContextAwarePluginTrait::setContextValue public function
ContextAwarePluginTrait::validateContexts public function
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass().
PluginWithFormsTrait::hasFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass().
SiteHeaderBlock::$isUserPage protected property If the current page is a user page.
SiteHeaderBlock::$menuTree protected property The menu link tree service.
SiteHeaderBlock::$notificationsManager protected property Notifications manager service.
SiteHeaderBlock::$pmService protected property The private messages manager service.
SiteHeaderBlock::$statsManager protected property The user statistics manager.
SiteHeaderBlock::$user protected property The current user.
SiteHeaderBlock::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build 1
SiteHeaderBlock::buildUserDropdownMenu private function Prepare the user dropdown menu.
SiteHeaderBlock::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
SiteHeaderBlock::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
SiteHeaderBlock::getCacheContexts public function Overrides ContextAwarePluginTrait::getCacheContexts
SiteHeaderBlock::getCacheTags public function Overrides ContextAwarePluginTrait::getCacheTags
SiteHeaderBlock::__construct public function Overrides BlockPluginTrait::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.