Skip to content

Commit

Permalink
check only for containing string in utils::getJsonFromResponse, added…
Browse files Browse the repository at this point in the history
… tests
  • Loading branch information
Sysix committed Jan 15, 2024
1 parent eb94e98 commit 3041911
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
6 changes: 3 additions & 3 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
58 changes: 58 additions & 0 deletions tests/UtilsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Sysix\LexOffice\Tests;

use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Sysix\LexOffice\Utils;

class UtilsTest extends TestCase
{
public function testGetJsonFromResponseWithoutAnHeader(): void
{
$response = new Response();
$json = Utils::getJsonFromResponse($response);

$this->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);
}
}

0 comments on commit 3041911

Please sign in to comment.