JsonParser::parse()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.6111
cc 5
nc 5
nop 1
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Request\Body\Parser;
6
7
use JsonException;
8
use Yiisoft\Request\Body\ParserException;
9
use Yiisoft\Request\Body\ParserInterface;
10
11
use function is_array;
12
use function is_object;
13
use function json_decode;
14
15
/**
16
 * Parses `application/json` requests where JSON is in the body.
17
 */
18
final class JsonParser implements ParserInterface
19
{
20
    private bool $convertToAssociativeArray;
21
    private int $depth;
22
    private int $options;
23
24
    /**
25
     * @param bool $convertToAssociativeArray Whether objects should be converted to associative array during parsing.
26
     * @param int $depth Maximum JSON recursion depth.
27
     * @param int $options JSON decoding options. {@see json_decode()}.
28
     */
29 11
    public function __construct(
30
        bool $convertToAssociativeArray = true,
31
        int $depth = 512,
32
        int $options = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE
33
    ) {
34 11
        $this->convertToAssociativeArray = $convertToAssociativeArray;
35 11
        $this->depth = $depth;
36 11
        $this->options = $options;
37
    }
38
39 8
    public function parse(string $rawBody)
40
    {
41 8
        if ($rawBody === '') {
42 1
            return null;
43
        }
44
45
        try {
46
            /** @var mixed $result */
47 7
            $result = json_decode($rawBody, $this->convertToAssociativeArray, $this->depth, $this->options);
48 4
            if (is_array($result) || is_object($result)) {
49 4
                return $result;
50
            }
51 3
        } catch (JsonException $e) {
52 3
            throw new ParserException('Invalid JSON data in request body: ' . $e->getMessage());
53
        }
54
55 2
        return null;
56
    }
57
}
58