You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6KB

  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. namespace yii\web;
  8. use yii\base\InvalidParamException;
  9. use yii\helpers\Json;
  10. /**
  11. * Parses a raw HTTP request using [[\yii\helpers\Json::decode()]]
  12. *
  13. * To enable parsing for JSON requests you can configure [[Request::parsers]] using this class:
  14. *
  15. * ```php
  16. * 'request' => [
  17. * 'parsers' => [
  18. * 'application/json' => 'yii\web\JsonParser',
  19. * ]
  20. * ]
  21. * ```
  22. *
  23. * @author Dan Schmidt <danschmidt5189@gmail.com>
  24. * @since 2.0
  25. */
  26. class JsonParser implements RequestParserInterface
  27. {
  28. /**
  29. * @var boolean whether to return objects in terms of associative arrays.
  30. */
  31. public $asArray = true;
  32. /**
  33. * @var boolean whether to throw a [[BadRequestHttpException]] if the body is invalid json
  34. */
  35. public $throwException = true;
  36. /**
  37. * Parses a HTTP request body.
  38. * @param string $rawBody the raw HTTP request body.
  39. * @param string $contentType the content type specified for the request body.
  40. * @return array parameters parsed from the request body
  41. * @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`.
  42. */
  43. public function parse($rawBody, $contentType)
  44. {
  45. try {
  46. return Json::decode($rawBody, $this->asArray);
  47. } catch (InvalidParamException $e) {
  48. if ($this->throwException) {
  49. throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage(), 0, $e);
  50. }
  51. return null;
  52. }
  53. }
  54. }