You are here

function uc_role_grant in Ubercart 8.4

Grants a role to a given user.

This function grants a given role to a user's list of roles. If there is a previous record of this user/role combination, it is first removed. The function then saves the user (if $user_save is TRUE). Next, a check to verify the role actually exists, if not, no expiration data is stored. The menu cache is flushed, as new menu items may be visible after the new role is granted. The function notifies the user of the role grant.

Parameters

\Drupal\user\UserInterface $account: A Drupal user object.

string $rid: A Drupal role ID.

int $timestamp: When this role will expire.

bool $save_user: Optimization to prevent unnecessary user saving when calling from uc_role_user_presave().

bool $silent: When set to TRUE will suppress any Drupal messages from this function.

2 calls to uc_role_grant()
RenewRole::doExecute in uc_role/src/Plugin/RulesAction/RenewRole.php
Renews an order's product roles.
uc_role_user_presave in uc_role/uc_role.module
Implements hook_user_presave().

File

uc_role/uc_role.module, line 573
Grants roles upon accepted payment of products.

Code

function uc_role_grant(UserInterface &$account, $rid, $timestamp, $save_user = TRUE, $silent = FALSE) {

  // First, delete any previous record of this user/role association.
  uc_role_delete($account, $rid, $silent);
  if ($save_user) {

    // Punch the role into the user object.
    $account
      ->addRole($rid);
    $account
      ->save();
  }

  // If the role expires, keep a record.
  $connection = \Drupal::database();
  if (!is_null($timestamp)) {
    $connection
      ->insert('uc_roles_expirations')
      ->fields([
      'uid' => $account
        ->id(),
      'rid' => $rid,
      'expiration' => $timestamp,
    ])
      ->execute();
  }

  // Display the message if appropriate.
  if (!$silent) {
    $role_name = $connection
      ->query('SELECT name FROM {role} WHERE rid = :rid', [
      ':rid' => $rid,
    ])
      ->fetchField();
    if (\Drupal::currentUser()
      ->id() == $account
      ->id()) {
      $message = t('You have been granted the %role role.', [
        '%role' => $role_name,
      ]);
    }
    else {
      $username = [
        '#theme' => 'username',
        '#account' => $account,
      ];
      $message = t('@user has been granted the %role role.', [
        '@user' => drupal_render($username),
        '%role' => $role_name,
      ]);
    }
    if ($timestamp) {
      $message .= ' ' . t('It will expire on %date', [
        '%date' => \Drupal::service('date.formatter')
          ->format($timestamp, 'short'),
      ]);
    }
    \Drupal::messenger()
      ->addMessage($message);
  }
}