JsonParser.php 969 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use yii\base\InvalidParamException;
use yii\helpers\Json;

/**
 * Parses a raw HTTP request using Json::encode()
 *
 * @author Dan Schmidt <danschmidt5189@gmail.com>
 * @since 2.0
 */
class JsonParser implements RequestParserInterface
{
Daniel Schmidt committed
21 22 23 24
	/**
	 * @var boolean whether to return objects in terms of associative arrays.
	 */
	public $asArray = true;
25

Daniel Schmidt committed
26 27 28 29
	/**
	 * @var boolean whether to throw an exception if the body is invalid json
	 */
	public $throwException = false;
30

Daniel Schmidt committed
31 32 33 34
	/**
	 * @param string $rawBody the raw HTTP request body
	 * @return array parameters parsed from the request body
	 */
35
	public function parse($rawBody)
Daniel Schmidt committed
36 37
	{
		try {
38
			return Json::decode($rawBody, $this->asArray);
Daniel Schmidt committed
39 40 41 42 43 44 45
		} catch (InvalidParamException $e) {
			if ($this->throwException) {
				throw $e;
			}
			return null;
		}
	}
46
}