JsonRequestParserMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 12
c 3
b 0
f 0
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A isJsonRequest() 0 8 3
A process() 0 6 2
A parseBody() 0 8 2
1
<?php declare(strict_types=1);
2
3
namespace jschreuder\Middle\ServerMiddleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
10
final class JsonRequestParserMiddleware implements MiddlewareInterface
11
{
12
    /** @param  string[]  $jsonContentTypes  array of regexes to check against content-types */
13 7
    public function __construct(
14
        private readonly array $jsonContentTypes = ['#^application\/json(;|$)#iD']
15 7
    ) {}
16
17 6
    public function process(ServerRequestInterface $request, RequestHandlerInterface $requestHandler): ResponseInterface
18
    {
19 6
        if ($this->isJsonRequest($request->getHeaderLine('Content-Type'))) {
20 5
            $request = $request->withParsedBody($this->parseBody($request));
21
        }
22 5
        return $requestHandler->handle($request);
23
    }
24
25 6
    private function isJsonRequest(string $requestContentType) : bool
26
    {
27 6
        foreach ($this->jsonContentTypes as $jsonContentType) {
28 6
            if (preg_match($jsonContentType, $requestContentType) > 0) {
29 5
                return true;
30
            }
31
        }
32 1
        return false;
33
    }
34
35 5
    private function parseBody(ServerRequestInterface $request) : array
36
    {
37 5
        $parsedBody = json_decode($request->getBody()->getContents(), true);
38 5
        if (json_last_error() !== JSON_ERROR_NONE) {
39 1
            throw new \InvalidArgumentException('Could not decode JSON body: ' . json_last_error_msg());
40
        }
41
42 4
        return $parsedBody;
43
    }
44
}
45