Passed
Pull Request — master (#269)
by
unknown
22:18 queued 07:10
created

JsonBodyParser::process()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 11
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 = true;
16
    private int $depth = 512;
17
    private int $options = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE;
18
    private bool $throwException = true;
19
20
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
21
    {
22
        $contentType = $request->getHeaderLine(Header::CONTENT_TYPE);
23
24
        if ($contentType && strpos(strtolower($contentType), 'application/json') !== false) {
25
            $request = $request->withParsedBody(
26
                $this->parse($request->getBody()->getContents())
27
            );
28
        }
29
30
        return $handler->handle($request);
31
    }
32
33
    public function withAssoc(bool $value): self
34
    {
35
        $new = clone $this;
36
        $new->assoc = $value;
37
        return $new;
38
    }
39
40
    public function withDepth(int $value): self
41
    {
42
        $new = clone $this;
43
        $new->depth = $value;
44
        return $new;
45
    }
46
47
    public function withOptions(int $value): self
48
    {
49
        $new = clone $this;
50
        $new->options = $value;
51
        return $new;
52
    }
53
54
    public function withThrowException(bool $value): self
55
    {
56
        $new = clone $this;
57
        $new->throwException = $value;
58
        return $new;
59
    }
60
61
    /**
62
     * @return mixed
63
     */
64
    private function parse(string $body)
65
    {
66
        try {
67
            $result = json_decode($body, $this->assoc, $this->depth, $this->options);
68
            if (is_array($result) || is_object($result)) {
69
                return $result;
70
            }
71
        } catch (\JsonException $e) {
72
            if ($this->throwException) {
73
                throw new \InvalidArgumentException('Invalid JSON data in request body: ' . $e->getMessage());
74
            }
75
        }
76
        return null;
77
    }
78
}
79