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

JsonRequestParserMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 31
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A process() 0 7 2
A parseBody() 0 9 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
}