Skip to content

Commit

Permalink
Merge pull request #17 from kartenmacherei/fix-handling-of-json-arrays
Browse files Browse the repository at this point in the history
Extend Json Body to handle pure json arrays
  • Loading branch information
web-dc authored Apr 10, 2024
2 parents 56b43e8 + f45b712 commit e2cdc1f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/Http/Request/Body/JsonBody.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class JsonBody extends Body
{
/** @var JsonObject */
/** @var JsonObject|JsonArray */
private $json;

/** @var string */
Expand All @@ -33,7 +33,8 @@ public function query(string $selector)
return $this->json->query($selector);
}

public function getJson(): JsonObject
/** @return JsonArray|JsonObject */
public function getJson()
{
return $this->json;
}
Expand All @@ -48,15 +49,19 @@ public function getEncodedString(): string
*
* @throws EnsureException
*
* @return JsonObject
* @return JsonObject|JsonArray
*/
private function decode(string $jsonString): JsonObject
private function decode(string $jsonString)
{
$decoded = json_decode($jsonString, false);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new EnsureException(sprintf('JSON body could not be decoded: %s', json_last_error_msg()));
}

if (is_array($decoded)) {
return new JsonArray($decoded);
}

return new JsonObject($decoded);
}
}
11 changes: 11 additions & 0 deletions tests/Unit/Http/Request/Body/JsonBodyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Kartenmacherei\HttpFramework\UnitTest\Http;

use Kartenmacherei\HttpFramework\Http\EnsureException;
use Kartenmacherei\HttpFramework\Http\JsonArray;
use Kartenmacherei\HttpFramework\Http\JsonObject;
use Kartenmacherei\HttpFramework\Http\Request\Body\JsonBody;
use PHPUnit\Framework\TestCase;
Expand All @@ -13,6 +14,7 @@
* @covers \Kartenmacherei\HttpFramework\Http\Request\Body\JsonBody
*
* @uses \Kartenmacherei\HttpFramework\Http\JsonObject
* @uses \Kartenmacherei\HttpFramework\Http\JsonArray
*/
class JsonBodyTest extends TestCase
{
Expand Down Expand Up @@ -45,4 +47,13 @@ public function testQueryReturnsExpectedValue(): void
$body = new JsonBody($jsonString);
$this->assertSame('bar', $body->query('foo'));
}

public function testGetJsonReturnsJsonArrayForArrayStrings(): void
{
$jsonString = '["foo","bar"]';
$body = new JsonBody($jsonString);
$expected = new JsonArray(json_decode($jsonString));

$this->assertEquals($expected, $body->getJson());
}
}

0 comments on commit e2cdc1f

Please sign in to comment.