You are here

function workbench_access_entity_create_access in Workbench Access 8

Implements hook_node_create_access().

@link https://www.drupal.org/node/2348203

File

./workbench_access.module, line 93
Contains workbench_access.module.

Code

function workbench_access_entity_create_access(AccountInterface $account, $context, $entity_bundle) {

  // @todo move this to the access schemes.
  $return = AccessResult::neutral();

  // User can bypass.
  if ($account
    ->hasPermission('bypass workbench access')) {
    return $return
      ->cachePerPermissions();
  }

  // Check that access control applies to this entity type.
  $entity_type_id = $context['entity_type_id'];
  $schemes = array_filter(\Drupal::entityTypeManager()
    ->getStorage('access_scheme')
    ->loadMultiple(), function (AccessSchemeInterface $scheme) use ($entity_type_id, $entity_bundle, $return) {
    $return
      ->addCacheableDependency($scheme);
    return $scheme
      ->getAccessScheme()
      ->applies($entity_type_id, $entity_bundle);
  });
  if (!$schemes) {
    return $return
      ->addCacheTags([
      'access_scheme_list',
    ]);
  }

  // Check that the user is able to assign content to a section.
  $user_section_storage = \Drupal::service('workbench_access.user_section_storage');
  $forbidden = AccessResult::forbidden();
  $invalid_schemes = array_reduce($schemes, function ($carry, AccessSchemeInterface $scheme) use ($user_section_storage, $account, $forbidden) {
    $sections = $user_section_storage
      ->getUserSections($scheme, $account);
    if (!$sections) {
      $carry[] = $scheme
        ->label();
    }
    $forbidden
      ->addCacheableDependency($scheme);
    return $carry;
  }, []);
  if ($invalid_schemes) {
    return $forbidden
      ->setReason(sprintf('User has no active sections for the following access scheme(s): %s', implode(', ', $invalid_schemes)));
  }
  return $return;
}