function 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 core/
modules/ jsonapi/ src/ EventSubscriber/ ResourceResponseSubscriber.php  - Serializes ResourceResponse responses' data, and removes that data.
 
File
- 
              core/
modules/ jsonapi/ src/ EventSubscriber/ ResourceResponseSubscriber.php, line 111  
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. Note that error responses do not need a
    // normalization context, since there are no entities to normalize.
    // @see \Drupal\jsonapi\EventSubscriber\DefaultExceptionSubscriber::isJsonApiExceptionEvent()
    $context = !$response->isSuccessful() ? [] : static::generateContext($request);
    $jsonapi_doc_object = $serializer->normalize($data, $format, $context);
    // Having just normalized the data, we can associate its cacheability with
    // the response object.
    if ($response instanceof CacheableResponseInterface) {
      assert($jsonapi_doc_object instanceof CacheableNormalization);
      $response->addCacheableDependency($jsonapi_doc_object);
    }
    // Finally, encode the normalized data (JSON:API's encoder rasterizes it
    // automatically).
    $response->setContent($serializer->encode($jsonapi_doc_object->getNormalization(), $format));
    $response->headers
      ->set('Content-Type', $request->getMimeType($format));
  }
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.