From 33d461a22a7ab4ebb4f18fa3616cbdbe7dae5174 Mon Sep 17 00:00:00 2001 From: Hemachandar Date: Thu, 18 Dec 2025 20:51:04 +0530 Subject: [PATCH] Support JSON string body in fetch --- src/Client.php | 6 +++--- tests/ClientTest.php | 23 +++++++++++++++++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/Client.php b/src/Client.php index 4b6772b..8ca3803 100644 --- a/src/Client.php +++ b/src/Client.php @@ -255,7 +255,7 @@ private function withRetries(callable $callback): mixed * * @param string $url * @param string $method - * @param array|array $body + * @param array|array|string|null $body * @param array $query * @param ?callable $chunks Optional callback function that receives a Chunk object * @param ?int $timeoutMs Optional request timeout in milliseconds @@ -265,7 +265,7 @@ private function withRetries(callable $callback): mixed public function fetch( string $url, string $method = self::METHOD_GET, - ?array $body = [], + array|string|null $body = [], ?array $query = [], ?callable $chunks = null, ?int $timeoutMs = null, @@ -275,7 +275,7 @@ public function fetch( throw new Exception("Unsupported HTTP method"); } - if (isset($this->headers['content-type']) && $body !== null) { + if (is_array($body) && isset($this->headers['content-type'])) { $body = match ($this->headers['content-type']) { self::CONTENT_TYPE_APPLICATION_JSON => $this->jsonEncode($body), self::CONTENT_TYPE_APPLICATION_FORM_URLENCODED, self::CONTENT_TYPE_MULTIPART_FORM_DATA => self::flatten($body), diff --git a/tests/ClientTest.php b/tests/ClientTest.php index e861285..bc9d78b 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -13,7 +13,7 @@ final class ClientTest extends TestCase * @dataProvider dataSet * @param string $url * @param string $method - * @param array $body + * @param array|string|null $body * @param array $headers * @param array $query * @return void @@ -53,7 +53,7 @@ public function testFetch( if ($headers['content-type'] != "application/x-www-form-urlencoded") { $this->assertSame( // Assert that the body is equal to the response's body $respData['body'], - json_encode($body) // Converting the body to JSON string + is_string($body) ? $body : json_encode($body) // Converting the body to JSON string ); } } @@ -307,6 +307,25 @@ public function dataSet(): array 'content-type' => 'application/json' ], ], + 'postSingleLineJsonStringBody' => [ + 'localhost:8000', + Client::METHOD_POST, + '{"name": "John Doe","age": 30}', + [ + 'content-type' => 'application/json' + ] + ], + 'postMultiLineJsonStringBody' => [ + 'localhost:8000', + Client::METHOD_POST, + '{ + "name": "John Doe", + "age": 30 + }', + [ + 'content-type' => 'application/json' + ] + ], 'postFormDataBody' => [ 'localhost:8000', Client::METHOD_POST,