Passed
Push — master ( b3f945...fcf496 )
by Jelmer
04:58
created

JsonRequestParserMiddleware::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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