You are here

user_menu_avatar.module in User Menu Avatar (User Image in Menu) 8.2

Display user_picture and/or username in menu.

File

user_menu_avatar.module
View source
<?php

/**
 * @file
 * Display user_picture and/or username in menu.
 */
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\Entity\User;
use Drupal\field\Entity\FieldConfig;

/**
 * Implements hook_link_alter().
 *
 * @inheritdoc
 */
function user_menu_avatar_link_alter(&$variables) {

  // Get the 'url' from $variables.
  $url = $variables['url'];

  // Get the form config.
  $config = \Drupal::config('user_menu_avatar.user_menu_avatar_settings');

  // Get the original link text value.
  $originalLinkText = $variables['text'];

  // Get link text form value.
  $linkTextNameFormValue = $config
    ->get('link_text_name');

  // Set $linkTextName.
  $linkTextName = 'My account';

  // We default to 'My account'.
  if (!empty($linkTextNameFormValue)) {
    $linkTextName = $linkTextNameFormValue;
  }

  // Compare the link text value.
  if ($url
    ->isRouted() && $originalLinkText == $linkTextName) {

    // Load the current user by user ID.
    $currentUser = User::load(\Drupal::currentUser()
      ->id());

    // Instantiate $imageURL to empty string.
    $imageURL = '';

    // Instantiate $name to empty string.
    $name = '';

    // Get show menu avatar form value.
    $showMenuAvatar = $config
      ->get('show_menu_avatar');

    // Compare $showMenuAvatar.
    if ($showMenuAvatar == 'yes') {

      // Get avatar shape form value.
      $avatarShapeFormValue = $config
        ->get('avatar_shape');

      // Set $avatarShape.
      $avatarShape = 'circle';

      // We default to circle.
      if (!empty($avatarShapeFormValue)) {
        $avatarShape = $avatarShapeFormValue;
      }

      // Get avatar size form value.
      $avatarSizeFormValue = $config
        ->get('avatar_size');

      // Set $avatarSize.
      $avatarSize = 50;

      // We default to 50px.
      if (!empty($avatarSizeFormValue)) {
        $avatarSize = $avatarSizeFormValue;
      }

      // Get the avatar image field name form value.
      $avatarImageField = $config
        ->get('avatar_image_field');

      // Set the $imageURL value.
      if ($avatarImageField != '') {

        // Check that field config exists.
        if (!empty(FieldConfig::loadByName('user', 'user', $avatarImageField))) {

          // Check that an image exists in the field.
          if ($currentUser->{$avatarImageField}->entity) {

            // Check that the image URL exists.
            if ($currentUser->{$avatarImageField}->entity
              ->url()) {

              // Set $imageURL as image field url value.
              $imageURL = $currentUser->{$avatarImageField}->entity
                ->url();
            }
          }
          elseif (FieldConfig::loadByName('user', 'user', $avatarImageField)
            ->getSetting('default_image')['uuid'] != NULL) {

            // Load the default image settings config.
            $avatarImageFieldSettings = FieldConfig::loadByName('user', 'user', $avatarImageField)
              ->getSetting('default_image');

            // Get the default image URI from settings config.
            $avatarImageFieldURI = \Drupal::entityManager()
              ->loadEntityByUuid('file', $avatarImageFieldSettings['uuid'])
              ->getFileUri();

            // Set $imageURL as image field default url value.
            $imageURL = file_create_url($avatarImageFieldURI);
          }
        }
      }
    }

    // Set the $name value.
    $showMenuName = $config
      ->get('show_menu_name');

    // Compare $showMenuName.
    if ($showMenuName == 'yes') {

      // Get the Drupal username.
      $name = $currentUser
        ->get('name')->value;

      // Get the custom name field form value.
      $customNameFormValue = $config
        ->get('avatar_custom_name_field');

      // Check that field config exists.
      if (!empty(FieldConfig::loadByName('user', 'user', $customNameFormValue))) {

        // Check that the name field has value.
        if ($currentUser->{$customNameFormValue}->value != '') {

          // Set &name as the custom name field value.
          $name = $currentUser->{$customNameFormValue}->value;
        }
      }
    }

    // Build our markup.
    if ($showMenuAvatar == 'yes' && $imageURL != '') {

      // Check that name is shown with image.
      if ($showMenuName == 'yes') {
        $currentUserMenuAvatar = new TranslatableMarkup('<span class="user-menu-avatar @avatarShape" style="background-image: url(@imageURL); width: @avatarSize; height: @avatarSize;" /></span><span class="show-user-name">@userName</span>', [
          '@avatarShape' => $avatarShape,
          '@avatarSize' => $avatarSize . 'px',
          '@imageURL' => $imageURL,
          '@userName' => $name,
        ]);
      }
      else {
        $currentUserMenuAvatar = new TranslatableMarkup('<span class="user-menu-avatar @avatarShape" style="background-image: url(@imageURL); width: @avatarSize; height: @avatarSize;" /></span>', [
          '@avatarShape' => $avatarShape,
          '@avatarSize' => $avatarSize . 'px',
          '@imageURL' => $imageURL,
        ]);
      }
    }
    else {
      $currentUserMenuAvatar = new TranslatableMarkup('<span class="show-user-name-only">@userName</span>', [
        '@userName' => $name,
      ]);
    }

    // Replaces the link text with our markup.
    if ($imageURL != '' || $name != '') {
      $variables['text'] = $currentUserMenuAvatar;
    }
  }
}

/**
 * Implements hook_preprocess_hook().
 *
 * @inheritdoc
 */
function user_menu_avatar_preprocess_page(&$variables) {

  // Attach our styles library.
  $variables['#attached']['library'][] = 'user_menu_avatar/styles';
}

/**
 * Implements hook_help().
 *
 * @inheritdoc
 */
function user_menu_avatar_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.user_menu_avatar':
      $text = file_get_contents(dirname(__FILE__) . '/README.md');
      if (!\Drupal::moduleHandler()
        ->moduleExists('markdown')) {
        return '<pre>' . $text . '</pre>';
      }
      else {

        // Use the Markdown filter to render the README.
        $filter_manager = \Drupal::service('plugin.manager.filter');
        $settings = \Drupal::configFactory()
          ->get('markdown.settings')
          ->getRawData();
        $config = [
          'settings' => $settings,
        ];
        $filter = $filter_manager
          ->createInstance('markdown', $config);
        return $filter
          ->process($text, 'en');
      }
  }
  return NULL;
}

Functions

Namesort descending Description
user_menu_avatar_help Implements hook_help().
user_menu_avatar_link_alter Implements hook_link_alter().
user_menu_avatar_preprocess_page Implements hook_preprocess_hook().