allowedIf example


  protected function doCheckAccess(AccountInterface $account, ConfigMapperInterface $mapper$source_language = NULL) {
    $access =
      $account->hasPermission('translate configuration') &&
      $mapper->hasSchema() &&
      $mapper->hasTranslatable() &&
      (!$source_language || !$source_language->isLocked());

    return AccessResult::allowedIf($access)->cachePerPermissions();
  }

}
switch ($operation) {
      case 'view':
        return AccessResult::allowedIfHasPermission($account, 'access shortcuts');

      case 'update':
        if ($account->hasPermission('administer shortcuts')) {
          return AccessResult::allowed()->cachePerPermissions();
        }
        if (!$account->hasPermission('access shortcuts')) {
          return AccessResult::neutral()->cachePerPermissions();
        }
        return AccessResult::allowedIf($account->hasPermission('customize shortcut links') && $entity == shortcut_current_displayed_set($account))->cachePerPermissions()->addCacheableDependency($entity);

      case 'delete':
        return AccessResult::allowedIf($account->hasPermission('administer shortcuts') && $entity->id() != 'default')->cachePerPermissions();

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

  /** * {@inheritdoc} */
case 'create':
          /** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
          $handler = $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'translation');
          $translations = $entity->getTranslationLanguages();
          $languages = $this->languageManager->getLanguages();
          $source_language = $this->languageManager->getLanguage($source) ?: $entity->language();
          $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
          $is_new_translation = ($source_language->getId() != $target_language->getId()
            && isset($languages[$source_language->getId()])
            && isset($languages[$target_language->getId()])
            && !isset($translations[$target_language->getId()]));
          return AccessResult::allowedIf($is_new_translation)->cachePerPermissions()->addCacheableDependency($entity)
            ->andIf($handler->getTranslationAccess($entity$operation));

        case 'delete':
          // @todo Remove this in https://www.drupal.org/node/2945956.           /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
          $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
          $access = $this->checkAccess($entity$language$operation);
          return $delete_access->andIf($access);

        case 'update':
          return $this->checkAccess($entity$language$operation);
      }
/** * {@inheritdoc} */
  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',
      ])),
      

  public function checkAccess(AccountInterface $account) {
    // The access result is uncacheable because it is just limiting access to     // the migrate UI which is not worth caching.     return AccessResultAllowed::allowedIf((int) $account->id() === 1)->mergeCacheMaxAge(0);
  }

}
// Grants only support these operations.     if (!in_array($operation['view', 'update', 'delete'])) {
      return AccessResult::neutral();
    }

    // If no module implements the hook or the node does not have an id there is     // no point in querying the database for access grants.     if (!$this->moduleHandler->hasImplementations('node_grants') || !$node->id()) {
      // Return the equivalent of the default grant, defined by       // self::writeDefault().       if ($operation === 'view') {
        return AccessResult::allowedIf($node->isPublished());
      }
      else {
        return AccessResult::neutral();
      }
    }

    // Check the database for potential access grants.     $query = $this->database->select('node_access');
    $query->addExpression('1');
    // Only interested for granting in the current operation.     $query->condition('grant_' . $operation, 1, '>=');
    
      // grants are already marked as uncacheable in the node grant storage.       // @see \Drupal\node\NodeGrantDatabaseStorage::access()       $access_result->addCacheableDependency($node);
    }
    return $access_result;
  }

  /** * {@inheritdoc} */
  protected function checkCreateAccess(AccountInterface $account, array $context$entity_bundle = NULL) {
    return AccessResult::allowedIf($account->hasPermission('create ' . $entity_bundle . ' content'))->cachePerPermissions();
  }

  /** * {@inheritdoc} */
  protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
    // Only users with the administer nodes permission can edit administrative     // fields.     $administrative_fields = ['uid', 'status', 'created', 'promote', 'sticky'];
    if ($operation == 'edit' && in_array($field_definition->getName()$administrative_fields, TRUE)) {
      return AccessResult::allowedIfHasPermission($account, 'administer nodes');
    }

  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. */
/** * {@inheritdoc} */
  public function getThirdPartyProviders() {
    return $this->getDisplay()->getThirdPartyProviders();
  }

  /** * {@inheritdoc} */
  public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowedIf($this->isLayoutBuilderEnabled())->addCacheableDependency($this);
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * {@inheritdoc} */
  public function isApplicable(RefinableCacheableDependencyInterface $cacheability) {
    $cacheability->addCacheableDependency($this);
    return $this->isLayoutBuilderEnabled();
  }

  

  public static function allowedIfHasPermission(AccountInterface $account$permission) {
    $access_result = static::allowedIf($account->hasPermission($permission))->addCacheContexts(['user.permissions']);

    if ($access_result instanceof AccessResultReasonInterface) {
      $access_result->setReason("The '$permission' permission is required.");
    }
    return $access_result;
  }

  /** * Creates an allowed access result if the permissions are present, neutral otherwise. * * Checks the permission and adds a 'user.permissions' cache contexts. * * @param \Drupal\Core\Session\AccountInterface $account * The account for which to check permissions. * @param array $permissions * The permissions to check. * @param string $conjunction * (optional) 'AND' if all permissions are required, 'OR' in case just one. * Defaults to 'AND' * * @return \Drupal\Core\Access\AccessResult * If the account has the permissions, isAllowed() will be TRUE, otherwise * isNeutral() will be TRUE. */

  public function access(AccountInterface $account, Route $route) {
    $required_status = filter_var($route->getRequirement('_user_is_logged_in'), FILTER_VALIDATE_BOOLEAN);
    $actual_status = $account->isAuthenticated();
    $access_result = AccessResult::allowedIf($required_status === $actual_status)->addCacheContexts(['user.roles:authenticated']);
    if (!$access_result->isAllowed()) {
      $access_result->setReason($required_status === TRUE ? 'This route can only be accessed by authenticated users.' : 'This route can only be accessed by anonymous users.');
    }
    return $access_result;
  }

}

class CommentAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\comment\CommentInterface|\Drupal\user\EntityOwnerInterface $entity */

    $comment_admin = $account->hasPermission('administer comments');
    if ($operation == 'approve') {
      return AccessResult::allowedIf($comment_admin && !$entity->isPublished())
        ->cachePerPermissions()
        ->addCacheableDependency($entity);
    }

    if ($comment_admin) {
      $access = AccessResult::allowed()->cachePerPermissions();
      return ($operation != 'view') ? $access : $access->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
    }

    switch ($operation) {
      case 'view':
        
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'view':
        return parent::checkAccess($entity$operation$account);

      case 'update':
        /** @var \Drupal\Core\Language\LanguageInterface $entity */
        return AccessResult::allowedIf(!$entity->isLocked())->addCacheableDependency($entity)
          ->andIf(parent::checkAccess($entity$operation$account));

      case 'delete':
        /** @var \Drupal\Core\Language\LanguageInterface $entity */
        return AccessResult::allowedIf(!$entity->isLocked())->addCacheableDependency($entity)
          ->andIf(AccessResult::allowedIf(!$entity->isDefault())->addCacheableDependency($entity))
          ->andIf(parent::checkAccess($entity$operation$account));

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

  protected function bypassAccessResult(AccountInterface $account) {
    // This approach assumes that the current "global" active workspace is     // correct, i.e. if you're "in" a given workspace then you get ALL THE PERMS     // to ALL THE THINGS! That's why this is a dangerous permission.     $active_workspace = $this->workspaceManager->getActiveWorkspace();

    return AccessResult::allowedIf($active_workspace->getOwnerId() == $account->id())->cachePerUser()->addCacheableDependency($active_workspace)
      ->andIf(AccessResult::allowedIfHasPermission($account, 'bypass entity access own workspace'));
  }

}
class TestController {

  public function accessAllow() {
    return AccessResult::allowed();
  }

  public function accessDeny() {
    return AccessResult::neutral();
  }

  public function accessParameter($parameter) {
    return AccessResult::allowedIf($parameter == 'TRUE');
  }

}
Home | Imprint | This part of the site doesn't use cookies.