I want to proposed new function in core user.module to omit long code like this:
global $user;
if(in_array($role, array_values($user->roles)) {
// .. do something
}
cleaner solution is
function user_is($roles) {
global $user;
if(is_array($roles)) {
foreach($roles as $role) {
if(in_array($role, array_values($user->roles))) {
return TRUE;
}
}
} else {
return in_array($role, array_values($user->roles));
}
}
.. so u can use like this
if(user_is('employer')) { /* ..do something */ }
OR
if user is employer OR employee (have one of role in array)
if(user_is(array('employer', 'employee'))) { /* ..do something */ }
Comments
Comment #1
sobi3ch commentedActually we need to work on this..
Comment #2
khanton commentedHi !
Small bug !
fix:
return in_array($role, array_values($user->roles));
replace to:
return in_array($roles, array_values($user->roles));
In this case $roles not array but string.
Thx for code.
Comment #3
sobi3ch commentedright @khanton
Comment #4
sobi3ch commentedpatch
Comment #5
gmak commented#4: user.module.user_is-features.patch queued for re-testing.
Comment #7
lelizondo commentedComment #8
swentel commentedIn D8 we have the hasRole() method.