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 */ }
CommentFileSizeAuthor
#4 user.module.user_is-features.patch739 bytessobi3ch

Comments

sobi3ch’s picture

Status: Needs review » Needs work

Actually we need to work on this..

khanton’s picture

Version: 7.x-dev » 6.16

Hi !

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.

sobi3ch’s picture

Version: 6.16 » 7.x-dev
Assigned: Unassigned » sobi3ch
Status: Needs work » Needs review

right @khanton

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($roles, array_values($user->roles));
        }
}
sobi3ch’s picture

Title: Check that user have specific role(s); user_is($roles); » Function that checks is user have specific role/roles
StatusFileSize
new739 bytes

patch

gmak’s picture

#4: user.module.user_is-features.patch queued for re-testing.

Status: Needs review » Needs work

The last submitted patch, user.module.user_is-features.patch, failed testing.

lelizondo’s picture

Version: 7.x-dev » 8.x-dev
swentel’s picture

Status: Needs work » Closed (fixed)

In D8 we have the hasRole() method.