Skip to content

Commit

Permalink
Merge pull request #6 from psfpro/patch-1
Browse files Browse the repository at this point in the history
Fix BodyParamsMiddleware: Valid JSON containing a scalar value causes InvalidArgumentException
  • Loading branch information
weierophinney committed Apr 20, 2021
2 parents 6262786 + 05d3233 commit 5521434
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
File renamed without changes.
4 changes: 4 additions & 0 deletions src/BodyParams/JsonStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ public function parse(ServerRequestInterface $request) : ServerRequestInterface
));
}

if (! is_array($parsedBody)) {
$parsedBody = null;
}

return $request
->withAttribute('rawBody', $rawBody)
->withParsedBody($parsedBody);
Expand Down
33 changes: 33 additions & 0 deletions test/BodyParams/JsonStrategyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,37 @@ public function testEmptyRequestBodyIsNotJsonDecoded(): void

$this->assertSame(json_last_error(), JSON_ERROR_NONE);
}

/** @psalm-return iterable<string, array{0: string}> */
public function provideNonArrayJsonRequestBody(): iterable
{
yield 'null' => ['null'];
yield 'true' => ['true'];
yield 'false' => ['false'];
yield 'integer' => ['1'];
yield 'float' => ['1.0'];
yield 'string' => ['"string"'];
}

/**
* @dataProvider provideNonArrayJsonRequestBody
*/
public function testParsedBodyEvaluatingToNonArrayValueResultsInNull(string $json): void
{
$stream = $this->prophesize(StreamInterface::class);
$stream->__toString()->willReturn($json);
$request = $this->prophesize(ServerRequestInterface::class);
$request->getBody()->willReturn($stream->reveal());
$request->withAttribute('rawBody', $json)->will(function () use ($request) {
return $request->reveal();
});
$request
->withParsedBody(null)
->will(function () use ($request) {
return $request->reveal();
})
->shouldBeCalled();

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

0 comments on commit 5521434

Please sign in to comment.