You are here

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

Display user_picture or username in menu.

File

user_menu_avatar.module
View source
<?php

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

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

  // Set the default size and shape values, there are none until the form is saved.
  $avatarSize = 50;
  $avatarShape = 'circle';

  // Grab the 'url' array key from $variables.
  $url = $variables['url'];

  // Check if $url matches the user profile URL value.
  if ($url
    ->isRouted() && $url
    ->getRouteName() == 'user.page') {
    $route_name = $url
      ->getRouteName();
    if ($route_name != 'user.page') {
      return;
    }
    elseif ($variables['text'] == t('My account')) {

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

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

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

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

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

      // Get the custom image field name.
      $avatarCustomImageField = $config
        ->get('avatar_custom_image_field');

      // Show picture and anme config.
      $avatarShowImageAndName = $config
        ->get('avatar_show_picture_and_name');

      // Check if $avatarShapeFormValue $config has values.
      if (!empty($avatarShapeFormValue)) {

        // Set the shape value with the form value.
        $avatarShape = $avatarShapeFormValue;
      }

      // Check if $avatarSizeFormValue $config has values.
      if (!empty($avatarSizeFormValue)) {

        // Set the size value with the form value.
        $avatarSize = $avatarSizeFormValue;
      }

      // Check if a custom image field exists.
      if (!empty(FieldStorageConfig::loadByName('user', $avatarCustomImageField))) {

        // Check the custom image field has value.
        if ($user
          ->get($avatarCustomImageField)->entity) {
          $imageURL = $user
            ->get($avatarCustomImageField)->entity
            ->url();
        }
        else {
          $imageURL = '';
        }
      }
      elseif (!empty(FieldStorageConfig::loadByName('user', 'user_picture'))) {

        // Check the user_picture field has value.
        if ($user
          ->get('user_picture')->entity) {
          $imageURL = $user
            ->get('user_picture')->entity
            ->url();
        }
        else {
          $imageURL = '';
        }
      }
      else {
        $imageURL = '';
      }
      if ($avatarShowImageAndName == 'yes') {

        // Check if $imageURL has value.
        if ($imageURL != '') {

          // Create a variable that contains our new markup with user image.
          $userMenuAvatar = 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,
          ]);

          // Replace text of the User Account menu item with new markup.
          $variables['text'] = $userMenuAvatar;
        }
        else {
          $variables['text'] = $name;
        }
      }
      else {

        // Check if $imageURL has value.
        if ($imageURL != '') {

          // Create a variable that contains our new markup with user image.
          $userMenuAvatar = 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,
          ]);

          // Replace text of the User Account menu item with new markup.
          $variables['text'] = $userMenuAvatar;
        }
        else {
          $variables['text'] = $name;
        }
      }
    }
  }
}

/**
 * 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().