You are here

protected function SubscriberAccessControlHandler::checkFieldAccess in Simplenews 8

Same name and namespace in other branches
  1. 8.2 src/SubscriberAccessControlHandler.php \Drupal\simplenews\SubscriberAccessControlHandler::checkFieldAccess()
  2. 3.x src/SubscriberAccessControlHandler.php \Drupal\simplenews\SubscriberAccessControlHandler::checkFieldAccess()

Default field access as determined by this access control handler.

Parameters

string $operation: The operation access should be checked for. Usually one of "view" or "edit".

\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition.

\Drupal\Core\Session\AccountInterface $account: The user session for which to check access.

\Drupal\Core\Field\FieldItemListInterface $items: (optional) The field values for which to check access, or NULL if access is checked for the field definition, without any specific value available. Defaults to NULL.

Return value

\Drupal\Core\Access\AccessResultInterface The access result.

Overrides EntityAccessControlHandler::checkFieldAccess

File

src/SubscriberAccessControlHandler.php, line 50

Class

SubscriberAccessControlHandler
Defines the access control handler for the simplenews subscriber entity type.

Namespace

Drupal\simplenews

Code

protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {

  // Protect access to viewing the mail field.
  if ($field_definition
    ->getName() == 'mail' && $operation == 'view') {

    // Allow based on permissions.
    if ($account
      ->hasPermission('administer simplenews subscriptions') || $account
      ->hasPermission('view simplenews subscriptions')) {
      return AccessResult::allowed()
        ->cachePerPermissions();
    }

    // Users can view their own value.
    if ($account
      ->isAuthenticated() && $items && ($entity = $items
      ->getEntity()) && $entity
      ->getUserId() == $account
      ->id()) {
      return AccessResult::allowed()
        ->addCacheableDependency($entity);
    }

    // Otherwise don't give access.
    return AccessResult::neutral();
  }
  if ($operation == 'edit') {
    switch ($field_definition
      ->getName()) {
      case 'uid':

        // No edit access even for admins.
        return AccessResult::forbidden();
      case 'status':
      case 'created':

        // Only admin can edit.
        return AccessResult::allowedIfHasPermission($account, 'administer simplenews subscriptions');
      case 'mail':
      case 'langcode':

        // No edit access if 'uid' is set.
        if ($items && ($entity = $items
          ->getEntity()) && $entity
          ->getUserId()) {
          return AccessResult::forbidden();
        }
        break;
    }
  }
  return parent::checkFieldAccess($operation, $field_definition, $account, $items);
}