Passed
Pull Request — master (#269)
by
unknown
14:23
created

JsonBodyParser::withThrowException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 1
b 1
f 0
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 const DEFAULT_FLAGS = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE;
16
    private bool $assoc = true;
17
    private int $depth = 512;
18
    private int $options = self::DEFAULT_FLAGS;
19
    private bool $throwException = true;
20
21
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
22
    {
23
        $contentType = $request->getHeaderLine(Header::CONTENT_TYPE);
24
25
        if ($contentType && \strpos(\strtolower($contentType), 'application/json') !== false) {
26
            $request = $request->withParsedBody(
27
                $this->parse($request->getBody()->getContents())
28
            );
29
        }
30
31
        return $handler->handle($request);
32
    }
33
34
    public function withAssoc(): self
35
    {
36
        $new = clone $this;
37
        $new->assoc = true;
38
        return $new;
39
    }
40
41
    public function withoutAssoc(): self
42
    {
43
        $new = clone $this;
44
        $new->assoc = false;
45
        return $new;
46
    }
47
48
    public function withDepth(int $value): self
49
    {
50
        $new = clone $this;
51
        $new->depth = $value;
52
        return $new;
53
    }
54
55
    public function withOptions(int $value): self
56
    {
57
        $new = clone $this;
58
        $new->options = self::DEFAULT_FLAGS | $value;
59
        return $new;
60
    }
61
62
    public function withThrowException(): self
63
    {
64
        $new = clone $this;
65
        $new->throwException = true;
66
        return $new;
67
    }
68
69
    public function withoutThrowException(): self
70
    {
71
        $new = clone $this;
72
        $new->throwException = false;
73
        return $new;
74
    }
75
76
    /**
77
     * @return array|object|null
78
     */
79
    private function parse(string $rawBody)
80
    {
81
        $result = \json_decode(
82
            $rawBody,
83
            $this->assoc,
84
            $this->depth,
85
            $this->throwException
86
                ? $this->options
87
                : $this->options & ~JSON_THROW_ON_ERROR
88
        );
89
        if (\is_array($result) || \is_object($result)) {
90
            return $result;
91
        }
92
        return null;
93
    }
94
}
95