You are here

function role_expire_cron in Role Expire 2.x

Same name and namespace in other branches
  1. 8 role_expire.module \role_expire_cron()
  2. 6 role_expire.module \role_expire_cron()
  3. 7 role_expire.module \role_expire_cron()

Implements hook_cron().

TODO: This method needs intensive debugging.

File

./role_expire.module, line 326
Role Expire module.

Code

function role_expire_cron() {
  $expires = \Drupal::service('role_expire.api')
    ->getExpired();
  if ($expires) {
    foreach ($expires as $expire) {

      // Remove the role expiration record from the role_expires table.
      \Drupal::service('role_expire.api')
        ->deleteRecord($expire->uid, $expire->rid);

      // Remove the role from the user.
      $account = User::load($expire->uid);

      // If the account *does* exist, update it.
      if (!empty($account)) {

        // Assign a new role after expiration if requested given configuration.
        $new_roles = \Drupal::service('role_expire.api')
          ->getRolesAfterExpiration();
        if (!empty($new_roles) && !empty($new_roles[$expire->rid])) {
          $new_rid = $new_roles[$expire->rid];
          $account
            ->addRole($new_rid);
          \Drupal::service('role_expire.api')
            ->processDefaultRoleDurationForUser($new_rid, $account
            ->id());
          \Drupal::logger('role_expire')
            ->notice(t('Added role @role to user @account.', [
            '@role' => $new_rid,
            '@account' => $account
              ->id(),
          ]));
        }
        $account
          ->removeRole($expire->rid);
        $account
          ->save();

        /*
         * Rules integration.
         * https://fago.gitbooks.io/rules-docs/content/extending_rules/events.html
         * #3193800: RoleExpiresEvent should not depend on Rules module
         */
        $event = new RoleExpiresEvent($account, $expire->rid);
        $event_dispatcher = \Drupal::service('event_dispatcher');
        $event_dispatcher
          ->dispatch(RoleExpiresEvent::EVENT_NAME, $event);
        \Drupal::logger('role_expire')
          ->notice(t('Removed role @role from user @account.', [
          '@role' => $expire->rid,
          '@account' => $account
            ->id(),
        ]));
      }
      else {

        // The account doesn't exist. Throw a warning message.
        \Drupal::logger('role_expire')
          ->notice(t('Data integrity warning: Role_expire table updated, but no user with uid @uid.', [
          '@uid' => $expire->uid,
        ]));
      }
    }
  }
}