LinkCollection example


  protected function normalize(EntityInterface $entity, Url $url) {
    // Don't use cached normalizations in tests.     $this->container->get('cache.jsonapi_normalizations')->deleteAll();

    $self_link = new Link(new CacheableMetadata()$url, 'self');
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->getByTypeName(static::$resourceTypeName);
    $doc = new JsonApiDocumentTopLevel(new ResourceObjectData([ResourceObject::createFromEntity($resource_type$entity)], 1)new NullIncludedData()new LinkCollection(['self' => $self_link]));
    return $this->serializer->normalize($doc, 'api_json', [
      'resource_type' => $resource_type,
      'account' => $this->account,
    ])->getNormalization();
  }

  /** * Creates the entity to be tested. * * @return \Drupal\Core\Entity\EntityInterface * The entity to be tested. */

  public static function createFromEntity(ResourceType $resource_type, EntityInterface $entity, LinkCollection $links = NULL) {
    return new static(
      $entity,
      $resource_type,
      $entity->uuid(),
      $resource_type->isVersionable() && $entity instanceof RevisionableInterface ? $entity->getRevisionId() : NULL,
      static::extractFieldsFromEntity($resource_type$entity),
      static::buildLinksFromEntity($resource_type$entity$links ?: new LinkCollection([])),
      $entity->language()
    );
  }

  /** * Whether the resource object has the given field. * * @param string $public_field_name * A public field name. * * @return bool * TRUE if the resource object has the given field, FALSE otherwise. */
        // not actually be serialized since the rel is omitted if it matches the         // link key; because of that no client can rely on it. Once an extension         // relation type is implemented for links to a collection, that should         // be used instead. Unfortunately, the `collection` link relation type         // would not be semantically correct since it would imply that the         // entrypoint is a *member* of the link target.         // @todo: implement an extension relation type to signal that this is a primary collection resource.         $link_relation_type = $resource_type->getTypeName();
        return $carry->withLink($resource_type->getTypeName()new Link(new CacheableMetadata()$url$link_relation_type));
      }
      return $carry;
    }new LinkCollection(['self' => $self_link]));

    $meta = [];
    if ($this->user->isAuthenticated()) {
      $current_user_uuid = $this->entityTypeManager()->getStorage('user')->load($this->user->id())->uuid();
      $meta['links']['me'] = ['meta' => ['id' => $current_user_uuid]];
      $cacheability->addCacheContexts(['user']);
      try {
        $me_url = Url::fromRoute(
          'jsonapi.user--user.individual',
          ['entity' => $current_user_uuid]
        )
          

  protected function buildWrappedResponse(TopLevelDataInterface $data, Request $request, IncludedData $includes$response_code = 200, array $headers = [], LinkCollection $links = NULL, array $meta = []) {
    $links = ($links ?: new LinkCollection([]));
    if (!$links->hasLinkWithKey('self')) {
      $self_link = new Link(new CacheableMetadata(), self::getRequestLink($request), 'self');
      $links = $links->withLink('self', $self_link);
    }
    $document = new JsonApiDocumentTopLevel($data$includes$links$meta);
    if (!$request->isMethodCacheable()) {
      return new ResourceResponse($document$response_code$headers);
    }
    $response = new CacheableResourceResponse($document$response_code$headers);
    $cacheability = (new CacheableMetadata())->addCacheContexts([
      // Make sure that different sparse fieldsets are cached differently.
public function onMaintenanceModeRequest(RequestEvent $event) {
    $request = $event->getRequest();

    if ($request->getRequestFormat() !== 'api_json') {
      return;
    }
    // Retry-After will be random within a range defined in jsonapi settings.     // The goals are to keep it short and to reduce the thundering herd problem.     $header_settings = $this->config->get('jsonapi.settings')->get('maintenance_header_retry_seconds');
    $retry_after_time = rand($header_settings['min']$header_settings['max']);
    $http_exception = new HttpException(503, $this->maintenanceMode->getSiteMaintenanceMessage());
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$http_exception])new NullIncludedData()new LinkCollection([]));
    $response = new ResourceResponse($document$http_exception->getStatusCode()[
      'Content-Type' => 'application/vnd.api+json',
      'Retry-After' => $retry_after_time,
    ]);
    // Calling RequestEvent::setResponse() also stops propagation of event.     $event->setResponse($response);
  }

}


    $this->setEventResponse($event$exception->getStatusCode());
  }

  /** * {@inheritdoc} */
  protected function setEventResponse(ExceptionEvent $event$status) {
    /** @var \Symfony\Component\HttpKernel\Exception\HttpException $exception */
    $exception = $event->getThrowable();
    $document = new JsonApiDocumentTopLevel(new ErrorCollection([$exception])new NullIncludedData()new LinkCollection([]));
    if ($event->getRequest()->isMethodCacheable()) {
      $response = new CacheableResourceResponse($document$exception->getStatusCode()$exception->getHeaders());
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new ResourceResponse($document$exception->getStatusCode()$exception->getHeaders());
    }
    $event->setResponse($response);
  }

  /** * Check if the error should be formatted using JSON:API. * * The JSON:API format is supported if the format is explicitly set or the * request is for a known JSON:API route. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $exception_event * The exception event. * * @return bool * TRUE if it needs to be formatted using JSON:API. FALSE otherwise. */
// Set the user IDs to something higher than 1 so these users cannot be     // mistaken for the site admin.     $this->testUsers[] = $this->createUser([], NULL, FALSE, ['uid' => 2]);
    $this->testUsers[] = $this->createUser([], NULL, FALSE, ['uid' => 3]);
    $this->serializer = $this->container->get('jsonapi.serializer');
  }

  /** * Tests the link collection normalizer. */
  public function testNormalize() {
    $link_context = new ResourceObject(new CacheableMetadata()new ResourceType('n/a', 'n/a', 'n/a'), 'n/a', NULL, []new LinkCollection([]));
    $link_collection = (new LinkCollection([]))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Most viewed']))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Top rated']))
      ->withContext($link_context);
    // Create the SUT.     $normalized = $this->getNormalizer()->normalize($link_collection)->getNormalization();
    $this->assertIsArray($normalized);
    foreach (array_keys($normalized) as $key) {
      $this->assertStringStartsWith('related', $key);
    }
    $this->assertSame([
      [

  public static function createFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links = NULL, array $meta = []) {
    $context_resource_type = $context->getResourceType();
    $resource_field = $context_resource_type->getFieldByInternalName($field->getName());
    return new static(
      $resource_field->getPublicName(),
      new RelationshipData(ResourceIdentifier::toResourceIdentifiers($field)$resource_field->hasOne() ? 1 : -1),
      static::buildLinkCollectionFromEntityReferenceField($context$field$links ?: new LinkCollection([])),
      $meta,
      $context
    );
  }

  /** * Gets context resource object of the relationship. * * @return \Drupal\jsonapi\JsonApiResource\ResourceObject * The context ResourceObject. * * @see \Drupal\jsonapi\JsonApiResource\Relationship::$context */

  public function testNormalize() {
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->get('node', 'article');

    $resource_object = ResourceObject::createFromEntity($resource_type$this->node);
    $includes = $this->includeResolver->resolve($resource_object, 'uid,field_tags,field_image');

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)$includesnew LinkCollection([])),
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
          'sparse_fieldset' => [
            'node--article' => [
              'title',
              'node_type',
              'uid',
              'field_tags',
              'field_image',
            ],

  public function filter(callable $f) {
    $links = iterator_to_array($this);
    $filtered = array_reduce(array_keys($links)function D$filtered$key) use ($links$f) {
      if ($f($key$links[$key]$this->context)) {
        $filtered[$key] = $links[$key];
      }
      return $filtered;
    }[]);
    return new LinkCollection($filtered$this->context);
  }

  /** * Merges two LinkCollections. * * @param \Drupal\jsonapi\JsonApiResource\LinkCollection $a * The first link collection. * @param \Drupal\jsonapi\JsonApiResource\LinkCollection $b * The second link collection. * * @return \Drupal\jsonapi\JsonApiResource\LinkCollection * A new LinkCollection with the links of both inputs. */
/** * {@inheritdoc} */
  public static function createFromEntity(ResourceType $resource_type, EntityInterface $entity, LinkCollection $links = NULL) {
    $resource_object = new static(
      $entity,
      $resource_type,
      $entity->uuid(),
      $resource_type->isVersionable() && $entity instanceof RevisionableInterface ? $entity->getRevisionId() : NULL,
      static::extractFieldsFromEntity($resource_type$entity),
      static::buildLinksFromEntity($resource_type$entity$links ?: new LinkCollection([]))
    );
    $resource_object->setEntity($entity);
    return $resource_object;
  }

  /** * Gets the decorated entity. * * @return \Drupal\Core\Entity\EntityInterface * The label for which to only normalize its label. */
  
$violations = $file;
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }iterator_to_array($violations)));
      throw new UnprocessableEntityHttpException($message);
    }

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $self_link = new Link(new CacheableMetadata(), Url::fromRoute('jsonapi.file--file.individual', ['entity' => $file->uuid()]), 'self');
    /* $self_link = new Link(new CacheableMetadata(), $this->entity->toUrl('jsonapi'), ['self']); */
    $links = new LinkCollection(['self' => $self_link]);

    $relatable_resource_types = $resource_type->getRelatableResourceTypesByField($resource_type->getPublicName($file_field_name));
    $file_resource_type = reset($relatable_resource_types);
    $resource_object = ResourceObject::createFromEntity($file_resource_type$file);
    return new ResourceResponse(new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1)new NullIncludedData()$links), 201, []);
  }

  /** * Ensures that the given account is allowed to upload a file. * * @param \Drupal\Core\Session\AccountInterface $account * The account for which access should be checked. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field for which the file is to be uploaded. * @param \Drupal\Core\Entity\FieldableEntityInterface|null $entity * The entity, if one exists, for which the file is to be uploaded. */
Home | Imprint | This part of the site doesn't use cookies.