get a user roles at various context / level
// at course level
$context = \context_course::instance($course->id);
// at system level
//$context = \context_system::instance();
// at category level
//$context = \context_coursecat::($cat->id);
$roles = get_user_roles($context, $user->id, '', 'c.contextlevel DESC');
// $roles will be array