1
votes

with:
$userRole = yii::$app->authManager->getRolesByUser($userId);

got the array:

$userRole = Array
(
    [author] => yii\rbac\Role Object
        (
            [type] => 1
            [name] => author
            [description] => 
            [ruleName] => 
            [data] => 
            [createdAt] => 1437713730
            [updatedAt] => 1437713730
        )

)


want to just get a string:
     the value of the $userRole is 'author'.


without using: $userRole = array_keys(yii::$app->authManager->getRolesByUser($userId))[0]
2
What if the user have more than one role ? it is about parsing the array or about figuring out how to get the role name directly instead of an array ? - Salem Ouerdani

2 Answers

1
votes

getRolesByUser() was built to return all user's roles, we can't force it to expect him having only one role because that is not how rbac works, if you need to check if user can do a certain role, then use this instead :

Yii::$app->user->can($role);

Otherwise if you really need $userRole to hold the role name as a string value if the user have only one role, and lets say an array of roles if he got more, then this may be a cleaner way to do what you are asking for :

$userRole = yii::$app->authManager->getRolesByUser($userId);

// if no roles $userRole will be null by default
// so we better be sure that is not the case before doing the next

if ($userRole) {

    foreach ($userRole as $role) {
       $roles[] = $role->name;
    }

    // if user have 1 role then $userRole will be a string containing it
    // othewhise let $userRole be an array containing them all

    $userRole = count($roles) === 1 ? $roles[0] : $roles ;
}
0
votes

Thanks! That was what I want to know exactly: yii2 don't have method to give the role back als string directly, because one User may have more roles.