File tree Expand file tree Collapse file tree 3 files changed +33
-3
lines changed Expand file tree Collapse file tree 3 files changed +33
-3
lines changed Original file line number Diff line number Diff line change 44
55use ArrayObject ;
66use HttpAccept \AcceptParser ;
7+ use JsonException ;
78use Nyholm \Psr7 \Response ;
89use Nyholm \Psr7 \Stream ;
910use Psr \Http \Message \ResponseInterface ;
1011use Psr \Http \Message \ServerRequestInterface ;
1112use RuntimeException ;
13+ use Tobyz \JsonApiServer \Exception \Data \InvalidJsonException ;
1214use Tobyz \JsonApiServer \Exception \ErrorProvider ;
1315use Tobyz \JsonApiServer \Exception \Field \InvalidFieldValueException ;
1416use Tobyz \JsonApiServer \Exception \JsonApiErrorsException ;
@@ -122,9 +124,17 @@ public function currentUrl(array $queryParams = []): string
122124 */
123125 public function body (): ?array
124126 {
125- return $ this ->body ??=
126- (array ) $ this ->request ->getParsedBody () ?:
127- json_decode ($ this ->request ->getBody ()->getContents (), true );
127+ try {
128+ return $ this ->body ??=
129+ (array ) $ this ->request ->getParsedBody () ?:
130+ json_decode (
131+ $ this ->request ->getBody ()->getContents (),
132+ true ,
133+ flags: JSON_THROW_ON_ERROR ,
134+ );
135+ } catch (JsonException $ e ) {
136+ throw new InvalidJsonException ($ e ->getMessage ());
137+ }
128138 }
129139
130140 public function id (Resource $ resource , $ model ): string
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Tobyz \JsonApiServer \Exception \Data ;
4+
5+ use Tobyz \JsonApiServer \Exception \BadRequestException ;
6+
7+ class InvalidJsonException extends BadRequestException
8+ {
9+ }
Original file line number Diff line number Diff line change 22
33namespace Tobyz \Tests \JsonApiServer \specification ;
44
5+ use Nyholm \Psr7 \Stream ;
56use Tobyz \JsonApiServer \Endpoint \Create ;
67use Tobyz \JsonApiServer \Endpoint \Show ;
78use Tobyz \JsonApiServer \Exception \BadRequestException ;
89use Tobyz \JsonApiServer \Exception \ConflictException ;
10+ use Tobyz \JsonApiServer \Exception \Data \InvalidJsonException ;
911use Tobyz \JsonApiServer \Exception \ForbiddenException ;
1012use Tobyz \JsonApiServer \Exception \ResourceNotFoundException ;
1113use Tobyz \JsonApiServer \JsonApi ;
@@ -37,6 +39,15 @@ public function setUp(): void
3739 $ this ->api ->resource (new MockResource ('pets ' ));
3840 }
3941
42+ public function test_bad_request_error_if_body_is_invalid_json ()
43+ {
44+ $ this ->expectException (InvalidJsonException::class);
45+
46+ $ this ->api ->handle (
47+ $ this ->buildRequest ('POST ' , '/users ' )->withBody (Stream::create ('invalid json ' )),
48+ );
49+ }
50+
4051 public function test_bad_request_error_if_body_does_not_contain_data_type ()
4152 {
4253 $ this ->expectException (BadRequestException::class);
You can’t perform that action at this time.
0 commit comments