diff --git a/test/BodyParamsMiddlewareTest.php b/test/BodyParamsMiddlewareTest.php new file mode 100644 index 0000000..4268287 --- /dev/null +++ b/test/BodyParamsMiddlewareTest.php @@ -0,0 +1,93 @@ +bodyParams = new BodyParamsMiddleware(); + + $stream = fopen('php://memory', 'r+'); + fwrite($stream, json_encode(['foo' => 'bar'])); + + $this->body = new Stream($stream); + $this->body->rewind(); + } + + public function testParsesRawBodyAndPreservesRawBodyInRequestAttribute() + { + $serverRequest = new ServerRequest([], [], '', 'PUT', $this->body, ['Content-type' => 'application/json']); + + $this->bodyParams->__invoke( + $serverRequest, + new Response(), + function ($request, $response) use (&$serverRequest) { + $serverRequest = $request; + + return $response; + } + ); + + $this->assertSame( + json_encode(['foo' => 'bar']), + $serverRequest->getAttribute('rawBody') + ); + $this->assertSame(['foo' => 'bar'], $serverRequest->getParsedBody()); + } + + public function notApplicableProvider() + { + return [ + ['GET', 'application/json'], + ['HEAD', 'application/json'], + ['OPTIONS', 'application/json'], + ['POST', 'application/x-www-form-urlencoded'], + ['DELETE', 'this-isnt-a-real-content-type'], + ]; + } + + /** + * @dataProvider notApplicableProvider + */ + public function testRequestIsUnchangedWhenBodyParamsMiddlewareIsNotApplicable($method, $contentType) + { + $originalRequest = new ServerRequest([], [], '', $method, $this->body, ['Content-type' => $contentType]); + $finalRequest = null; + + $this->bodyParams->__invoke( + $originalRequest, + new Response(), + function ($request, $response) use (&$finalRequest) { + $finalRequest = $request; + + return $response; + } + ); + + $this->assertSame($originalRequest, $finalRequest); + } +}