You are here

protected static function ResourceResponseTestTrait::toResourceResponse in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/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\CacheableResourceResponse The ResourceResponse.

File

core/modules/jsonapi/tests/src/Functional/ResourceResponseTestTrait.php, line 236

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 (!empty($response
    ->getHeaderLine('X-Drupal-Cache-Contexts'))) {
    $cacheability
      ->addCacheContexts(explode(' ', $response
      ->getHeader('X-Drupal-Cache-Contexts')[0]));
  }
  if ($dynamic_cache = $response
    ->getHeader('X-Drupal-Dynamic-Cache')) {
    $cacheability
      ->setCacheMaxAge($dynamic_cache[0] === 'UNCACHEABLE' && $response
      ->getStatusCode() < 400 ? 0 : Cache::PERMANENT);
  }
  $related_document = Json::decode($response
    ->getBody());
  $resource_response = new CacheableResourceResponse($related_document, $response
    ->getStatusCode());
  return $resource_response
    ->addCacheableDependency($cacheability);
}