protected function ResourceResponseSubscriber::renderResponseBody in JSON:API 8
Same name and namespace in other branches
- 8.2 src/EventSubscriber/ResourceResponseSubscriber.php \Drupal\jsonapi\EventSubscriber\ResourceResponseSubscriber::renderResponseBody()
Renders a resource response body.
Serialization can invoke rendering (e.g., generating URLs), but the serialization API does not provide a mechanism to collect the bubbleable metadata associated with that (e.g., language and other contexts), so instead, allow those to "leak" and collect them here in a render context.
@todo Add test coverage for language negotiation contexts in https://www.drupal.org/node/2135829.
Parameters
\Symfony\Component\HttpFoundation\Request $request: The request object.
\Drupal\jsonapi\ResourceResponse $response: The response from the JSON API resource.
\Symfony\Component\Serializer\SerializerInterface $serializer: The serializer to use.
string|null $format: The response format, or NULL in case the response does not need a format, for example for the response to a DELETE request.
1 call to ResourceResponseSubscriber::renderResponseBody()
- ResourceResponseSubscriber::onResponse in src/
EventSubscriber/ ResourceResponseSubscriber.php - Serializes ResourceResponse responses' data, and removes that data.
File
- src/
EventSubscriber/ ResourceResponseSubscriber.php, line 107
Class
- ResourceResponseSubscriber
- Response subscriber that serializes and removes ResourceResponses' data.
Namespace
Drupal\jsonapi\EventSubscriberCode
protected function renderResponseBody(Request $request, ResourceResponse $response, SerializerInterface $serializer, $format) {
$data = $response
->getResponseData();
// If there is data to send, serialize and set it as the response body.
if ($data !== NULL) {
// First normalize the data.
$jsonapi_doc_object = $serializer
->normalize($data, $format, [
'request' => $request,
'resource_type' => $request
->get('resource_type'),
]);
// Having just normalized the data, we can associate its cacheability with
// the response object.
assert($jsonapi_doc_object instanceof JsonApiDocumentTopLevelNormalizerValue);
$response
->addCacheableDependency($jsonapi_doc_object);
// Finally, encode the normalized data (JSON API's encoder rasterizes it
// automatically).
$response
->setContent($serializer
->encode($jsonapi_doc_object, $format));
$response->headers
->set('Content-Type', $request
->getMimeType($format));
}
}