You are here

function realname_update in Real Name 8

Same name and namespace in other branches
  1. 7 realname.module \realname_update()
  2. 2.x realname.module \realname_update()

Update the realname for a user account.

Parameters

Drupal\user\Entity\User $account: A user account object.

Return value

string A string with the real name.

See also

hook_realname_pattern_alter()

hook_realname_alter()

hook_realname_update()

Related topics

3 calls to realname_update()
RealnameUpdateRealname::execute in src/Plugin/Action/RealnameUpdateRealname.php
Executes the plugin.
realname_load_multiple in ./realname.module
Loads multiple real names.
realname_user_update in ./realname.module
Implements hook_ENTITY_TYPE_update().

File

./realname.module, line 207
Provides token-based name displays for users.

Code

function realname_update(User $account) {
  $realname = '';
  if (!$account
    ->isAnonymous()) {

    // Get the default pattern and allow other modules to alter it.
    $config = \Drupal::config('realname.settings');
    $pattern = $config
      ->get('pattern');
    \Drupal::moduleHandler()
      ->alter('realname_pattern', $pattern, $account);

    // Perform token replacement on the real name pattern.
    $realname = \Drupal::token()
      ->replace($pattern, [
      'user' => $account,
    ], [
      'clear' => TRUE,
      'sanitize' => FALSE,
    ]);

    // Remove any HTML tags.
    $realname = strip_tags(Html::decodeEntities($realname));

    // Remove double spaces (if a token had no value).
    $realname = preg_replace('/ {2,}/', ' ', $realname);

    // Allow other modules to alter the generated realname.
    \Drupal::moduleHandler()
      ->alter('realname', $realname, $account);

    // The name must be trimmed to 255 characters before inserting into the
    // database.
    $realname = Unicode::truncate(trim($realname), 255);
  }
  else {

    // DisplayName cannot generated with tokens for anonymous users.
    $realname = $account
      ->label();
  }

  // Save to the database and the static cache.
  \Drupal::database()
    ->merge('realname')
    ->key([
    'uid' => $account
      ->id(),
  ])
    ->fields([
    'realname' => $realname,
    'created' => \Drupal::time()
      ->getRequestTime(),
  ])
    ->execute();

  // Allow modules to react to the realname being updated.
  \Drupal::moduleHandler()
    ->invokeAll('realname_update', [
    $realname,
    $account,
  ]);

  // Clear the entity cache.

  /** @var \Drupal\user\UserStorageInterface $user_storage */
  $user_storage = \Drupal::entityTypeManager()
    ->getStorage('user');
  $user_storage
    ->resetCache([
    $account
      ->id(),
  ]);
  return $realname;
}