Commit 7f8850bc by Daniel Schmidt

Adds customizable parsing functionality to the web\Request class (Issue #2043)

parent 12eca516
<?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
{
/**
* @var boolean whether to return objects in terms of associative arrays.
*/
public $asArray = true;
/**
* @var boolean whether to throw an exception if the body is invalid json
*/
public $throwException = false;
/**
* @param string $rawBody the raw HTTP request body
* @return array parameters parsed from the request body
*/
public function parse($rawBody)
{
try {
return Json::encode($rawBody, $this->asArray);
} catch (InvalidParamException $e) {
if ($this->throwException) {
throw $e;
}
return null;
}
}
}
......@@ -128,6 +128,13 @@ class Request extends \yii\base\Request
* @see getRestParams()
*/
public $restVar = '_method';
/**
* @var array the parsers for converting the raw request body into [[restParams]]
* The array keys are the request content-types, and the array values are the
* corresponding configurations for creating the parser objects.
* @see getRestParams()
*/
public $parsers = [];
private $_cookies;
......@@ -257,8 +264,12 @@ class Request extends \yii\base\Request
if ($this->_restParams === null) {
if (isset($_POST[$this->restVar])) {
$this->_restParams = $_POST;
} elseif(strncmp($this->getContentType(), 'application/json', 16) === 0) {
$this->_restParams = Json::decode($this->getRawBody(), true);
} else if (isset($this->parsers[$this->getContentType()])) {
$parser = Yii::createObject($this->parsers[$this->getContentType()]);
if (! $parser instanceof RequestParserInterface) {
throw new InvalidConfigException("The '{$this->contentType}' request parser is invalid. It must implement the RequestParserInterface.");
}
$this->_restParams = $parser->parse($this->getRawBody());
} else {
$this->_restParams = [];
mb_parse_str($this->getRawBody(), $this->_restParams);
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
/**
* Interface for objects that parse the raw request body into a parameters array
*
* @author Dan Schmidt <danschmidt5189@gmail.com>
* @since 2.0
*/
interface RequestParserInterface
{
/**
* @param string $rawBody the raw HTTP request body
* @return array parameters parsed from the request body
*/
public function parse($rawBody);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment