Add defaultDecoder for parseResponse

This commit is contained in:
Rambo
2016-05-19 19:14:18 +08:00
parent 1e100063a3
commit 1cf7bc169a
2 changed files with 28 additions and 0 deletions
+2
View File
@@ -1,2 +1,4 @@
vendor/
composer.lock
.idea/
+26
View File
@@ -80,6 +80,7 @@ class Curl
private $jsonPattern = '/^(?:application|text)\/(?:[a-z]+(?:[\.-][0-9a-z]+){0,}[\+\.]|x-)?json(?:-[a-z]+)?/i';
private $xmlDecoder = null;
private $xmlPattern = '~^(?:text/|application/(?:atom\+|rss\+)?)xml~i';
private $defaultDecoder = null;
/**
* Construct
@@ -99,6 +100,7 @@ class Curl
$this->setDefaultUserAgent();
$this->setDefaultJsonDecoder();
$this->setDefaultXmlDecoder();
$this->setDefaultDecoder();
$this->setDefaultTimeout();
$this->setOpt(CURLINFO_HEADER_OUT, true);
$this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'headerCallback'));
@@ -752,6 +754,25 @@ class Curl
};
}
/**
* Set Default Decoder
*
* @access public
* @param $decoder string|callable
*/
public function setDefaultDecoder($decoder = 'json')
{
if (is_callable($decoder)) {
$this->defaultDecoder = $decoder;
} else {
if ($decoder === 'json') {
$this->defaultDecoder = $this->jsonDecoder;
} elseif ($decoder === 'xml') {
$this->defaultDecoder = $this->xmlDecoder;
}
}
}
/**
* Set Default Timeout
*
@@ -1036,6 +1057,11 @@ class Curl
if (is_callable($xml_decoder)) {
$response = $xml_decoder($response);
}
} else {
$decoder = $this->defaultDecoder;
if (is_callable($decoder)) {
$response = $decoder($response);
}
}
}