diff --git a/src/HttpMultipart/HttpFoundation/MultipartResponse.php b/src/HttpMultipart/HttpFoundation/MultipartResponse.php index 783c8034..269b4e1e 100644 --- a/src/HttpMultipart/HttpFoundation/MultipartResponse.php +++ b/src/HttpMultipart/HttpFoundation/MultipartResponse.php @@ -20,7 +20,7 @@ class MultipartResponse extends ResourceResponse { /** * @var Response[] */ - protected $parts; + protected $parts = []; /** * Constructor. @@ -28,30 +28,37 @@ class MultipartResponse extends ResourceResponse { public function __construct(array $parts = NULL, $status = 200, $headers = [], $subtype = NULL) { parent::__construct(NULL, $status, $headers); + if ($parts) { + $this->setParts($parts); + } + $this->subtype = $subtype ?: 'mixed'; $this->boundary = md5(microtime()); + } - if (NULL !== $parts) { - $this->setParts($parts); + /** + * {@inheritdoc} + */ + public function prepare(Request $request) { + $this->headers->set('Content-Type', sprintf('multipart/%s; boundary="%s"', $this->subtype, $this->boundary)); + $this->headers->set('Transfer-Encoding', 'chunked'); + + // Prepare the response content from the parts. + $parts = $this->getParts(); + + if ($parts) { $content = ''; - foreach ($this->getParts() as $part) { + + foreach ($parts as $part) { $content .= "--{$this->boundary}\r\n"; $content .= "Content-Type: {$part->headers->get('Content-Type')}\r\n\r\n"; - $content .= \Drupal::service('serializer') - ->serialize($part->getResponseData(), 'json'); + $content .= $part->getContent(); $content .= "\r\n"; } + $content .= "--{$this->boundary}--"; $this->setContent($content); } - } - - /** - * {@inheritdoc} - */ - public function prepare(Request $request) { - $this->headers->set('Content-Type', "multipart/{$this->subtype}; boundary=\"{$this->boundary}\""); - $this->headers->set('Transfer-Encoding', 'chunked'); return parent::prepare($request); } diff --git a/src/HttpMultipart/ResourceMultipartResponse.php b/src/HttpMultipart/ResourceMultipartResponse.php index 7816e29b..5685d6ae 100644 --- a/src/HttpMultipart/ResourceMultipartResponse.php +++ b/src/HttpMultipart/ResourceMultipartResponse.php @@ -26,24 +26,10 @@ public function prepare(Request $request) { public function sendContent() { // This fixes the "Malformed encoding found in chunked-encoding" // error message in curl and makes possible to get the correct response body. - $size = $this->getSize(); + $size = strlen($this->getContent()); echo "$size\r\n"; - parent::sendContent(); - } - /** - * Returns the length of all the parts in the response body. - * - * @return int - */ - protected function getSize() { - $size = 0; - foreach ($this->parts as $part) { - $content = $part->getContent(); - $output = "--{$this->boundary}" . "{$part->headers}" . $content; - $size += strlen($output); - } - return $size; + parent::sendContent(); } }