You are here

class RoleExpireSetExpireTime in Role Expire 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/RulesAction/RoleExpireSetExpireTime.php \Drupal\role_expire\Plugin\RulesAction\RoleExpireSetExpireTime

Provides a 'Set expire time' action.

Plugin annotation


@RulesAction(
  id = "role_expire_set_expire_time",
  label = @Translation("Set expire time for user roles"),
  category = @Translation("Role expire"),
  context_definitions = {
    "user" = @ContextDefinition("entity:user",
      label = @Translation("User")
    ),
    "roles" = @ContextDefinition("string",
      label = @Translation("Roles ID"),
      multiple = TRUE
    ),
    "date" = @ContextDefinition("string",
      label = @Translation("Roles expiry date"),
      description = @Translation("Enter date and time in format <em>YYYY-MM-DD HH:MM:SS</em> or use relative time i.e. 1 day, 2 months, 1 year, 3 years.")
    )
  }
)

Hierarchy

Expanded class hierarchy of RoleExpireSetExpireTime

File

src/Plugin/RulesAction/RoleExpireSetExpireTime.php, line 31

Namespace

Drupal\role_expire\Plugin\RulesAction
View source
class RoleExpireSetExpireTime extends RulesActionBase {

  /**
   * Assign expire time for user and role.
   *
   * @param \Drupal\user\UserInterface $account
   *   User object.
   * @param string $roles
   *   Array of User roles ID.
   * @param string $date
   *   Date when the roles will expire.
   *
   * @throws \Drupal\rules\Exception\InvalidArgumentException
   */
  protected function doExecute(UserInterface $account, array $roles, $date) {
    foreach ($roles as $role) {

      // Skip adding the expire time for the role if user doesn't have it.
      if ($account
        ->hasRole($role)) {
        try {
          $time = strtotime($date);
          if (!empty($time)) {
            \Drupal::service('role_expire.api')
              ->writeRecord($account
              ->id(), $role, $time);
          }
          else {
            throw new InvalidArgumentException($this
              ->t('Invalid date format.'));
          }
        } catch (\InvalidArgumentException $e) {
          throw new InvalidArgumentException($e
            ->getMessage());
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
RoleExpireSetExpireTime::doExecute protected function Assign expire time for user and role.