Passed
Pull Request — master (#269)
by
unknown
12:26
created

JsonBodyParser::parse()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
cc 3
eloc 4
c 4
b 0
f 1
nc 2
nop 1
dl 0
loc 7
rs 10
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