You are here

function webform_group_webform_element_access in Webform 8.5

Same name and namespace in other branches
  1. 6.x modules/webform_group/webform_group.module \webform_group_webform_element_access()

Implements hook_webform_element_access().

File

modules/webform_group/webform_group.module, line 381
Provides a Webform integration with the Group module.

Code

function webform_group_webform_element_access($operation, array $element, AccountInterface $account = NULL) {

  // Set default access rules.
  $element += [
    '#access_' . $operation . '_roles' => [
      'anonymous',
      'authenticated',
    ],
    '#access_' . $operation . '_group_roles' => [],
  ];

  // Get user and group roles.
  $user_roles = $element['#access_' . $operation . '_roles'];
  $group_roles = $element['#access_' . $operation . '_group_roles'];

  // If group roles are empty and current user is assigned Drupal's
  // anonymous/authenticated roles, then allow access.
  if (empty($group_roles)) {
    $current_user_default_role = $account
      ->isAnonymous() ? 'anonymous' : 'authenticated';
    if (in_array($current_user_default_role, $user_roles)) {
      return AccessResult::allowed();
    }
  }

  /** @var \Drupal\webform_group\WebformGroupManagerInterface $webform_group_manager */
  $webform_group_manager = \Drupal::service('webform_group.manager');
  $current_user_group_roles = $webform_group_manager
    ->getCurrentUserGroupRoles() ?: [];

  // If the group or current user roles are empty return no opinion.
  if (empty($group_roles) || empty($current_user_group_roles)) {
    return AccessResult::neutral();
  }
  return AccessResult::allowedIf(array_intersect($group_roles, $current_user_group_roles));
}