本文整理汇总了PHP中Psr\Http\Message\ServerRequestInterface::getMediaType方法的典型用法代码示例。如果您正苦于以下问题:PHP ServerRequestInterface::getMediaType方法的具体用法?PHP ServerRequestInterface::getMediaType怎么用?PHP ServerRequestInterface::getMediaType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Psr\Http\Message\ServerRequestInterface
的用法示例。
在下文中一共展示了ServerRequestInterface::getMediaType方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __invoke
/**
* JSON middleware invokable class. It forces Content-Type on the response
* to be application/json. If the request Content-Type is not json then
* return the response with status 415 (Unsupported Media Type)
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(Request $request, Response $response, $next)
{
$mediaType = $request->getMediaType();
$method = strtolower($request->getMethod());
if (in_array($method, ['post', 'put', 'patch']) && '' !== (string) $request->getBody()) {
if (empty($mediaType) || $mediaType !== 'application/json') {
return $response->withStatus(415);
}
}
$response = $response->withHeader('Content-type', 'application/json');
$response = $next($request, $response);
return $response;
}