Json::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
/*
4
 * body-parser (https://github.com/juliangut/body-parser).
5
 * PSR7 body parser middleware.
6
 *
7
 * @license BSD-3-Clause
8
 * @link https://github.com/juliangut/body-parser
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
namespace Jgut\BodyParser\Decoder;
13
14
/**
15
 * JSON request decoder.
16
 */
17
class Json implements Decoder
18
{
19
    use MimeTypeTrait;
20
21
    /**
22
     * @var bool
23
     */
24
    protected $assoc;
25
26
    /**
27
     * JSON request decoder constructor.
28
     *
29
     * @param bool $assoc
30
     */
31
    public function __construct($assoc = true)
32
    {
33
        $this->addMimeType('application/json');
34
        $this->addMimeType('text/json');
35
        $this->addMimeType('application/x-json');
36
37
        $this->assoc = (bool) $assoc;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     *
43
     * @throws \RuntimeException
44
     */
45
    public function decode($rawBody)
46
    {
47
        $parsedBody = json_decode($rawBody, $this->assoc, 512, JSON_BIGINT_AS_STRING);
48
49
        if (json_last_error() !== JSON_ERROR_NONE) {
50
            throw new \RuntimeException(sprintf('JSON request body parsing error: %s', json_last_error_msg()));
51
        }
52
53
        return $parsedBody;
54
    }
55
}
56