Passed
Pull Request — master (#269)
by
unknown
10:59
created

JsonBodyParser::parse()   A

Complexity

Conditions 4
Paths 7

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 10
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
12
final class JsonBodyParser implements MiddlewareInterface
13
{
14
    private bool $throwException = true;
15
16
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
17
    {
18
        $contentType = $request->getHeaderLine('Content-Type');
19
20
        if ($contentType && strpos(strtolower($contentType), 'application/json') !== false) {
21
            $request = $request->withParsedBody(
22
                $this->parse($request->getBody()->getContents())
23
            );
24
        }
25
26
        return $handler->handle($request);
27
    }
28
29
    public function throwException(bool $value): self
30
    {
31
        $new = clone $this;
32
        $new->throwException = $value;
33
        return $new;
34
    }
35
36
    private function parse(string $body): array
37
    {
38
        try {
39
            $result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
40
            return is_array($result) ? $result : [];
41
        } catch (\JsonException $e) {
42
            if ($this->throwException) {
43
                throw new \InvalidArgumentException('Invalid JSON data in request body: ' . $e->getMessage());
44
            }
45
            return [];
46
        }
47
    }
48
}
49