Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

61 linhas
1.7KB

  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. $parameters = Json::decode($rawBody, $this->asArray);
  47. return $parameters === null ? [] : $parameters;
  48. } catch (InvalidParamException $e) {
  49. if ($this->throwException) {
  50. throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
  51. }
  52. return [];
  53. }
  54. }
  55. }