diff --git a/src/ContentLengthMiddleware.php b/src/ContentLengthMiddleware.php new file mode 100644 index 0000000..c5e484a --- /dev/null +++ b/src/ContentLengthMiddleware.php @@ -0,0 +1,41 @@ +process($request); + if ($response->hasHeader('Content-Length')) { + return $response; + } + + $body = $response->getBody(); + if (null === $body->getSize()) { + return $response; + } + + return $response->withHeader('Content-Length', (string) $body->getSize()); + } +} diff --git a/test/ContentLengthMiddlewareTest.php b/test/ContentLengthMiddlewareTest.php new file mode 100644 index 0000000..a14e22a --- /dev/null +++ b/test/ContentLengthMiddlewareTest.php @@ -0,0 +1,59 @@ +response = $response = $this->prophesize(ResponseInterface::class); + $this->request = $request = $this->prophesize(ServerRequestInterface::class)->reveal(); + $this->stream = $this->prophesize(StreamInterface::class); + + $delegate = $this->prophesize(DelegateInterface::class); + $delegate->process($request)->will([$response, 'reveal']); + $this->delegate = $delegate->reveal(); + + $this->middleware = new ContentLengthMiddleware(); + } + + public function testReturnsResponseVerbatimIfContentLengthHeaderPresent() + { + $this->response->hasHeader('Content-Length')->willReturn(true); + $response = $this->middleware->process($this->request, $this->delegate); + $this->assertSame($this->response->reveal(), $response); + } + + public function testReturnsResponseVerbatimIfContentLengthHeaderNotPresentAndBodySizeIsNull() + { + $this->stream->getSize()->willReturn(null); + $this->response->hasHeader('Content-Length')->willReturn(false); + $this->response->getBody()->will([$this->stream, 'reveal']); + + $response = $this->middleware->process($this->request, $this->delegate); + $this->assertSame($this->response->reveal(), $response); + } + + public function testReturnsResponseWithContentLengthHeaderBasedOnBodySize() + { + $this->stream->getSize()->willReturn(42); + $this->response->hasHeader('Content-Length')->willReturn(false); + $this->response->getBody()->will([$this->stream, 'reveal']); + $this->response->withHeader('Content-Length', '42')->will([$this->response, 'reveal']); + + $response = $this->middleware->process($this->request, $this->delegate); + $this->assertSame($this->response->reveal(), $response); + } +}