getReason example

$resource_type = $this->resourceType;
    $resource_data = array_reduce($include_pathsfunction D$data$path) use ($request_options$resource_type) {
      $field_names = explode('.', $path);
      /** @var \Drupal\Core\Entity\EntityInterface $entity */
      $entity = $this->entity;
      $collected_responses = [];
      foreach ($field_names as $public_field_name) {
        $resource_type = $this->container->get('jsonapi.resource_type.repository')->get($entity->getEntityTypeId()$entity->bundle());
        $field_name = $resource_type->getInternalName($public_field_name);
        $field_access = static::entityFieldAccess($entity$field_name, 'view', $this->account);
        if (!$field_access->isAllowed()) {
          if (!$entity->access('view') && $entity->access('view label') && $field_access instanceof AccessResultReasonInterface && empty($field_access->getReason())) {
            $field_access->setReason("The user only has authorization for the 'view label' operation.");
          }
          $via_link = Url::fromRoute(
            sprintf('jsonapi.%s.%s.related', $entity->getEntityTypeId() . '--' . $entity->bundle()$public_field_name),
            ['entity' => $entity->uuid()]
          );
          $collected_responses[] = static::getAccessDeniedResponse($entity$field_access$via_link$field_name, 'The current user is not allowed to view this relationship.', $field_name);
          break;
        }
        if ($target_entity = $entity->{$field_name}->entity) {
          $target_access = static::entityAccess($target_entity, 'view', $this->account);
          
if (\in_array($payload['event']['accepted', 'rejected', 'delivered', 'failed', 'blocked'], true)) {
            $name = match ($payload['event']) {
                'accepted' => MailerDeliveryEvent::RECEIVED,
                'rejected' => MailerDeliveryEvent::DROPPED,
                'delivered' => MailerDeliveryEvent::DELIVERED,
                'blocked' => MailerDeliveryEvent::DROPPED,
                'failed' => $this->matchFailedEvent($payload),
            };

            $event = new MailerDeliveryEvent($name$payload['id']$payload);
            // reason is only available on failed messages             $event->setReason($this->getReason($payload));
        } else {
            $name = match ($payload['event']) {
                'clicked' => MailerEngagementEvent::CLICK,
                'unsubscribed' => MailerEngagementEvent::UNSUBSCRIBE,
                'opened' => MailerEngagementEvent::OPEN,
                'complained' => MailerEngagementEvent::SPAM,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['event'])),
            };
            $event = new MailerEngagementEvent($name$payload['id']$payload);
        }
        if (!$date = \DateTimeImmutable::createFromFormat('U.u', $payload['timestamp'])) {
            
class AccessResultForbiddenTest extends UnitTestCase {

  /** * Tests the construction of an AccessResultForbidden object. * * @covers ::__construct * @covers ::getReason */
  public function testConstruction() {

    $a = new AccessResultForbidden();
    $this->assertEquals(NULL, $a->getReason());

    $reason = $this->getRandomGenerator()->string();
    $b = new AccessResultForbidden($reason);
    $this->assertEquals($reason$b->getReason());
  }

  /** * Tests setReason() * * @covers ::setReason */
  
if ($resource_type = $route_match->getParameter(Routes::RESOURCE_TYPE_KEY)) {
      assert($resource_type instanceof ResourceType);
      $entity = $route_match->getParameter('entity');
      $internal_name = $resource_type->getInternalName($relationship_field_name);
      if ($entity instanceof FieldableEntityInterface && $entity->hasField($internal_name)) {
        $entity_access = $this->entityAccessChecker->checkEntityAccess($entity$entity_operation$account);
        $field_access = $entity->get($internal_name)->access($field_operation$account, TRUE);
        // Ensure that access is respected for different entity revisions.         $access_result = $entity_access->andIf($field_access);
        if (!$access_result->isAllowed()) {
          $reason = "The current user is not allowed to {$field_operation} this relationship.";
          $access_reason = $access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : NULL;
          $detailed_reason = empty($access_reason) ? $reason : $reason . " {$access_reason}";
          $access_result->setReason($detailed_reason);
        }
        return $access_result;
      }
    }
    return AccessResult::neutral();
  }

}
    // globally cacheable (no cache contexts). B is cacheable per role. If we     // don't have merging case 3, then A->orIf(B) will be globally cacheable,     // which means that even if a user of a different role logs in, the     // cached access result will be used, even though for that other role, B     // is forbidden!     if ($this->isForbidden() || $other->isForbidden()) {
      $result = static::forbidden();
      if (!$this->isForbidden() || ($this->getCacheMaxAge() === 0 && $other->isForbidden())) {
        $merge_other = TRUE;
      }

      if ($this->isForbidden() && $this instanceof AccessResultReasonInterface && $this->getReason() !== '') {
        $result->setReason($this->getReason());
      }
      elseif ($other->isForbidden() && $other instanceof AccessResultReasonInterface && $other->getReason() !== '') {
        $result->setReason($other->getReason());
      }
    }
    elseif ($this->isAllowed() || $other->isAllowed()) {
      $result = static::allowed();
      if (!$this->isAllowed() || ($this->getCacheMaxAge() === 0 && $other->isAllowed()) || ($this->getCacheMaxAge() !== 0 && $other instanceof CacheableDependencyInterface && $other->getCacheMaxAge() !== 0)) {
        $merge_other = TRUE;
      }
    }

  public function checkEntityAccess(EntityInterface $entity$operation, AccountInterface $account) {
    $access = $entity->access($operation$account, TRUE);
    if ($entity->getEntityType()->isRevisionable()) {
      $access = AccessResult::neutral()->addCacheContexts(['url.query_args:' . JsonApiSpec::VERSION_QUERY_PARAMETER])->orIf($access);
      if (!$entity->isDefaultRevision()) {
        assert($operation === 'view', 'JSON:API does not yet support mutable operations on revisions.');
        $revision_access = $this->checkRevisionViewAccess($entity$account);
        $access = $access->andIf($revision_access);
        // The revision access reason should trump the primary access reason.         if (!$access->isAllowed()) {
          $reason = $access instanceof AccessResultReasonInterface ? $access->getReason() : '';
          $access->setReason(trim('The user does not have access to the requested version. ' . $reason));
        }
      }
    }
    return $access;
  }

  /** * Checks access to the given revision entity. * * This should only be called for non-default revisions. * * There is no standardized API for revision access checking in Drupal core * and this method shims that missing API. * * @param \Drupal\Core\Entity\EntityInterface $entity * The revised entity for which to check access. * @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. */
$resource->set($relationship_field_name[]);
      $this->assertResourceResponse(204, NULL, $response);
      $resource->set($relationship_field_name[]);
      $expected_document = $this->getExpectedGetRelationshipDocument($relationship_field_name$resource);
      $response = $this->request('GET', $url$request_options);
      $this->assertSameDocument($expected_document, Json::decode((string) $response->getBody()));
    }
    else {
      $request_options[RequestOptions::BODY] = Json::encode(['data' => [$target_identifier]]);
      $response = $this->request('POST', $url$request_options);
      $message = 'The current user is not allowed to edit this relationship.';
      $message .= ($reason = $update_access->getReason()) ? ' ' . $reason : '';
      $this->assertResourceErrorResponse(403, $message$url$response, FALSE);
      $response = $this->request('PATCH', $url$request_options);
      $this->assertResourceErrorResponse(403, $message$url$response, FALSE);
      $response = $this->request('DELETE', $url$request_options);
      $this->assertResourceErrorResponse(403, $message$url$response, FALSE);
    }

    // Remove the test entities that were created.     $resource->delete();
    $target_resource->delete();
  }

  
public function testSetAccessDependency($use_set_first) {
    $testRefinable = new RefinableDependentAccessTraitTestClass();

    if ($use_set_first) {
      $testRefinable->setAccessDependency($this->forbidden);
    }
    else {
      $testRefinable->addAccessDependency($this->forbidden);
    }
    $accessResult = $testRefinable->getAccessDependency()->access('view', $this->account, TRUE);
    $this->assertTrue($accessResult->isForbidden());
    $this->assertEquals('Because I said so', $accessResult->getReason());

    // Calling setAccessDependency() replaces the existing dependency.     $testRefinable->setAccessDependency($this->neutral);
    $dependency = $testRefinable->getAccessDependency();
    $this->assertNotInstanceOf(AccessGroupAnd::class$dependency);
    $accessResult = $dependency->access('view', $this->account, TRUE);
    $this->assertTrue($accessResult->isNeutral());
    $this->assertEquals('I have no opinion', $accessResult->getReason());
  }

  /** * Tests merging a new dependency with existing non-group access dependency. * * @dataProvider providerTestSetFirst */
    // 'view own unpublished media' permission.     $this->grantPermissions($role['view media']);
    $this->drupalGet('media/' . $user_media->id());
    $this->assertNoCacheContext('user');
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);
    $user_media->setUnpublished()->save();
    $this->drupalGet('media/' . $user_media->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(403);
    $access_result = $user_media->access('view', NULL, TRUE);
    $this->assertSame("The user must be the owner and the 'view own unpublished media' permission is required when the media item is unpublished.", $access_result->getReason());
    $this->grantPermissions($role['view own unpublished media']);
    $this->drupalGet('media/' . $user_media->id());
    $this->assertCacheContext('user');
    $assert_session->statusCodeEquals(200);

    // Test 'create media' permission.     $this->drupalGet('media/add/' . $media_type->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(403);
    $permissions = ['create media'];
    $this->grantPermissions($role$permissions);
    
protected function checkAccess(Request $request) {
    // The cacheability (if any) of this request's access check result must be     // applied to the response.     $access_result = $this->accessManager->checkRequest($request$this->account, TRUE);
    // Allow a master request to set the access result for a subrequest: if an     // access result attribute is already set, don't overwrite it.     if (!$request->attributes->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
      $request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
    }
    if (!$access_result->isAllowed()) {
      if ($access_result instanceof CacheableDependencyInterface && $request->isMethodCacheable()) {
        throw new CacheableAccessDeniedHttpException($access_result$access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
      else {
        throw new AccessDeniedHttpException($access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
    }
  }

  /** * {@inheritdoc} */
  public function getRouteCollection(): RouteCollection {
    
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
    $field_definition = $field_definitions[$field_name];
    if ($field_definition->getSetting('target_type') !== 'file') {
      throw new AccessDeniedHttpException(sprintf('"%s" is not a file field', $field_name));
    }

    $entity_access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
    $bundle = $this->entityTypeManager->getDefinition($entity_type_id)->hasKey('bundle') ? $bundle : NULL;
    $access_result = $entity_access_control_handler->createAccess($bundle, NULL, [], TRUE)
      ->andIf($entity_access_control_handler->fieldAccess('edit', $field_definition, NULL, NULL, TRUE));
    if (!$access_result->isAllowed()) {
      throw new AccessDeniedHttpException($access_result->getReason());
    }

    return $field_definition;
  }

  /** * Validates the file. * * @todo this method is unused in this class because file validation needs to * be split up in 2 steps in ::post(). Add a deprecation notice as soon as a * central core file upload service can be used in this class. * See https://www.drupal.org/project/drupal/issues/2940383 * * @param \Drupal\file\FileInterface $file * The file entity to validate. * @param array $validators * An array of upload validators to pass to file_validate(). * * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException * Thrown when there are file validation errors. */

class AccessResultNeutralTest extends UnitTestCase {

  /** * Tests the construction of an AccessResultForbidden object. * * @covers ::__construct * @covers ::getReason */
  public function testConstruction() {
    $a = new AccessResultNeutral();
    $this->assertEquals('', $a->getReason());

    $reason = $this->getRandomGenerator()->string();
    $b = new AccessResultNeutral($reason);
    $this->assertEquals($reason$b->getReason());
  }

  /** * Tests setReason() * * @covers ::setReason */
  

  public function post(EntityInterface $entity = NULL) {
    if ($entity == NULL) {
      throw new BadRequestHttpException('No entity content received.');
    }

    $entity_access = $entity->access('create', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException($entity_access->getReason() ?: $this->generateFallbackAccessDeniedMessage($entity, 'create'));
    }
    $definition = $this->getPluginDefinition();
    // Verify that the deserialized entity is of the type that we expect to     // prevent security issues.     if ($entity->getEntityTypeId() != $definition['entity_type']) {
      throw new BadRequestHttpException('Invalid entity type');
    }
    // POSTed entities must not have an ID set, because we always want to create     // new entities here.     if (!$entity->isNew()) {
      throw new BadRequestHttpException('Only new entities can be created');
    }
      $resource_types = array_filter($resource_typesfunction DResourceType $resource_type) use ($candidate_definitions) {
        return isset($candidate_definitions[$resource_type->getTypeName()]);
      });

      // Check access to execute a query for each field per resource type since       // field definitions are bundle-specific.       foreach ($resource_types as $resource_type) {
        $field_access = $this->getFieldAccess($resource_type$field_name);
        $cacheability->addCacheableDependency($field_access);
        if (!$field_access->isAllowed()) {
          $message = sprintf('The current user is not authorized to filter by the `%s` field, given in the path `%s`.', $field_nameimplode('.', $reference_breadcrumbs));
          if ($field_access instanceof AccessResultReasonInterface && ($reason = $field_access->getReason()) && !empty($reason)) {
            $message .= ' ' . $reason;
          }
          throw new CacheableAccessDeniedHttpException($cacheability$message);
        }
      }

      // Get all of the referenceable resource types.       $resource_types = $this->getRelatableResourceTypes($resource_types$candidate_definitions);

      $at_least_one_entity_reference_field = FALSE;
      $candidate_property_names = array_unique(NestedArray::mergeDeepArray(array_map(function DFieldItemDataDefinitionInterface $definition) use (&$at_least_one_entity_reference_field) {
        

  protected function assertTermAccess(TermInterface $term, string $access_operation, bool $access_allowed, string $access_reason = ''): void {
    $access_result = $term->access($access_operation, NULL, TRUE);
    $this->assertSame($access_allowed$access_result->isAllowed());

    if ($access_reason) {
      $this->assertSame($access_reason$access_result->getReason());
    }
  }

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