Completed
Push — 2.1 ( c952e8...98ed49 )
by Carsten
10:00
created

JsonParser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 32
ccs 0
cts 12
cp 0
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A parse() 0 12 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use yii\base\InvalidParamException;
11
use yii\helpers\Json;
12
13
/**
14
 * Parses a raw HTTP request using [[\yii\helpers\Json::decode()]]
15
 *
16
 * To enable parsing for JSON requests you can configure [[Request::parsers]] using this class:
17
 *
18
 * ```php
19
 * 'request' => [
20
 *     'parsers' => [
21
 *         'application/json' => \yii\web\JsonParser::class,
22
 *     ]
23
 * ]
24
 * ```
25
 *
26
 * @author Dan Schmidt <[email protected]>
27
 * @since 2.0
28
 */
29
class JsonParser implements RequestParserInterface
30
{
31
    /**
32
     * @var boolean whether to return objects in terms of associative arrays.
33
     */
34
    public $asArray = true;
35
    /**
36
     * @var boolean whether to throw a [[BadRequestHttpException]] if the body is invalid json
37
     */
38
    public $throwException = true;
39
40
41
    /**
42
     * Parses a HTTP request body.
43
     * @param string $rawBody the raw HTTP request body.
44
     * @param string $contentType the content type specified for the request body.
45
     * @return array parameters parsed from the request body
46
     * @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`.
47
     */
48
    public function parse($rawBody, $contentType)
49
    {
50
        try {
51
            $parameters = Json::decode($rawBody, $this->asArray);
52
            return $parameters === null ? [] : $parameters;
53
        } catch (InvalidParamException $e) {
54
            if ($this->throwException) {
55
                throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
56
            }
57
            return [];
58
        }
59
    }
60
}
61