JsonParser.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. * @author Dan Schmidt <[email protected]>
  14. * @since 2.0
  15. */
  16. class JsonParser implements RequestParserInterface
  17. {
  18. /**
  19. * @var boolean whether to return objects in terms of associative arrays.
  20. */
  21. public $asArray = true;
  22. /**
  23. * @var boolean whether to throw a [[BadRequestHttpException]] if the body is invalid json
  24. */
  25. public $throwException = true;
  26. /**
  27. * Parses a HTTP request body.
  28. * @param string $rawBody the raw HTTP request body.
  29. * @param string $contentType the content type specified for the request body.
  30. * @return array parameters parsed from the request body
  31. * @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`.
  32. */
  33. public function parse($rawBody, $contentType)
  34. {
  35. try {
  36. return Json::decode($rawBody, $this->asArray);
  37. } catch (InvalidParamException $e) {
  38. if ($this->throwException) {
  39. throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage(), 0, $e);
  40. }
  41. return null;
  42. }
  43. }
  44. }