Skip to content

Commit

Permalink
BasicEntity: fix json body decode (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
miranovy authored Sep 7, 2021
1 parent 22862ac commit 0a2f43c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Mapping/Request/BasicEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Apitte\Core\Mapping\Request;

use Apitte\Core\Exception\Api\ClientErrorException;
use Apitte\Core\Http\ApiRequest;
use Apitte\Core\Mapping\TReflectionProperties;
use Apitte\Core\Schema\Endpoint;
use Nette\Utils\JsonException;

abstract class BasicEntity extends AbstractEntity
{
Expand Down Expand Up @@ -78,7 +80,13 @@ protected function normalize(string $property, $value)
*/
protected function fromBodyRequest(ApiRequest $request): self
{
return $this->factory((array) $request->getJsonBody(true));
try {
$body = (array) $request->getJsonBody(true);
} catch (JsonException $ex) {
throw new ClientErrorException('Invalid json data', 400, $ex);
}

return $this->factory($body);
}

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/cases/Mapping/RequestEntityMapping.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

require_once __DIR__ . '/../../bootstrap.php';

use Apitte\Core\Exception\Api\ClientErrorException;
use Apitte\Core\Exception\Logical\InvalidStateException;
use Apitte\Core\Http\ApiRequest;
use Apitte\Core\Http\ApiResponse;
Expand Down Expand Up @@ -105,3 +106,16 @@ test(function (): void {
Assert::same(1, $entity->foo);
}
});

// Try mapping invalid json body
test(function (): void {
$request = new ApiRequest(Psr7ServerRequestFactory::fromSuperGlobal());
$entity = new NotEmptyEntity();

$bodyRequest = $request
->withBody(Utils::streamFor('invalid-json'));

Assert::exception(function () use ($entity, $bodyRequest): void {
$entity = $entity->fromRequest($bodyRequest->withMethod('POST'));
}, ClientErrorException::class, 'Invalid json data');
});

0 comments on commit 0a2f43c

Please sign in to comment.