andIf example

case 'update':
        // Users can always edit their own account.         $access_result = AccessResult::allowedIf($account->id() == $entity->id())->cachePerUser();
        if (!$access_result->isAllowed() && $access_result instanceof AccessResultReasonInterface) {
          $access_result->setReason("Users can only update their own account, unless they have the 'administer users' permission.");
        }
        return $access_result;

      case 'delete':
        // Users with 'cancel account' permission can cancel their own account.         return AccessResult::allowedIfHasPermission($account, 'cancel account')
          ->andIf(AccessResult::allowedIf($account->id() == $entity->id())->cachePerUser());
    }

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

  /** * {@inheritdoc} */
  protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
    // Fields that are not implicitly allowed to administrative users.
$field_definition->getTargetEntityTypeId() === $entity->getEntityTypeId() &&
      // Base fields do not have target bundles.       (is_null($field_definition->getTargetBundle()) || $field_definition->getTargetBundle() === $entity->bundle())
    );
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_access_control_handler = $entity_type_manager->getAccessControlHandler($field_definition->getTargetEntityTypeId());
    $bundle = $entity_type_manager->getDefinition($field_definition->getTargetEntityTypeId())->hasKey('bundle') ? $field_definition->getTargetBundle() : NULL;
    $entity_access_result = $entity
      ? $entity_access_control_handler->access($entity, 'update', $account, TRUE)
      : $entity_access_control_handler->createAccess($bundle$account[], TRUE);
    $field_access_result = $entity_access_control_handler->fieldAccess('edit', $field_definition, NULL, NULL, TRUE);
    return $entity_access_result->andIf($field_access_result);
  }

  /** * Streams file upload data to temporary file and moves to file destination. * * @return string * The temp file path. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * Thrown when input data cannot be read, the temporary file cannot be * opened, or the temporary file cannot be written. */
/** @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);
      }
    }
if (!$account->hasPermission('administer menu')) {
          return AccessResult::neutral("The 'administer menu' permission is required.")->cachePerPermissions();
        }
        else {
          // Assume that access is allowed.           $access = AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
          /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
          // If the link is routed determine whether the user has access unless           // they have the 'link to any page' permission.           if (!$account->hasPermission('link to any page') && ($url_object = $entity->getUrlObject()) && $url_object->isRouted()) {
            $link_access = $this->accessManager->checkNamedRoute($url_object->getRouteName()$url_object->getRouteParameters()$account, TRUE);
            $access = $access->andIf($link_access);
          }
          return $access;
        }

      case 'delete':
        return AccessResult::allowedIfHasPermission($account, 'administer menu')
          ->andIf(AccessResult::allowedIf(!$entity->isNew())->addCacheableDependency($entity));

      default:
        return parent::checkAccess($entity$operation$account);
    }
  }
        if (!$entity->isNew()) {
          return $return_as_object ? AccessResult::forbidden('The entity UUID cannot be changed.')->addCacheableDependency($entity) : FALSE;
        }
      }
    }

    // Get the default access restriction as specified by the access control     // handler.     $entity_default = $this->checkFieldAccess($operation$field_definition$account$items);

    // Combine default access, denying access wins.     $default = $default->andIf($entity_default);

    // Invoke hook and collect grants/denies for field access from other     // modules.     $grants = [];
    $this->moduleHandler()->invokeAllWith(
      'entity_field_access',
      function Dcallable $hook, string $module) use ($operation$field_definition$account$items, &$grants) {
        $grants[] = [$module => $hook($operation$field_definition$account$items)];
      }
    );
    // Our default access flag is masked under the ':default' key.

  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['keywords'] = Tags::explode($form_state->getValue('keywords'));
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\comment\CommentInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}
$dependency = $entity->getAccessDependency();
      if (empty($dependency)) {
        // If an access dependency has not been set let modules set one.         $event = new BlockContentGetDependencyEvent($entity);
        $this->eventDispatcher->dispatch($event, BlockContentEvents::BLOCK_CONTENT_GET_DEPENDENCY);
        $dependency = $event->getAccessDependency();
        if (empty($dependency)) {
          return AccessResult::forbidden("Non-reusable blocks must set an access dependency for access control.");
        }
      }
      /** @var \Drupal\Core\Entity\EntityInterface $dependency */
      $access = $access->andIf($dependency->access($operation$account, TRUE));
    }
    return $access;
  }

  /** * {@inheritdoc} */
  protected function checkCreateAccess(AccountInterface $account, array $context$entity_bundle = NULL) {
    return AccessResult::allowedIfHasPermissions($account[
      'create ' . $entity_bundle . ' block content',
      'access block library',
    ])
protected function blockAccess(AccountInterface $account) {
    $entity = $this->getEntity();

    // First consult the entity.     $access = $entity->access('view', $account, TRUE);
    if (!$access->isAllowed()) {
      return $access;
    }

    // Check that the entity in question has this field.     if (!$entity instanceof FieldableEntityInterface || !$entity->hasField($this->fieldName)) {
      return $access->andIf(AccessResult::forbidden());
    }

    // Check field access.     $field = $entity->get($this->fieldName);
    $access = $access->andIf($field->access('view', $account, TRUE));
    if (!$access->isAllowed()) {
      return $access;
    }

    // Check to see if the field has any values or a default value.     if ($field->isEmpty() && !$field->getFieldDefinition()->getDefaultValue($entity)) {
      
$uuid = $request->query->get('uuid');
    if (!$uuid || !Uuid::isValid($uuid)) {
      throw new BadRequestHttpException();
    }
    $media = $this->entityRepository->loadEntityByUuid('media', $uuid);
    if (!$media) {
      throw new NotFoundHttpException();
    }
    $filters = $editor->getFilterFormat()->filters();

    return AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status)
      ->andIf($media->access('view', $this->currentUser, TRUE))
      ->addCacheableDependency($editor->getFilterFormat());
  }

  /** * Gets the name of an image media item's source field. * * @param \Drupal\media\MediaInterface $media * The media item being embedded. * * @return string|null * The name of the image source field configured for the media item, or * NULL if the source field is not an image field. */
$entity->setUnpublished()->save();
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $key = $object->getEntityType()->getKey('published');

    /** @var \Drupal\Core\Entity\EntityInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->$key->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

  public function checkAccess(MediaLibraryState $state, AccountInterface $account) {
    $filter_format_id = $state->getOpenerParameters()['filter_format_id'];
    $filter_format = $this->filterStorage->load($filter_format_id);
    if (empty($filter_format)) {
      return AccessResult::forbidden()
        ->addCacheTags(['filter_format_list'])
        ->setReason("The text format '$filter_format_id' could not be loaded.");
    }
    $filters = $filter_format->filters();
    return $filter_format->access('use', $account, TRUE)
      ->andIf(AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status === TRUE));
  }

  /** * {@inheritdoc} */
  public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
    $selected_media = $this->mediaStorage->load(reset($selected_ids));

    $response = new AjaxResponse();
    $values = [
      'attributes' => [
        

  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['keywords'] = Tags::explode($form_state->getValue('keywords'));
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $access = $object->access('update', $account, TRUE)
      ->andIf($object->status->access('edit', $account, TRUE));

    return $return_as_object ? $access : $access->isAllowed();
  }

}

  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'));
  }

}
public function addDependency(AccessibleInterface $dependency) {
    $this->dependencies[] = $dependency;
    return $this;
  }

  /** * {@inheritdoc} */
  public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $access_result = AccessResult::neutral();
    foreach (array_slice($this->dependencies, 1) as $dependency) {
      $access_result = $access_result->andIf($dependency->access($operation$account, TRUE));
    }
    return $return_as_object ? $access_result : $access_result->isAllowed();
  }

  /** * {@inheritdoc} */
  public function getDependencies() {
    return $this->dependencies;
  }

}
// Filter out checks which require the incoming request.     if (!isset($request)) {
      $checks = array_diff($checks$this->checkProvider->getChecksNeedRequest());
    }

    $result = AccessResult::neutral();
    if (!empty($checks)) {
      $arguments_resolver = $this->argumentsResolverFactory->getArgumentsResolver($route_match$account$request);
      $result = AccessResult::allowed();
      foreach ($checks as $service_id) {
        $result = $result->andIf($this->performCheck($service_id$arguments_resolver));
      }
    }
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * Performs the specified access check. * * @param string $service_id * The access check service ID to use. * @param \Drupal\Component\Utility\ArgumentsResolverInterface $arguments_resolver * The parametrized arguments resolver instance. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. * * @throws \Drupal\Core\Access\AccessException * Thrown when the access check returns an invalid value. */
Home | Imprint | This part of the site doesn't use cookies.