You are here

public function MultiresponseNormalizer::normalize in Subrequests 3.x

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

File

src/Normalizer/MultiresponseNormalizer.php, line 16

Class

MultiresponseNormalizer
Normalizes multiple response objects into a single string.

Namespace

Drupal\subrequests\Normalizer

Code

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

  // Prepare the root content type header.
  $content_type = sprintf('multipart/related; boundary="%s"; type=%s', $delimiter, $context['sub-content-type']);
  $headers = [
    'Content-Type' => $content_type,
  ];
  $separator = sprintf("\r\n--%s\r\n", $delimiter);

  // Join the content responses with the separator.
  $content_items = array_map(function (Response $part_response) {
    $part_response->headers
      ->set('Status', $part_response
      ->getStatusCode());
    return sprintf("%s\r\n%s", $part_response->headers, $part_response
      ->getContent());
  }, (array) $object);
  $content = sprintf("--%s\r\n", $delimiter) . implode($separator, $content_items) . sprintf("\r\n--%s--", $delimiter);
  return [
    'content' => $content,
    'headers' => $headers,
  ];
}