You are here

class MultiresponseNormalizer in Subrequests 8.2

Same name and namespace in other branches
  1. 8 src/Normalizer/MultiresponseNormalizer.php \Drupal\subrequests\Normalizer\MultiresponseNormalizer
  2. 3.x src/Normalizer/MultiresponseNormalizer.php \Drupal\subrequests\Normalizer\MultiresponseNormalizer

Normalizes multiple response objects into a single string.

Hierarchy

  • class \Drupal\subrequests\Normalizer\MultiresponseNormalizer implements \Symfony\Component\Serializer\Normalizer\NormalizerInterface

Expanded class hierarchy of MultiresponseNormalizer

2 files declare their use of MultiresponseNormalizer
BlueprintManagerTest.php in tests/src/Unit/Blueprint/BlueprintManagerTest.php
MultiresponseNormalizerTest.php in tests/src/Unit/Normalizer/MultiresponseNormalizerTest.php
1 string reference to 'MultiresponseNormalizer'
subrequests.services.yml in ./subrequests.services.yml
subrequests.services.yml
1 service uses MultiresponseNormalizer
subrequests.normalizer.multiresponse in ./subrequests.services.yml
Drupal\subrequests\Normalizer\MultiresponseNormalizer

File

src/Normalizer/MultiresponseNormalizer.php, line 11

Namespace

Drupal\subrequests\Normalizer
View source
class MultiresponseNormalizer implements NormalizerInterface {

  /**
   * {@inheritdoc}
   */
  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,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function supportsNormalization($data, $format = NULL) {
    if ($format !== 'multipart-related') {
      return FALSE;
    }
    if (!is_array($data)) {
      return FALSE;
    }
    $responses = array_filter($data, function ($response) {
      return $response instanceof Response;
    });
    if (count($responses) !== count($data)) {
      return FALSE;
    }
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MultiresponseNormalizer::normalize public function Normalizes an object into a set of arrays/scalars.
MultiresponseNormalizer::supportsNormalization public function Checks whether the given class is supported for normalization by this normalizer.