Passed
Push — master ( 197709...9b4e33 )
by Alexander
02:36
created

JsonParser   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 15
c 1
b 0
f 0
dl 0
loc 38
ccs 14
cts 14
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A parse() 0 17 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
use function is_array;
11
use function is_object;
12
use function json_decode;
13
14
/**
15
 * Parses `application/json` requests where JSON is in the body.
16
 */
17
final class JsonParser implements ParserInterface
18
{
19
    private bool $convertToAssociativeArray;
20
    private int $depth;
21
    private int $options;
22
23
    /**
24
     * @param bool $convertToAssociativeArray Whether objects should be converted to associative array during parsing.
25
     * @param int $depth Maximum JSON recursion depth.
26
     * @param int $options JSON decoding options. {@see json_decode()}.
27
     */
28 11
    public function __construct(
29
        bool $convertToAssociativeArray = true,
30
        int $depth = 512,
31
        int $options = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE
32
    ) {
33 11
        $this->convertToAssociativeArray = $convertToAssociativeArray;
34 11
        $this->depth = $depth;
35 11
        $this->options = $options;
36 11
    }
37
38 8
    public function parse(string $rawBody)
39
    {
40 8
        if ($rawBody === '') {
41 1
            return null;
42
        }
43
44
        try {
45
            /** @var mixed $result */
46 7
            $result = json_decode($rawBody, $this->convertToAssociativeArray, $this->depth, $this->options);
47 4
            if (is_array($result) || is_object($result)) {
48 4
                return $result;
49
            }
50 3
        } catch (JsonException $e) {
51 3
            throw new ParserException('Invalid JSON data in request body: ' . $e->getMessage());
52
        }
53
54 2
        return null;
55
    }
56
}
57