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

JsonBodyParser::withAssoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
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
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(): self
34
    {
35
        $new = clone $this;
36
        $new->assoc = true;
37
        return $new;
38
    }
39
40
    public function withoutAssoc(): self
41
    {
42
        $new = clone $this;
43
        $new->assoc = false;
44
        return $new;
45
    }
46
47
    public function withDepth(int $value): self
48
    {
49
        $new = clone $this;
50
        $new->depth = $value;
51
        return $new;
52
    }
53
54
    public function withOptions(int $value): self
55
    {
56
        $new = clone $this;
57
        $new->options = self::DEFAULT_FLAGS | $value;
58
        return $new;
59
    }
60
61
    public function withThrowException(): self
62
    {
63
        $new = clone $this;
64
        $new->options |= JSON_THROW_ON_ERROR;
65
        return $new;
66
    }
67
68
    public function withoutThrowException(): self
69
    {
70
        $new = clone $this;
71
        $new->options &= ~JSON_THROW_ON_ERROR;
72
        return $new;
73
    }
74
75
    /**
76
     * @return array|object|null
77
     */
78
    private function parse(string $rawBody)
79
    {
80
        $result = \json_decode($rawBody, $this->assoc, $this->depth, $this->options);
81
        if (\is_array($result) || \is_object($result)) {
82
            return $result;
83
        }
84
        return null;
85
    }
86
}
87