1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license https://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\web; |
9
|
|
|
|
10
|
|
|
use yii\base\InvalidArgumentException; |
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', |
22
|
|
|
* ] |
23
|
|
|
* ] |
24
|
|
|
* ``` |
25
|
|
|
* |
26
|
|
|
* @author Dan Schmidt <[email protected]> |
27
|
|
|
* @since 2.0 |
28
|
|
|
*/ |
29
|
|
|
class JsonParser implements RequestParserInterface |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* @var bool whether to return objects in terms of associative arrays. |
33
|
|
|
*/ |
34
|
|
|
public $asArray = true; |
35
|
|
|
/** |
36
|
|
|
* @var bool 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|\stdClass parameters parsed from the request body |
46
|
|
|
* @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`. |
47
|
|
|
*/ |
48
|
2 |
|
public function parse($rawBody, $contentType) |
49
|
|
|
{ |
50
|
|
|
// converts JSONP to JSON |
51
|
2 |
|
if (strpos($contentType, 'application/javascript') !== false) { |
52
|
1 |
|
$rawBody = preg_filter('/(^[^{]+|[^}]+$)/', '', $rawBody); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
try { |
56
|
2 |
|
$parameters = Json::decode($rawBody, $this->asArray); |
|
|
|
|
57
|
2 |
|
return $parameters === null ? [] : $parameters; |
58
|
|
|
} catch (InvalidArgumentException $e) { |
59
|
|
|
if ($this->throwException) { |
60
|
|
|
throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return []; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|