Completed
Push — master ( 08b488...ad6d35 )
by maxime
02:09
created

JsonContentMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 43
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A process() 0 9 2
A parse() 0 18 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Aidphp\Http\Middleware;
6
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\StreamInterface;
12
use RuntimeException;
13
14
class JsonContentMiddleware implements MiddlewareInterface
15
{
16
    protected $type  = 'application/json';
17
    protected $assoc = true;
18
    protected $depth = 512;
19
    protected $opts  = 0;
20
21 4
    public function __construct(bool $assoc = true, int $depth = 512, int $opts = 0)
22
    {
23 4
        $this->assoc = $assoc;
24 4
        $this->depth = $depth;
25 4
        $this->opts  = $opts;
26 4
    }
27
28 4
    public function process(ServerRequestInterface $req, RequestHandlerInterface $handler): ResponseInterface
29
    {
30 4
        if (0 === stripos($req->getHeaderLine('Content-Type'), $this->type))
31
        {
32 3
            $req = $req->withParsedBody($this->parse($req->getBody()));
33
        }
34
35 3
        return $handler->handle($req);
36
    }
37
38 3
    protected function parse(StreamInterface $body)//: array
39
    {
40 3
        $json = $body->__toString();
41
42 3
        if (! $json)
43
        {
44 1
            return [];
45
        }
46
47 2
        $data = json_decode($json, $this->assoc, $this->depth, $this->opts);
48
49 2
        if (JSON_ERROR_NONE !== json_last_error())
50
        {
51 1
            throw new RuntimeException('Error parsing JSON: ' . json_last_error_msg());
52
        }
53
54 1
        return $data;
55
    }
56
}