Passed
Pull Request — master (#269)
by
unknown
12:09 queued 10s
created

JsonBodyParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 7
Bugs 1 Features 2
Metric Value
eloc 17
c 7
b 1
f 2
dl 0
loc 44
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A parse() 0 7 3
A isJsonRequest() 0 5 2
A process() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Yiisoft\Http\Header;
12
13
final class JsonBodyParser implements MiddlewareInterface
14
{
15
    private bool $assoc;
16
    private int $depth;
17
    private int $options;
18
19
    public function __construct(
20
        bool $assoc = true,
21
        int $depth = 512,
22
        int $options = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE
23
    ) {
24
        $this->assoc = $assoc;
25
        $this->depth = $depth;
26
        $this->options = $options;
27
    }
28
29
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
30
    {
31
        if ($this->isJsonRequest($request)) {
32
            $request = $request->withParsedBody(
33
                $this->parse($request->getBody()->getContents())
34
            );
35
        }
36
37
        return $handler->handle($request);
38
    }
39
40
    private function isJsonRequest(ServerRequestInterface $request): bool
41
    {
42
        $contentType = $request->getHeaderLine(Header::CONTENT_TYPE);
43
44
        return $contentType && stripos($contentType, 'application/json') !== false;
45
    }
46
47
    /**
48
     * @return array|object|null
49
     */
50
    private function parse(string $rawBody)
51
    {
52
        $result = \json_decode($rawBody, $this->assoc, $this->depth, $this->options);
53
        if (\is_array($result) || \is_object($result)) {
54
            return $result;
55
        }
56
        return null;
57
    }
58
}
59