Passed
Push — master ( cc9651...b913e4 )
by Jelmer
05:03
created

JsonRequestParserMiddleware::parseBody()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.032
1
<?php declare(strict_types = 1);
2
3
namespace jschreuder\Middle\ServerMiddleware;
4
5
use Interop\Http\ServerMiddleware\DelegateInterface;
6
use Interop\Http\ServerMiddleware\MiddlewareInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
10
final class JsonRequestParserMiddleware implements MiddlewareInterface
11
{
12
    /** @var  string[]  array of regexes to check against content-types */
13
    private $jsonContentTypes;
14
15 5
    public function __construct(array $jsonContentTypes = null)
16
    {
17 5
        if (is_null($jsonContentTypes)) {
18 4
            $jsonContentTypes = ['#^application\/json(;|$)#iD'];
19
        }
20 5
        $this->jsonContentTypes = $jsonContentTypes;
21 5
    }
22
23 4
    public function process(ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface
24
    {
25 4
        if ($this->isJsonRequest($request->getHeaderLine('Content-Type'))) {
26 3
            $request = $request->withParsedBody($this->parseBody($request));
27
        }
28 4
        return $delegate->process($request);
29
    }
30
31 4
    private function isJsonRequest(?string $requestContentType)
32
    {
33 4
        foreach ($this->jsonContentTypes as $jsonContentType) {
34 4
            if (preg_match($jsonContentType, $requestContentType) > 0) {
35 4
                return true;
36
            }
37
        }
38 1
        return false;
39
    }
40
41 3
    private function parseBody(ServerRequestInterface $request) : array
42
    {
43 3
        $parsedBody = json_decode($request->getBody()->getContents(), true);
44 3
        if (json_last_error() !== JSON_ERROR_NONE) {
45
            throw new \InvalidArgumentException('Could not decode JSON body: ' . json_last_error_msg());
46
        }
47
48 3
        return $parsedBody;
49
    }
50
}
51