You are here

protected static function ResourceResponseTestTrait::toResourceResponse in JSON:API 8

Same name and namespace in other branches
  1. 8.2 tests/src/Functional/ResourceResponseTestTrait.php \Drupal\Tests\jsonapi\Functional\ResourceResponseTestTrait::toResourceResponse()

Maps a response object to a JSON API ResourceResponse.

This helper can be used to ease comparing, recording and merging cacheable responses and to have easier access to the JSON API document as an array instead of a string.

Parameters

\Psr\Http\Message\ResponseInterface $response: A PSR response to be mapped.

Return value

\Drupal\jsonapi\ResourceResponse The ResourceResponse.

File

tests/src/Functional/ResourceResponseTestTrait.php, line 207

Class

ResourceResponseTestTrait
Utility methods for handling resource responses.

Namespace

Drupal\Tests\jsonapi\Functional

Code

protected static function toResourceResponse(ResponseInterface $response) {
  $cacheability = new CacheableMetadata();
  if ($cache_tags = $response
    ->getHeader('X-Drupal-Cache-Tags')) {
    $cacheability
      ->addCacheTags(explode(' ', $cache_tags[0]));
  }
  if ($cache_contexts = $response
    ->getHeader('X-Drupal-Cache-Contexts')) {
    $cacheability
      ->addCacheContexts(explode(' ', $cache_contexts[0]));
  }
  if ($dynamic_cache = $response
    ->getHeader('X-Drupal-Dynamic-Cache')) {
    $cacheability
      ->setCacheMaxAge($dynamic_cache[0] === 'UNCACHEABLE' ? 0 : Cache::PERMANENT);
  }
  $related_document = Json::decode($response
    ->getBody());
  $resource_response = new ResourceResponse($related_document, $response
    ->getStatusCode());
  return $resource_response
    ->addCacheableDependency($cacheability);
}