You are here

public function MultiresponseJsonNormalizer::normalize in Subrequests 3.x

Same name and namespace in other branches
  1. 8.2 src/Normalizer/MultiresponseJsonNormalizer.php \Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer::normalize()

File

src/Normalizer/MultiresponseJsonNormalizer.php, line 17

Class

MultiresponseJsonNormalizer
Normalizes multiple response objects into a single string.

Namespace

Drupal\subrequests\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) {

  // Prepare the root content type header.
  $content_type = sprintf('application/json; type=%s', $context['sub-content-type']);
  $headers = [
    'Content-Type' => $content_type,
  ];

  // Join the content responses as a JSON object with the separator.
  $output = array_reduce((array) $object, function ($carry, Response $part_response) {
    $part_response->headers
      ->set('Status', $part_response
      ->getStatusCode());
    $content_id = $part_response->headers
      ->get('Content-ID');
    $content_id = substr($content_id, 1, strlen($content_id) - 2);
    $carry[$content_id] = [
      'headers' => $part_response->headers
        ->all(),
      'body' => $part_response
        ->getContent(),
    ];
    return $carry;
  }, []);
  $content = Json::encode($output);
  return [
    'content' => $content,
    'headers' => $headers,
  ];
}