Drupal - Currently logged in user's roles
Something like:
$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();
will return an array like:
Array
(
[0] => authenticated
[1] => administrator
[2] => some_other_role
)
where the array values are role IDs (equivalent to the machine name of the role in Drupal 7). In OO code, use the appropriate mechanism get the current user from the container, eg
$current_user = $container->get('current_user');
This is the way I do it:
// Get actual user role.
$current_user_roles = \Drupal::currentUser()->getRoles();
// Check if user is not admin.
if (!in_array('administrator', $current_user_roles)) {
// Check if user is an admin.
if (in_array('administrator', $current_user_roles)) {