JsonParser.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\InvalidArgumentException;
  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 bool whether to return objects in terms of associative arrays.
  30. */
  31. public $asArray = true;
  32. /**
  33. * @var bool 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. $parameters = Json::decode($rawBody, $this->asArray);
  47. return $parameters === null ? [] : $parameters;
  48. } catch (InvalidArgumentException $e) {
  49. if ($this->throwException) {
  50. throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
  51. }
  52. return [];
  53. }
  54. }
  55. }