-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBodyParamsMiddleware.php
More file actions
55 lines (45 loc) · 1.8 KB
/
BodyParamsMiddleware.php
File metadata and controls
55 lines (45 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace HttpSoft\Basis\Middleware;
use HttpSoft\Basis\Exception\BadRequestHttpException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function json_decode;
use function json_last_error;
use function json_last_error_msg;
use function in_array;
use function parse_str;
use function preg_match;
use function sprintf;
use const JSON_ERROR_NONE;
final class BodyParamsMiddleware implements MiddlewareInterface
{
/**
* {@inheritDoc}
*
* @throws BadRequestHttpException
* @link https://tools.ietf.org/html/rfc7231
* @psalm-suppress MixedArgument, MixedAssignment, RiskyTruthyFalsyComparison
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getParsedBody() || in_array($request->getMethod(), ['GET', 'HEAD', 'OPTIONS'], true)) {
return $handler->handle($request);
}
$contentType = $request->getHeaderLine('content-type');
if (preg_match('#^application/(|[\S]+\+)json($|[ ;])#', $contentType)) {
$parsedBody = json_decode((string) $request->getBody(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new BadRequestHttpException(sprintf(
'Error when parsing JSON request body: %s',
json_last_error_msg()
));
}
} elseif (preg_match('#^application/x-www-form-urlencoded($|[ ;])#', $contentType)) {
parse_str((string) $request->getBody(), $parsedBody);
}
return $handler->handle(empty($parsedBody) ? $request : $request->withParsedBody($parsedBody));
}
}