Skip to content

Commit 67724bb

Browse files
authored
Merge pull request #144 from Sysix/jsonfromresponse-fix
check only for containing string in utils::getJsonFromResponse
2 parents eb94e98 + 3041911 commit 67724bb

File tree

3 files changed

+63
-4
lines changed

3 files changed

+63
-4
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -275,5 +275,6 @@ $response = $client->getPage(0);
275275

276276
```php
277277
// can be possible null because the response body can be empty
278-
$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response);
278+
$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response); // as object
279+
$json = \Sysix\LexOffice\Utils::getJsonFromResponse($response, true); // as associative array
279280
```

src/Utils.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
1212

1313
class Utils
1414
{
15-
public static function getJsonFromResponse(ResponseInterface $response): mixed
15+
public static function getJsonFromResponse(ResponseInterface $response, bool $assoc = false): mixed
1616
{
1717
$body = $response->getBody()->__toString();
1818

19-
if ($response->getHeaderLine('Content-Type') === 'application/json') {
20-
return self::jsonDecode($body);
19+
if (str_contains($response->getHeaderLine('Content-Type'), 'application/json')) {
20+
return self::jsonDecode($body, $assoc);
2121
}
2222

2323
return null;

tests/UtilsTest.php

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Sysix\LexOffice\Tests;
6+
7+
use GuzzleHttp\Psr7\Response;
8+
use PHPUnit\Framework\TestCase;
9+
use Sysix\LexOffice\Utils;
10+
11+
class UtilsTest extends TestCase
12+
{
13+
public function testGetJsonFromResponseWithoutAnHeader(): void
14+
{
15+
$response = new Response();
16+
$json = Utils::getJsonFromResponse($response);
17+
18+
$this->assertNull($json);
19+
}
20+
21+
public function testGetJsonFromResponseWithInvalidHeader(): void
22+
{
23+
$response = new Response(200, [
24+
'Content-Type' => 'application/xml'
25+
]);
26+
$json = Utils::getJsonFromResponse($response);
27+
28+
$this->assertNull($json);
29+
}
30+
31+
public function testGetJsonFromResponseWithValidHeader(): void
32+
{
33+
$response = new Response(200, [
34+
'Content-Type' => 'application/json'
35+
], (string) json_encode([
36+
'test' => true
37+
]));
38+
$json = Utils::getJsonFromResponse($response);
39+
40+
$this->assertEquals((object)[
41+
'test' => true
42+
], $json);
43+
}
44+
45+
public function testGetJsonFromResponseWithValidCharsetHeader(): void
46+
{
47+
$response = new Response(200, [
48+
'Content-Type' => 'application/json; charset=utf-8'
49+
], (string) json_encode([
50+
'test' => true
51+
]));
52+
$json = Utils::getJsonFromResponse($response);
53+
54+
$this->assertEquals((object)[
55+
'test' => true
56+
], $json);
57+
}
58+
}

0 commit comments

Comments
 (0)