Skip to content
This repository has been archived by the owner on Jan 21, 2020. It is now read-only.

Don't throw exception on empty JSON body #29

Merged
merged 2 commits into from
Dec 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/BodyParams/JsonStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function parse(ServerRequestInterface $request)
$rawBody = (string) $request->getBody();
$parsedBody = json_decode($rawBody, true);

if (json_last_error() !== JSON_ERROR_NONE) {
if (! empty($rawBody) && json_last_error() !== JSON_ERROR_NONE) {
throw new MalformedRequestBodyException('Error when parsing JSON request body: ' . json_last_error_msg());
}

Expand Down
17 changes: 17 additions & 0 deletions test/BodyParams/JsonStrategyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,21 @@ public function testThrowsExceptionOnMalformedJsonInRequestBody()

$this->strategy->parse($request->reveal());
}

public function testEmptyRequestBodyYieldsNullParsedBodyWithNoExceptionThrown()
{
$body = '';
$stream = $this->prophesize(StreamInterface::class);
$stream->__toString()->willReturn($body);
$request = $this->prophesize(ServerRequestInterface::class);
$request->getBody()->willReturn($stream->reveal());
$request->withAttribute('rawBody', $body)->will(function () use ($request) {
return $request->reveal();
});
$request->withParsedBody(null)->will(function () use ($request) {
return $request->reveal();
});

$this->assertSame($request->reveal(), $this->strategy->parse($request->reveal()));
}
}