You are here

function uc_role_user_presave in Ubercart 8.4

Implements hook_user_presave().

File

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

Code

function uc_role_user_presave(UserInterface $account) {
  if (!\Drupal::currentUser()
    ->hasPermission('administer users')) {
    return;
  }

  // Grant a new role if a new temporary role is added.
  if (!empty($account->new_role)) {

    // Save our role info, but don't save the user; user.module will do that.
    uc_role_grant($account, $account->new_role, _uc_role_get_expiration($account->new_role_add_qty, $account->new_role_add_granularity), FALSE);

    // Push in values so user.module will save in the roles.
    $account->roles[$account->new_role_add] = _uc_role_get_name($account->new_role_add);

    // Reset the new role form.
    unset($account->new_role);
    unset($account->new_role_add);
    unset($account->new_role_add_qty);
    unset($account->new_role_add_qty);
  }

  // Check if any temporary role actions were taken.
  if (isset($account->table)) {
    foreach ($account->table as $rid => $value) {

      // Remove this expiration.
      if ($value['remove']) {
        uc_role_delete($account, $rid);
      }
      else {
        if ($value['qty'] && $account
          ->hasRole($rid)) {
          $qty = $value['qty'];
          $qty *= $value['polarity'] == 'add' ? 1 : -1;
          uc_role_renew($account, $rid, _uc_role_get_expiration($qty, $value['granularity'], $value['expiration']));
        }
      }
    }
  }

  // If a user's role is removed using Drupal, then so is any expiration data.
  if (isset($account->original->roles)) {
    foreach ($account->original->roles as $rid => $role) {
      if (!in_array($rid, $account
        ->getRoles()) && $rid != AccountInterface::AUTHENTICATED_ROLE) {
        uc_role_delete($account, $rid);
      }
    }
  }
}