diff --git a/src/JsonDecodeMiddleware.php b/src/JsonDecodeMiddleware.php index 592665e..9c2c6a7 100644 --- a/src/JsonDecodeMiddleware.php +++ b/src/JsonDecodeMiddleware.php @@ -48,6 +48,16 @@ public function post( return resolve($response); } + if (!isset($options[self::class]) && + $response->getHeaderLine('Content-Type') !== 'application/json') { + return resolve($response); + } + + if (isset($options[self::class][Options::CONTENT_TYPE]) && + $response->getHeaderLine('Content-Type') !== $options[self::class][Options::CONTENT_TYPE]) { + return resolve($response); + } + $body = (string)$response->getBody(); if ($body === '') { $stream = new BufferStream(0); diff --git a/src/Options.php b/src/Options.php new file mode 100644 index 0000000..3d02f2a --- /dev/null +++ b/src/Options.php @@ -0,0 +1,9 @@ + 'application/json'], '[]'); $body = await( $middleware->post($response, 'abc'), @@ -34,6 +35,78 @@ public function testPost() ); } + public function testPostNoContentType() + { + $loop = Factory::create(); + $service = new JsonDecodeService($loop); + $middleware = new JsonDecodeMiddleware($service); + $response = new Response(200, [], '[]'); + + self::assertSame( + $response, + await( + $middleware->post($response, 'abc'), + $loop + ) + ); + } + + public function testPostNoContentTypeCheck() + { + $loop = Factory::create(); + $service = new JsonDecodeService($loop); + $middleware = new JsonDecodeMiddleware($service); + $response = new Response(200, [], '[]'); + + $body = await( + $middleware->post( + $response, + 'abc', + [ + JsonDecodeMiddleware::class => [ + Options::NO_CONTENT_TYPE_CHECK => true, + ], + ] + ), + $loop + )->getBody(); + + self::assertInstanceOf(JsonStream::class, $body); + + self::assertSame( + [], + $body->getJson() + ); + } + + public function testPostCustomTYpe() + { + $loop = Factory::create(); + $service = new JsonDecodeService($loop); + $middleware = new JsonDecodeMiddleware($service); + $response = new Response(200, ['Content-Type' => 'custom/type'], '[]'); + + $body = await( + $middleware->post( + $response, + 'abc', + [ + JsonDecodeMiddleware::class => [ + Options::CONTENT_TYPE => 'custom/type', + ], + ] + ), + $loop + )->getBody(); + + self::assertInstanceOf(JsonStream::class, $body); + + self::assertSame( + [], + $body->getJson() + ); + } + public function testPostNoJson() { $loop = Factory::create();