You are here

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

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;
use Drupal\file\Entity\File;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * 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.settings');

  // Get link text form value by langcode.
  $menuLinkText = $config
    ->get('link_text') ?: NULL;

  // Show menu avatar.
  $showAvatar = $config
    ->get('show_menu_avatar') ?: 'no';

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

  // 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.
  $avatarImageField = $config
    ->get('avatar_image_field') ?: 'user_picture';

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

  // Show anonymous avatar.
  $showAnonymousAvatar = $config
    ->get('show_anonymous_avatar') ?: 'no';

  // Get the anonymous avatar.
  $anonymousUserAvatar = $config
    ->get('anonymous_user_avatar') ?: '';

  // Show anonymous user text.
  $showAnonymousName = $config
    ->get('show_anonymous_name') ?: 'no';

  // Get the anonymous user text.
  $customAnonymousText = $config
    ->get('custom_anonymous_text') ?: '';
  return [
    'menuLinkText' => $menuLinkText,
    'showAvatar' => $showAvatar,
    'showName' => $showName,
    'avatarShape' => $avatarShape,
    'avatarSize' => $avatarSize,
    'avatarImageField' => $avatarImageField,
    'customNameField' => $customNameField,
    'showAnonymousAvatar' => $showAnonymousAvatar,
    'anonymousUserAvatar' => $anonymousUserAvatar,
    'showAnonymousName' => $showAnonymousName,
    'customAnonymousText' => $customAnonymousText,
  ];
}

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

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

  // Check if we should show user name.
  if (\Drupal::currentUser()
    ->isAnonymous() && uma_CFV()['showAnonymousName'] === 'yes') {
    if (uma_CFV()['customAnonymousText'] != '') {

      // Get our anonymous text.
      $name = uma_CFV()['customAnonymousText'];
    }
    else {

      // Set $name as default username.
      $name = uma_getUser()['currentUser']
        ->getDisplayName();
    }
  }
  if (!\Drupal::currentUser()
    ->isAnonymous() && 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 = NULL;

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

  // Check to show anonymous avatar.
  if (\Drupal::currentUser()
    ->isAnonymous() && uma_CFV()['showAnonymousAvatar'] === 'yes') {
    if (isset(uma_CFV()['anonymousUserAvatar'][0])) {

      // Load anonymous avatar with image style.
      $imageStyleURL = $imageStyle
        ->buildUrl(File::load(uma_CFV()['anonymousUserAvatar'][0])
        ->getFileUri());

      // Set $imageURL as anonymous image field url value.
      $imageURL = file_url_transform_relative($imageStyleURL);
    }
  }

  // Check to show avatar.
  if (!\Drupal::currentUser()
    ->isAnonymous() && uma_CFV()['showAvatar'] === 'yes') {

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

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

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

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

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

        // Load the default image settings.
        $imageGetSettings = FieldConfig::loadByName('user', 'user', $avatarImageField)
          ->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 = file_url_transform_relative($imageStyleURL);
      }
    }
  }
  return $imageURL;
}

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

  // Check that name is shown with image.
  if (uma_ImageURL() && uma_UserName()) {
    $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(),
    ]);
  }
  elseif (uma_ImageURL()) {
    $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(),
    ]);
  }
  elseif (uma_UserName()) {
    $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) {

  // Check we have anything to replace.
  if (uma_ImageURL() || uma_UserName()) {

    // 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) {
  $title = $menu_link['title'] ? trim(strip_tags($menu_link['title'])) : NULL;

  // Compare menu link ID value.
  if ($title && $title === uma_CFV()['menuLinkText']) {

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

    // Replace title with our markup.
    $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().