BodyParamsMiddleware::process()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 22
ccs 14
cts 14
cp 1
crap 7
rs 8.8333
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