From 3041911989fd39d7c07456b2effd3d5a20a2d1b7 Mon Sep 17 00:00:00 2001 From: Sysix Date: Mon, 15 Jan 2024 18:26:22 +0100 Subject: [PATCH] check only for containing string in utils::getJsonFromResponse, added tests --- README.md | 3 ++- src/Utils.php | 6 ++--- tests/UtilsTest.php | 58 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 tests/UtilsTest.php diff --git a/README.md b/README.md index 4ee752a..bc19e0f 100644 --- a/README.md +++ b/README.md @@ -275,5 +275,6 @@ $response = $client->getPage(0); ```php // can be possible null because the response body can be empty -$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response); +$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response); // as object +$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response, true); // as associative array ``` \ No newline at end of file diff --git a/src/Utils.php b/src/Utils.php index dab90c9..2215878 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -12,12 +12,12 @@ class Utils { - public static function getJsonFromResponse(ResponseInterface $response): mixed + public static function getJsonFromResponse(ResponseInterface $response, bool $assoc = false): mixed { $body = $response->getBody()->__toString(); - if ($response->getHeaderLine('Content-Type') === 'application/json') { - return self::jsonDecode($body); + if (str_contains($response->getHeaderLine('Content-Type'), 'application/json')) { + return self::jsonDecode($body, $assoc); } return null; diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php new file mode 100644 index 0000000..8e46225 --- /dev/null +++ b/tests/UtilsTest.php @@ -0,0 +1,58 @@ +assertNull($json); + } + + public function testGetJsonFromResponseWithInvalidHeader(): void + { + $response = new Response(200, [ + 'Content-Type' => 'application/xml' + ]); + $json = Utils::getJsonFromResponse($response); + + $this->assertNull($json); + } + + public function testGetJsonFromResponseWithValidHeader(): void + { + $response = new Response(200, [ + 'Content-Type' => 'application/json' + ], (string) json_encode([ + 'test' => true + ])); + $json = Utils::getJsonFromResponse($response); + + $this->assertEquals((object)[ + 'test' => true + ], $json); + } + + public function testGetJsonFromResponseWithValidCharsetHeader(): void + { + $response = new Response(200, [ + 'Content-Type' => 'application/json; charset=utf-8' + ], (string) json_encode([ + 'test' => true + ])); + $json = Utils::getJsonFromResponse($response); + + $this->assertEquals((object)[ + 'test' => true + ], $json); + } +}