zendframework / zend-diactoros

PSR-7 HTTP Message implementation
BSD 3-Clause "New" or "Revised" License
1.55k stars 152 forks source link

Request with JSON Content-Type #287

Closed spartan closed 6 years ago

spartan commented 6 years ago

I believe in the case below the getParsedBody should return an array. Currently returns NULL.

$request = $request
        ->withHeader('Content-Type', 'application/json')
        ->withBody(new StringStream('{"message":"Ok"}');

 // returns null - should return array
$request->getParsedBody();

// returns json string
(string)$request->getBody();
froschdesign commented 6 years ago

I think this is a duplicate of #278

weierophinney commented 6 years ago

Parsing the body contents is out of scope for the ServerRequest class.

The reason is that how to parse the body will vary based on the request content type. x-www-form-urlencoded is different from JSON is different from XML, and within XML, how that gets parsed will be highly dependent on the XML schema and how it relates to domain objects.

On top of that, even with JSON, how it is parsed will often be up to the specific application. Some will want JSON objects mapped to stdClass instances, while others (like yourself) will want associative arrays.

As such, it's up to the application to determine how to parse the body. This is a job generally left to middleware.

spartan commented 6 years ago

@weierophinney Indeed it makes more sense to handle it in the middleware. Thank you.