I would like to retrieve JSON raw params from POST request in my controller using $this->request->getPost("foo");
In order to achieve this I wrote a simple middleware class that is triggered on "dispatch:beforeExecuteRoute" event:
$di->set('dispatcher', function() use ($di) {
$eventsManager = $di->getShared('eventsManager');
$eventsManager->attach('dispatch:beforeExecuteRoute', new ContentNegotiationPlugin());
$dispatcher = new Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
class ContentNegotiationPlugin extends Plugin
{
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
$contentType = $this->request->getHeader('Content-Type');
$contentType = $_SERVER['CONTENT_TYPE'];
if ($contentType === 'application/json') {
$rawBody = $this->request->getJsonRawBody(true);
// inject params in the request
}
}
}
I have two questions:
- Why
$this->request->getHeader("Content-Type");
returns an empty string whereas$_SERVER["CONTENT_TYPE"]
returns "application/json"? - Is there a way to inject
$rawBody
into the request, something like$this->request->setPost($rawBody);
?