diff --git a/src/Request.php b/src/Request.php index f33faeb..b113ba6 100644 --- a/src/Request.php +++ b/src/Request.php @@ -1,6 +1,7 @@ uri = $uri; return $clone; } + + /** @inheritDoc */ + public function withBody(StreamInterface|FormData $body):self { + if($body instanceof FormData) { + $stream = new Stream(); + $stream->write((string)$body); + $stream->rewind(); + + $clone = clone $this; + $clone->stream = $stream; + if(!$clone->headers->contains("Content-Type")) { + $clone->headers->set("Content-Type", "application/x-www-form-urlencoded"); + } + return $clone; + } + + $clone = clone $this; + $clone->stream = $body; + return $clone; + } } diff --git a/test/phpunit/RequestTest.php b/test/phpunit/RequestTest.php index 913a191..b833791 100644 --- a/test/phpunit/RequestTest.php +++ b/test/phpunit/RequestTest.php @@ -1,6 +1,7 @@ withUri(self::getUriMock("https://example2.com/something")); } + public function testWithFormDataBodyAutomaticallySetsContentTypeHeader():void { + $formData = new FormData(); + $formData->append("key", "value"); + + $request = new Request( + "POST", + self::getUriMock("/"), + new RequestHeaders() + ); + + $request = $request->withBody($formData); + self::assertSame( + "application/x-www-form-urlencoded", + $request->getHeaderLine("Content-Type") + ); + } + /** @return MockObject|Uri */ protected function getUriMock(string $uriPath = ""):MockObject { $partPath = parse_url($uriPath, PHP_URL_PATH);