简体   繁体   中英

Is there a way to remove all roles from a user that have a specific subrole in Symfony?

I am using the FosUserBundle which provides the function where you can remove roles.

$user->removeRole("ROLE_SUBSCRIBER_BASIC")

This is nice and all, but my main problem is that I would like to remove the role by a specific subrole. My hierarchy in security.yml looks like this:

    ROLE_SUBSCRIBER: ROLE_USER
    ROLE_SUBSCRIBER_MONTHLY: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_YEARLY: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_BASIC:  [ROLE_SUBSCRIBER]
    ROLE_PRIVILEGE_PLUS: [ROLE_SUBSCRIBER]
    ROLE_SUBSCRIBER_PLUS:  [ROLE_PRIVILEGE_PLUS]
    ROLE_SUBSCRIBER_EXTRA:  [ROLE_PRIVILEGE_PLUS]

As you can see a PLUS, EXTRA and BASIC subscriber all are subscribers so i gave them a subrole "ROLE_SUBSCRIBER". In my unsubscribe function, I would like to remove the current subscriber role, without having to use if else loops like this:

 public function unsubscribe(User $user)
    {
    if($user->hasRole("ROLE_SUBSCRIBER_BASIC")){
        $user->removeRole("ROLE_SUBSCRIBER_BASIC");
    }
    if($user->hasRole("ROLE_SUBSCRIBER_PLUS")){
        $user->removeRole("ROLE_SUBSCRIBER_PLUS");
    }
    if($user->hasRole("ROLE_SUBSCRIBER_EXTRA")){
        $user->removeRole("ROLE_SUBSCRIBER_EXTRA");
    }

... }

This if/else loops does its job, but think about the future. What if my boss wants there to be more subscriber roles, then I would have to edit this function every single time and add another IF. Is there a more efficient way to do this? Like by deleting the role by subrole.

$user->removeRole("ROLE_SUBSCRIBER")

This way it would remove ROLE_SUBSCRIBER_EXTRA,ROLE_SUBSCRIBER_BASIC, ...MONTHLY, ...YEARLY or ...PLUS automatically, without me having to check what kind of subscription the user currently has!?

You can do something like this:

const KEEP_ROLES = ['ROLE_ADMIN'];

$rolesToRemove = array_diff($user->getRoles(), KEEP_ROLES);

foreach ($rolesToRemove as $role) {
   $user->removeRole($role);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM