orIf example

$account = $this->prepareUser($account);
      $file_uid = $entity->get('uid')->getValue();
      // Only the file owner can update the file entity.       if (isset($file_uid[0]['target_id']) && $account->id() == $file_uid[0]['target_id']) {
        return AccessResult::allowed();
      }
      return AccessResult::forbidden('Only the file owner can update the file entity.');
    }
    elseif ($operation == 'delete') {
      $access = AccessResult::allowedIfHasPermission($account, 'delete any file');
      if (!$access->isAllowed() && $account->hasPermission('delete own files')) {
        $access = $access->orIf(AccessResult::allowedIf($account->id() == $entity->getOwnerId()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // No opinion.     return AccessResult::neutral();
  }

  /** * Wrapper for file_get_file_references(). * * @param \Drupal\file\FileInterface $file * The file object for which to get references. * * @return array * A multidimensional array. The keys are field_name, entity_type, * entity_id and the value is an entity referencing this file. * * @see file_get_file_references() */
$neutral_other = AccessResult::neutral('other neutral message');
    $neutral_reasonless = AccessResult::neutral();
    $allowed = AccessResult::allowed();
    $forbidden = AccessResult::forbidden('forbidden message');
    $forbidden_other = AccessResult::forbidden('other forbidden message');
    $forbidden_reasonless = AccessResult::forbidden();
    $unused_access_result_due_to_lazy_evaluation = $this->createMock('\Drupal\Core\Access\AccessResultInterface');
    $unused_access_result_due_to_lazy_evaluation->expects($this->never())
      ->method($this->anything());

    // ALLOWED || ALLOWED === ALLOWED.     $access = $allowed->orIf($allowed);
    $this->assertTrue($access->isAllowed());
    $this->assertFalse($access->isForbidden());
    $this->assertFalse($access->isNeutral());
    $this->assertDefaultCacheability($access);

    // ALLOWED || NEUTRAL === ALLOWED.     $access = $allowed->orIf($neutral);
    $this->assertTrue($access->isAllowed());
    $this->assertFalse($access->isForbidden());
    $this->assertFalse($access->isNeutral());
    $this->assertDefaultCacheability($access);

    
/** * Provides en entity access control handler for base field override entity. */
class BaseFieldOverrideAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    $access = parent::checkAccess($entity$operation$account);
    return $access->orIf(AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields'));
  }

}

  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    // This tab should not show up unless there's a reason to show it.     $entity = $this->loadEntity($route$route_match);
    if ($this->moderationInfo->hasPendingRevision($entity)) {
      // Check the global permissions first.       $access_result = AccessResult::allowedIfHasPermissions($account['view latest version', 'view any unpublished content']);
      if (!$access_result->isAllowed()) {
        // Check entity owner access.         $owner_access = AccessResult::allowedIfHasPermissions($account['view latest version', 'view own unpublished content']);
        $owner_access = $owner_access->andIf((AccessResult::allowedIf($entity instanceof EntityOwnerInterface && ($entity->getOwnerId() == $account->id()))));
        $access_result = $access_result->orIf($owner_access);
      }

      return $access_result->addCacheableDependency($entity);
    }

    return AccessResult::forbidden('No pending revision for moderated entity.')->addCacheableDependency($entity);
  }

  /** * Returns the default revision of the entity this route is for. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * * @return \Drupal\Core\Entity\ContentEntityInterface * returns the Entity in question. * * @throws \Drupal\Core\Access\AccessException * An AccessException is thrown if the entity couldn't be loaded. */

      elseif ($entity_display = $this->entityTypeManager->getStorage('entity_view_display')->load($entity_type_id . '.' . $bundle . '.' . $view_mode_name)) {
        $visibility = $entity_display->status();
      }

      if ($view_mode_name != 'default' && $entity_display) {
        $access->addCacheableDependency($entity_display);
      }

      if ($visibility) {
        $permission = $route->getRequirement('_field_ui_view_mode_access');
        $access = $access->orIf(AccessResult::allowedIfHasPermission($account$permission));
      }
    }
    return $access;
  }

}
$access = $this->checkEntityAccess($entity, 'view', $account);
    $entity->addCacheableDependency($access);
    if (!$access->isAllowed()) {
      // If this is the default revision or the entity is not revisionable, then       // check access to the entity label. Revision support is all or nothing.       if (!$entity->getEntityType()->isRevisionable() || $entity->isDefaultRevision()) {
        $label_access = $entity->access('view label', NULL, TRUE);
        $entity->addCacheableDependency($label_access);
        if ($label_access->isAllowed()) {
          return LabelOnlyResourceObject::createFromEntity($resource_type$entity);
        }
        $access = $access->orIf($label_access);
      }
      return new EntityAccessDeniedHttpException($entity$access, '/data', 'The current user is not allowed to GET the selected resource.');
    }
    return ResourceObject::createFromEntity($resource_type$entity);
  }

  /** * Checks access to the given entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which access should be evaluated. * @param string $operation * The entity operation for which access should be evaluated. * @param \Drupal\Core\Session\AccountInterface $account * (optional) The account with which access should be checked. Defaults to * the current user. * * @return \Drupal\Core\Access\AccessResultInterface|\Drupal\Core\Access\AccessResultReasonInterface * The access check result. */
        // - non-configurable field storages,         // - locked field storages,         // - field storages that should not be added via user interface,         // - field storages that already have a field in the bundle.         $field_type = $field_storage->getType();
        $access->addCacheableDependency($field_storage);
        if ($field_storage instanceof FieldStorageConfigInterface
          && !$field_storage->isLocked()
          && empty($field_types[$field_type]['no_ui'])
          && !in_array($bundle$field_storage->getBundles(), TRUE)) {
          $permission = $route->getRequirement('_field_ui_field_reuse_access');
          $access = $access->orIf(AccessResult::allowedIfHasPermission($account$permission));
        }
      }
      $access->addCacheableDependency($this->entityFieldManager);
    }
    return $access;
  }

}

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    assert($entity instanceof BlockContentInterface);
    $bundle = $entity->bundle();
    $forbidIfNotDefaultAndLatest = fn (): AccessResultInterface => AccessResult::forbiddenIf($entity->isDefaultRevision() && $entity->isLatestRevision());
    $forbidIfNotReusable = fn (): AccessResultInterface => AccessResult::forbiddenIf($entity->isReusable() === FALSE, sprintf('Block content must be reusable to use `%s` operation', $operation));
    $access = match ($operation) {
      // Allow view and update access to user with the 'edit any (type) block       // content' permission or the 'administer blocks' permission.       'view' => AccessResult::allowedIf($entity->isPublished())
        ->orIf(AccessResult::allowedIfHasPermissions($account[
          'access block library',
        ]))->orIf(AccessResult::allowedIfHasPermissions($account[
          'administer block content',
        ])),
      'update' => AccessResult::allowedIfHasPermissions($account[
        'access block library',
        'edit any ' . $bundle . ' block content',
      ])->orIf(AccessResult::allowedIfHasPermissions($account[
        'administer block content',
      ])),
      'delete' => AccessResult::allowedIfHasPermissions($account[
        

  protected function getExpectedGetRelationshipResponse($relationship_field_name, EntityInterface $entity = NULL) {
    $entity = $entity ?: $this->entity;
    $access = AccessResult::neutral()->addCacheContexts($entity->getEntityType()->isRevisionable() ? ['url.query_args:resourceVersion'] : []);
    $access = $access->orIf(static::entityFieldAccess($entity$this->resourceType->getInternalName($relationship_field_name), 'view', $this->account));
    if (!$access->isAllowed()) {
      $via_link = Url::fromRoute(
        sprintf('jsonapi.%s.%s.relationship.get', static::$resourceTypeName$relationship_field_name),
        ['entity' => $entity->uuid()]
      );
      return static::getAccessDeniedResponse($this->entity, $access$via_link$relationship_field_name, 'The current user is not allowed to view this relationship.', FALSE);
    }
    $expected_document = $this->getExpectedGetRelationshipDocument($relationship_field_name$entity);
    $expected_cacheability = (new CacheableMetadata())
      ->addCacheTags(['http_response'])
      ->addCacheContexts([
        
return AccessResult::allowedIfHasPermission($account, 'view test entity translations');
        }
      }
      if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
        return AccessResult::neutral('Unpublished entity');
      }
      return AccessResult::allowedIfHasPermission($account, 'view test entity');
    }
    elseif (in_array($operation['update', 'delete'])) {
      $access = AccessResult::allowedIfHasPermission($account, 'administer entity_test content');
      if (!$access->isAllowed() && $operation === 'update' && $account->hasPermission('edit own entity_test content')) {
        $access = $access->orIf(AccessResult::allowedIf($entity->getOwnerId() === $account->id()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // Access to revisions is based on labels, so access can vary by individual     // revisions, since the 'name' field can vary by revision.     $labels = explode(',', $entity->label());
    $labels = array_map('trim', $labels);
    if (in_array($operation[
      'view all revisions',
      'view revision',
    ],
          // access.           return AccessResult::forbidden();
        }
        $is_name = $field_definition->getName() === 'name';
        $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous');
        $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments');
        $anonymous_access = AccessResult::allowedIf($entity->isNew() && $account->isAnonymous() && ($anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT || $is_name) && $account->hasPermission('post comments'))
          ->cachePerPermissions()
          ->addCacheableDependency($entity)
          ->addCacheableDependency($field_definition->getConfig($commented_entity->bundle()))
          ->addCacheableDependency($commented_entity);
        return $admin_access->orIf($anonymous_access);
      }
    }

    if ($operation == 'view') {
      // Nobody has access to the hostname.       if ($field_definition->getName() == 'hostname') {
        return AccessResult::forbidden();
      }
      // The mail field is hidden from non-admins.       if ($field_definition->getName() == 'mail') {
        return AccessResult::allowedIfHasPermission($account, 'administer comments');
      }

      elseif ($entity_display = $this->entityTypeManager->getStorage('entity_form_display')->load($entity_type_id . '.' . $bundle . '.' . $form_mode_name)) {
        $visibility = $entity_display->status();
      }

      if ($form_mode_name != 'default' && $entity_display) {
        $access->addCacheableDependency($entity_display);
      }

      if ($visibility) {
        $permission = $route->getRequirement('_field_ui_form_mode_access');
        $access = $access->orIf(AccessResult::allowedIfHasPermission($account$permission));
      }
    }
    return $access;
  }

}
/** * Provides an entity access control handler for displays. */
class EntityViewDisplayAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $entity */
    return parent::checkAccess($entity$operation$account)
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' display'));
  }

}
// Users may not contact themselves by default, hence this requires user     // granularity for caching.     $access = AccessResult::neutral()->cachePerUser();
    if ($account->id() == $contact_account->id()) {
      return $access;
    }

    // User administrators should always have access to personal contact forms.     $permission_access = AccessResult::allowedIfHasPermission($account, 'administer users');
    if ($permission_access->isAllowed()) {
      return $access->orIf($permission_access);
    }

    // If requested user has been blocked, do not allow users to contact them.     $access->addCacheableDependency($contact_account);
    if ($contact_account->isBlocked()) {
      return $access;
    }

    // Forbid access if the requested user has disabled their contact form.     $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled');
    if (isset($account_data) && !$account_data) {
      
    // - At least one module says to grant access.     $access = array_merge(
      $this->moduleHandler()->invokeAll('entity_access', [$entity$operation$account]),
      $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', [$entity$operation$account])
    );

    $return = $this->processAccessHookResults($access);

    // Also execute the default access check except when the access result is     // already forbidden, as in that case, it can not be anything else.     if (!$return->isForbidden()) {
      $return = $return->orIf($this->checkAccess($entity$operation$account));
    }
    $result = $this->setCache($return$cid$operation$langcode$account);
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * Determines entity access. * * We grant access to the entity if both of these conditions are met: * - No modules say to deny access. * - At least one module says to grant access. * * @param \Drupal\Core\Access\AccessResultInterface[] $access * An array of access results of the fired access hook. * * @return \Drupal\Core\Access\AccessResultInterface * The combined result of the various access checks' results. All their * cacheability metadata is merged as well. * * @see \Drupal\Core\Access\AccessResultInterface::orIf() */
Home | Imprint | This part of the site doesn't use cookies.