From 76002b1213314cb1f123f67eee2e8ddfe6b53997 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 21 Jun 2023 17:59:30 +0200 Subject: [PATCH] [HttpFoundation] Make Request::getPayload() return an empty InputBag if request body is empty --- Request.php | 20 +++++++++++++++++++- Tests/RequestTest.php | 3 +++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 9445a4b28..0bef6f8d7 100644 --- a/Request.php +++ b/Request.php @@ -1513,7 +1513,25 @@ public function getContent(bool $asResource = false) */ public function getPayload(): InputBag { - return $this->request->count() ? clone $this->request : new InputBag($this->toArray()); + if ($this->request->count()) { + return clone $this->request; + } + + if ('' === $content = $this->getContent()) { + return new InputBag([]); + } + + try { + $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new JsonException('Could not decode request body.', $e->getCode(), $e); + } + + if (!\is_array($content)) { + throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content))); + } + + return new InputBag($content); } /** diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 5e8df28bb..308e9e6fd 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1309,6 +1309,9 @@ public function testGetPayload() $req = new Request([], ['foo' => 'bar'], [], [], [], [], json_encode(['baz' => 'qux'])); $this->assertSame(['foo' => 'bar'], $req->getPayload()->all()); + + $req = new Request([], [], [], [], [], [], ''); + $this->assertSame([], $req->getPayload()->all()); } /**