public function ResourceResponseFactory::create in JSON:API Resources 8
Builds a response with the appropriate wrapped document.
Parameters
\Drupal\jsonapi\JsonApiResource\ResourceObjectData $data: The data to wrap.
\Symfony\Component\HttpFoundation\Request $request: The request object.
int $response_code: The response code.
array $headers: An array of response headers.
\Drupal\jsonapi\JsonApiResource\LinkCollection $links: The URLs to which to link. A 'self' link is added automatically.
array $meta: (optional) The top-level metadata.
Return value
\Drupal\jsonapi\ResourceResponse The response.
Throws
\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
\Drupal\Component\Plugin\Exception\PluginNotFoundException
File
- src/
Unstable/ ResourceResponseFactory.php, line 67
Class
- ResourceResponseFactory
- Creates JSON:API response objects.
Namespace
Drupal\jsonapi_resources\UnstableCode
public function create(ResourceObjectData $data, Request $request, $response_code = 200, array $headers = [], LinkCollection $links = NULL, array $meta = []) {
$links = $links ?: new LinkCollection([]);
if (!$links
->hasLinkWithKey('self')) {
$self_link = new Link(new CacheableMetadata(), Url::fromUri($request
->getUri()), 'self');
$links = $links
->withLink('self', $self_link);
}
$includes = $this
->getIncludes($request, $data);
// \Drupal\jsonapi\ResourceResponse no longer implements
// CacheableResponseInterface in Drupal 9.1.
// Drupal\jsonapi\CacheableResourceResponse has ben added for cacheable
// responses. Keep compatibility with Drupal < 9.1.
// See https://www.drupal.org/node/3163310
$document = new JsonApiDocumentTopLevel($data, $includes, $links, $meta);
$response = class_exists('\\Drupal\\jsonapi\\CacheableResourceResponse') ? new CacheableResourceResponse($document, $response_code, $headers) : new ResourceResponse($document, $response_code, $headers);
// Make sure that different sparse fieldsets are cached differently.
$cache_contexts[] = 'url.query_args:fields';
// Make sure that different sets of includes are cached differently.
$cache_contexts[] = 'url.query_args:include';
$cacheability = (new CacheableMetadata())
->addCacheContexts($cache_contexts);
$response
->addCacheableDependency($cacheability);
return $response;
}