You are here

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

Display user picture and/or user name in menu.

File

user_menu_avatar.module
View source
<?php

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

/**
 * Get the current user.
 */
function uma_getUser() {

  // Get current user ID.
  $userID = \Drupal::currentUser()
    ->id();

  // Load the current user by user ID.
  $currentUser = User::load($userID);
  return [
    'user_id' => $userID,
    'currentUser' => $currentUser,
  ];
}

/**
 * Get our form values.
 */
function uma_CFV() {

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

  // Get link text form value.
  $configLinkText = $config
    ->get('link_text_name') ? rtrim(strip_tags($config
    ->get('link_text_name'))) : 'My account';

  // Get show menu avatar form value.
  $showAvatar = $config
    ->get('show_menu_avatar') ?: 'yes';

  // Set the $name value.
  $showName = $config
    ->get('show_menu_name') ?: 'yes';

  // Get avatar shape form value.
  $avatarShape = $config
    ->get('avatar_shape') ?: 'circle';

  // Get avatar size form value.
  $avatarSize = $config
    ->get('avatar_size') ?: 50;

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

  // Get the custom name field form value.
  $customNameField = $config
    ->get('avatar_custom_name_field') ?: '';
  return [
    'configLinkText' => $configLinkText,
    'showAvatar' => $showAvatar,
    'showName' => $showName,
    'avatarShape' => $avatarShape,
    'avatarSize' => $avatarSize,
    'avatarImageField' => $imageFieldName,
    'customNameField' => $customNameField,
  ];
}

/**
 * Set $name value.
 */
function uma_UserName() {

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

  // Check if we should show user name.
  if (uma_CFV()['showName'] == 'yes') {

    // Get our custom field name.
    $customNameField = uma_CFV()['customNameField'];

    // Check that custom field exists.
    if (!empty(FieldConfig::loadByName('user', 'user', $customNameField)) && uma_getUser()['currentUser']->{$customNameField}->value != '') {

      // Set $name as the value custom name field.
      $name = uma_getUser()['currentUser']->{$customNameField}->value;
    }
    else {

      // Set $name as default username.
      $name = uma_getUser()['currentUser']
        ->getDisplayName();
    }
  }
  return $name;
}

/**
 * Set the $imageURL value.
 */
function uma_ImageURL() {

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

  // Compare $showAvatar.
  if (uma_CFV()['showAvatar'] == 'yes') {

    // Set the avatar field name.
    $imageFieldName = uma_CFV()['avatarImageField'];

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

      // Load image style.
      $imageStyle = \Drupal::entityTypeManager()
        ->getStorage('image_style')
        ->load('thumbnail');

      // Check that an image exists in the field.
      if (uma_getUser()['currentUser']->{$imageFieldName}->entity) {

        // Load image with image style.
        $imageStyleURL = $imageStyle
          ->buildUrl(uma_getUser()['currentUser']->{$imageFieldName}->entity->uri->value);

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

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

        // Get the default image URI from settings.
        $imageURI = Drupal::service('entity.repository')
          ->loadEntityByUuid('file', $imageGetSettings['uuid'])
          ->getFileUri();

        // Load image with image style.
        $imageStyleURL = $imageStyle
          ->buildUrl($imageURI);

        // Set $imageURL as image field default URI value.
        $imageURL = $imageStyleURL;
      }
    }
  }
  return file_url_transform_relative($imageURL);
}

/**
 * Build our new replacement markup.
 */
function uma_Markup() {

  // Build our markup.
  if (uma_CFV()['showAvatar'] == 'yes' && uma_ImageURL() != '') {

    // Check that name is shown with image.
    if (uma_CFV()['showName'] == 'yes') {
      $markup = 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' => uma_CFV()['avatarShape'],
        '@avatarSize' => uma_CFV()['avatarSize'] . 'px',
        '@imageURL' => uma_ImageURL(),
        '@userName' => uma_UserName(),
      ]);
    }
    else {
      $markup = new TranslatableMarkup('<span class="user-menu-avatar @avatarShape" style="background-image: url(@imageURL); width: @avatarSize; height: @avatarSize;" /></span>', [
        '@avatarShape' => uma_CFV()['avatarShape'],
        '@avatarSize' => uma_CFV()['avatarSize'] . 'px',
        '@imageURL' => uma_ImageURL(),
      ]);
    }
  }
  else {
    $markup = new TranslatableMarkup('<span class="show-user-name-only">@userName</span>', [
      '@userName' => uma_UserName(),
    ]);
  }
  return $markup;
}

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

  // Loop through first menu level.
  foreach ($variables['items'] as &$key) {
    uma_apply_markup($variables, $key);
  }
}

/**
 * Apply markup per menu link.
 *
 * @param $variables
 *   Variables.
 * @param $menu_link
 *   Menu link item.
 */
function uma_apply_markup(&$variables, &$menu_link) {

  // Get clean link title to compare against.
  $title = rtrim(strip_tags($menu_link['title']));

  // Compare $title value.
  if ($title === uma_CFV()['configLinkText']) {

    // Replaces the link title with our markup.
    if (uma_ImageURL() != '' || uma_UserName() != '') {

      // Get our markup.
      $markup = uma_Markup();

      // Change the item title.
      $menu_link['title'] = $markup;

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

      // Set cache context per user.
      $variables['#cache']['contexts'][] = 'user';
    }
  }

  // Loop through second menu level.
  foreach ($menu_link['below'] as &$beKey) {
    uma_apply_markup($variables, $beKey);
  }
}

/**
 * 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
uma_apply_markup Apply markup per menu link.
uma_CFV Get our form values.
uma_getUser Get the current user.
uma_ImageURL Set the $imageURL value.
uma_Markup Build our new replacement markup.
uma_UserName Set $name value.
user_menu_avatar_help Implements hook_help().
user_menu_avatar_preprocess_menu Implements hook_preprocess_hook().