Skip to content

Commit 7c8b4b6

Browse files
committed
🆕 Handle 415 http code
When request format violate router supported formats
1 parent 7030993 commit 7c8b4b6

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

features/handle_payload.feature

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ Feature: Handle json payload
3434
"name": "Bond"
3535
}
3636
"""
37-
Then the JSON node "name" should not exist
37+
Then the response status code should be 415
38+
And the JSON node "name" should not exist
3839

3940
Scenario: Send invalid data
4041
Given I set "Content-Type" header equal to "application/json"

src/JsonBodyListener.php

+14
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
namespace Rezzza\SymfonyRestApiJson;
44

5+
use Symfony\Component\HttpFoundation\Request;
56
use Symfony\Component\HttpFoundation\ParameterBag;
67
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
78
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
9+
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
810

911
/**
1012
* Allow to pass JSON raw as request content.
@@ -31,6 +33,10 @@ public function onKernelRequest(GetResponseEvent $event)
3133
: $request->getFormat($contentType);
3234

3335
if ($format !== 'json') {
36+
if ($this->requestFormatViolateSupportedFormats($format, $request->attributes->get('_supportedFormats', false))) {
37+
throw new UnsupportedMediaTypeHttpException("Request body format '$format' not supported");
38+
}
39+
3440
return;
3541
}
3642

@@ -51,4 +57,12 @@ public function onKernelRequest(GetResponseEvent $event)
5157

5258
$request->request = new ParameterBag($data);
5359
}
60+
61+
private function requestFormatViolateSupportedFormats($format, $supportedFormats)
62+
{
63+
return null !== $format
64+
&& false !== $supportedFormats
65+
&& false === in_array($format, $supportedFormats, true)
66+
;
67+
}
5468
}

testapp/index.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ protected function configureRoutes(RouteCollectionBuilder $routes)
3333
{
3434
// kernel is a service that points to this class
3535
// optional 3rd argument is the route name
36-
$routes->add('/echo', 'kernel:echoAction')->setDefault('_jsonSchema', ['request' => 'schema.json']);
36+
$routes->add('/echo', 'kernel:echoAction')
37+
->setDefault('_jsonSchema', ['request' => 'schema.json'])
38+
->setDefault('_supportedFormats', ['json'])
39+
;
3740
$routes->add('/exception', 'kernel:exceptionAction');
3841
}
3942

0 commit comments

Comments
 (0)