Permalink
Fetching contributors…
Cannot retrieve contributors at this time
executable file 74 lines (65 sloc) 1.99 KB
<?php
use Psr\Http\{
Message\ResponseInterface,
Message\ServerRequestInterface as Request,
Server\MiddlewareInterface,
Server\RequestHandlerInterface as RequestHandler
};
use Zend\Diactoros\PhpInputStream;
class ParsedBody implements MiddlewareInterface
{
/**
* Process request
*
* @param ServerRequestInterface $request request
* @param RequestHandlerInterface $handler
*
* @return object ResponseInterface
*/
public function process(Request $request, RequestHandler $handler) : ResponseInterface
{
$parsedBody = $request->getParsedBody();
if (empty($parsedBody)) {
$body = (string)new PhpInputStream('php://input');
$mediaType = $this->getMediaType($request);
switch ($mediaType) {
case 'application/json':
$parsedBody = json_decode($body, true);
break;
case 'application/xml':
$parsedBody = simplexml_load_string($body);
break;
}
$request = $request->withParsedBody($parsedBody);
}
return $handler->handle($request);
}
/**
* Get request media type, if known.
*
* @param ServerRequestInterface $request request
*
* @return string|null The request media type, minus content-type params
*/
protected function getMediaType(Request $request)
{
$contentType = $this->getContentType($request);
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
return strtolower($contentTypeParts[0]);
}
return null;
}
/**
* Get request content type.
*
* @param ServerRequestInterface $request request
*
* @return string|null The request content type, if known
*/
protected function getContentType(Request $request)
{
$result = $request->getHeader('Content-Type');
return $result ? $result[0] : null;
}
}