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