Passed
Pull Request — master (#269)
by
unknown
11:28
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 bool $throwException = true;
17
18
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
19
    {
20
        $contentType = $request->getHeaderLine(Header::CONTENT_TYPE);
21
22
        if ($contentType && strpos(strtolower($contentType), 'application/json') !== false) {
23
            $request = $request->withParsedBody(
24
                $this->parse($request->getBody()->getContents())
25
            );
26
        }
27
28
        return $handler->handle($request);
29
    }
30
31
    public function withAssoc(bool $value): self
32
    {
33
        $new = clone $this;
34
        $new->assoc = $value;
35
        return $new;
36
    }
37
38
    public function withThrowException(bool $value): self
39
    {
40
        $new = clone $this;
41
        $new->throwException = $value;
42
        return $new;
43
    }
44
45
    /**
46
     * @return mixed
47
     */
48
    private function parse(string $body)
49
    {
50
        try {
51
            $result = json_decode($body, $this->assoc, 512, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE);
52
            if (($this->assoc === true && is_array($result)) || ($this->assoc === false && is_object($result))) {
53
                return $result;
54
            }
55
        } catch (\JsonException $e) {
56
            if ($this->throwException) {
57
                throw new \InvalidArgumentException('Invalid JSON data in request body: ' . $e->getMessage());
58
            }
59
        }
60
        return null;
61
    }
62
}
63