Skip to content

Commit fcd422c

Browse files
authored
Merge pull request #81 from danopz/body-parser
allow body parsers for media types containing +
2 parents 08de41c + 57cbf5f commit fcd422c

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

src/ServerRequest.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -268,14 +268,17 @@ public function getParsedBody()
268268
return null;
269269
}
270270

271-
// Look for a media type with a structured syntax suffix (RFC 6839)
272-
$parts = explode('+', $mediaType);
273-
if (count($parts) >= 2) {
274-
$mediaType = 'application/' . $parts[count($parts)-1];
271+
// Check if this specific media type has a parser registered first
272+
if (!isset($this->bodyParsers[$mediaType])) {
273+
// If not, look for a media type with a structured syntax suffix (RFC 6839)
274+
$parts = explode('+', $mediaType);
275+
if (count($parts) >= 2) {
276+
$mediaType = 'application/' . $parts[count($parts) - 1];
277+
}
275278
}
276279

277-
if (isset($this->bodyParsers[$mediaType]) === true) {
278-
$body = (string) $this->getBody();
280+
if (isset($this->bodyParsers[$mediaType])) {
281+
$body = (string)$this->getBody();
279282
$parsed = $this->bodyParsers[$mediaType]($body);
280283

281284
if (!is_null($parsed) && !is_object($parsed) && !is_array($parsed)) {

tests/ServerRequestTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,29 @@ public function testGetParsedBodyWithJsonStructuredSuffix()
780780
}
781781
}
782782

783+
public function testGetParsedBodyWithJsonStructuredSuffixAndRegisteredParser()
784+
{
785+
foreach ($this->factoryProviders as $factoryProvider) {
786+
/** @var Psr17FactoryProvider $provider */
787+
$provider = new $factoryProvider;
788+
$decoratedServerRequestFactory = new DecoratedServerRequestFactory($provider->getServerRequestFactory());
789+
790+
$streamFactory = $provider->getStreamFactory();
791+
$stream = $streamFactory->createStream('{"foo":"bar"}');
792+
793+
$request = $decoratedServerRequestFactory->createServerRequest('POST', 'https://google.com');
794+
$request = $request
795+
->withHeader('Content-Type', 'application/vnd.api+json;charset=utf8')
796+
->withBody($stream);
797+
798+
$request->registerMediaTypeParser('application/vnd.api+json', function ($input) {
799+
return ['data' => $input];
800+
});
801+
802+
$this->assertEquals(['data' => '{"foo":"bar"}'], $request->getParsedBody());
803+
}
804+
}
805+
783806
public function testGetParsedBodyXml()
784807
{
785808
foreach ($this->factoryProviders as $factoryProvider) {

0 commit comments

Comments
 (0)