Passed
Pull Request — master (#269)
by
unknown
14:09 queued 16s
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
c 1
b 1
f 0
nc 1
nop 1
dl 0
loc 5
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 $throwException = true;
16
17
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
18
    {
19
        $contentType = $request->getHeaderLine(Header::CONTENT_TYPE);
20
21
        if ($contentType && strpos(strtolower($contentType), 'application/json') !== false) {
22
            $request = $request->withParsedBody(
23
                $this->parse($request->getBody()->getContents())
24
            );
25
        }
26
27
        return $handler->handle($request);
28
    }
29
30
    public function withThrowException(bool $value): self
31
    {
32
        $new = clone $this;
33
        $new->throwException = $value;
34
        return $new;
35
    }
36
37
    private function parse(string $body): array
38
    {
39
        try {
40
            $result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
41
            return is_array($result) ? $result : [];
42
        } catch (\JsonException $e) {
43
            if ($this->throwException) {
44
                throw new \InvalidArgumentException('Invalid JSON data in request body: ' . $e->getMessage());
45
            }
46
            return [];
47
        }
48
    }
49
}
50