Commit bd210511 authored by shajiaiming's avatar shajiaiming

调整请求时间

parent 176cbc54
...@@ -8,612 +8,656 @@ use yii\helpers\Json; ...@@ -8,612 +8,656 @@ use yii\helpers\Json;
class Curl class Curl
{ {
/** /**
* @var string * @var string
* * Holds response data right after sending a request. * * Holds response data right after sending a request.
*/ */
public $httpType = 'http'; public $httpType = 'http';
/** /**
* @var string|boolean * @var string|boolean
* Holds response data right after sending a request. * Holds response data right after sending a request.
*/ */
public $response = null; public $response = null;
/** /**
* @var null|integer * @var null|integer
* Error code holder: https://curl.haxx.se/libcurl/c/libcurl-errors.html * Error code holder: https://curl.haxx.se/libcurl/c/libcurl-errors.html
*/ */
public $errorCode = null; public $errorCode = null;
/** /**
* @var null|string * @var null|string
* Error text holder: http://php.net/manual/en/function.curl-strerror.php * Error text holder: http://php.net/manual/en/function.curl-strerror.php
*/ */
public $errorText = null; public $errorText = null;
/** /**
* @var integer HTTP-Status Code * @var integer HTTP-Status Code
* This value will hold HTTP-Status Code. False if request was not successful. * This value will hold HTTP-Status Code. False if request was not successful.
*/ */
public $responseCode = null; public $responseCode = null;
/** /**
* @var string|null HTTP Response Charset * @var string|null HTTP Response Charset
* (taken from Content-type header) * (taken from Content-type header)
*/ */
public $responseCharset = null; public $responseCharset = null;
/** /**
* @var int HTTP Response Length * @var int HTTP Response Length
* (taken from Content-length header, or strlen() of downloaded content) * (taken from Content-length header, or strlen() of downloaded content)
*/ */
public $responseLength = -1; public $responseLength = -1;
/** /**
* @var string|null HTTP Response Content Type * @var string|null HTTP Response Content Type
* (taken from Content-type header) * (taken from Content-type header)
*/ */
public $responseType = null; public $responseType = null;
/** /**
* @var array|null HTTP Response headers * @var array|null HTTP Response headers
* Lists response header in an array if CURLOPT_HEADER is set to true. * Lists response header in an array if CURLOPT_HEADER is set to true.
*/ */
public $responseHeaders = null; public $responseHeaders = null;
/** /**
* @var array HTTP-Status Code * @var array HTTP-Status Code
* Custom options holder * Custom options holder
*/ */
protected $_options = []; protected $_options = [];
/** /**
* @var array * @var array
* Hold array of get params to send with the request * Hold array of get params to send with the request
*/ */
protected $_getParams = []; protected $_getParams = [];
/** /**
* @var array * @var array
* Hold array of post params to send with the request * Hold array of post params to send with the request
*/ */
protected $_postParams = []; protected $_postParams = [];
/** /**
* @var resource|null * @var resource|null
* Holds cURL-Handler * Holds cURL-Handler
*/ */
public $curl = null; public $curl = null;
/** /**
* @var string * @var string
* hold base URL * hold base URL
*/ */
protected $_baseUrl = ''; protected $_baseUrl = '';
/** /**
* @var array default curl options * @var array default curl options
* Default curl options * Default curl options
*/ */
protected $_defaultOptions = [ protected $_defaultOptions = [
CURLOPT_USERAGENT => 'Yii2-Curl-Agent', CURLOPT_USERAGENT => 'Yii2-Curl-Agent',
CURLOPT_TIMEOUT => 10, CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true, CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYHOST => 2,
]; ];
// ############################################### class methods // ############################################## // ############################################### class methods // ##############################################
/** /**
* Start performing GET-HTTP-Request * Start performing GET-HTTP-Request
* *
* @param string $url * @param string $url
* @param boolean $raw if response body contains JSON and should be decoded * @param boolean $raw if response body contains JSON and should be decoded
* *
* @return mixed response * @return mixed response
*/ */
public function get($url, $raw = true) protected $connect_timeout_ms;
{ protected $timeout_ms;
$this->_baseUrl = $url;
return $this->_httpRequest('GET', $raw); public function __construct($config = [])
} {
/** if (!empty($config)) {
* Start performing HEAD-HTTP-Request $this->connect_timeout_ms = isset($config['connect_timeout']) ? $config['connect_timeout'] : 10;
* $this->timeout_ms = isset($config['timeout_ms']) ? $config['timeout_ms'] : 100;
* @param string $url }
* }
* @return mixed response
*/
public function head($url) public function get($url, $raw = true)
{ {
$this->_baseUrl = $url; $this->_baseUrl = $url;
return $this->_httpRequest('HEAD'); return $this->_httpRequest('GET', $raw);
} }
/**
* Start performing POST-HTTP-Request /**
* * Start performing HEAD-HTTP-Request
* @param string $url *
* @param boolean $raw if response body contains JSON and should be decoded * @param string $url
* *
* @return mixed response * @return mixed response
*/ */
public function post($url, $raw = true) public function head($url)
{ {
$this->_baseUrl = $url; $this->_baseUrl = $url;
return $this->_httpRequest('POST', $raw); return $this->_httpRequest('HEAD');
} }
/**
* Start performing PUT-HTTP-Request /**
* * Start performing POST-HTTP-Request
* @param string $url *
* @param boolean $raw if response body contains JSON and should be decoded * @param string $url
* * @param boolean $raw if response body contains JSON and should be decoded
* @return mixed response *
*/ * @return mixed response
public function put($url, $raw = true) */
{ public function post($url, $raw = true)
$this->_baseUrl = $url; {
return $this->_httpRequest('PUT', $raw); $this->_baseUrl = $url;
} return $this->_httpRequest('POST', $raw);
/** }
* Start performing PATCH-HTTP-Request
* /**
* @param string $url * Start performing PUT-HTTP-Request
* @param boolean $raw if response body contains JSON and should be decoded *
* * @param string $url
* @return mixed response * @param boolean $raw if response body contains JSON and should be decoded
*/ *
public function patch($url, $raw = true) * @return mixed response
{ */
$this->_baseUrl = $url; public function put($url, $raw = true)
$this->setHeaders([ {
'X-HTTP-Method-Override' => 'PATCH' $this->_baseUrl = $url;
]); return $this->_httpRequest('PUT', $raw);
return $this->_httpRequest('POST',$raw); }
}
/** /**
* Start performing DELETE-HTTP-Request * Start performing PATCH-HTTP-Request
* *
* @param string $url * @param string $url
* @param boolean $raw if response body contains JSON and should be decoded * @param boolean $raw if response body contains JSON and should be decoded
* *
* @return mixed response * @return mixed response
*/ */
public function delete($url, $raw = true) public function patch($url, $raw = true)
{ {
$this->_baseUrl = $url; $this->_baseUrl = $url;
return $this->_httpRequest('DELETE', $raw); $this->setHeaders([
} 'X-HTTP-Method-Override' => 'PATCH'
/** ]);
* Set curl option return $this->_httpRequest('POST', $raw);
* }
* @param string $key
* @param mixed $value /**
* * Start performing DELETE-HTTP-Request
* @return $this *
*/ * @param string $url
public function setOption($key, $value) * @param boolean $raw if response body contains JSON and should be decoded
{ *
//set value * @return mixed response
if (array_key_exists($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) { */
$this->_defaultOptions[$key] = $value; public function delete($url, $raw = true)
} else { {
$this->_options[$key] = $value; $this->_baseUrl = $url;
} return $this->_httpRequest('DELETE', $raw);
//return self }
return $this;
} /**
/** * Set curl option
* Set get params *
* * @param string $key
* @param array $params * @param mixed $value
* @return $this *
*/ * @return $this
public function setGetParams($params) */
{ public function setOption($key, $value)
if (is_array($params)) { {
foreach ($params as $key => $value) { //set value
$this->_getParams[$key] = $value; if (array_key_exists($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) {
} $this->_defaultOptions[$key] = $value;
} } else {
//return self $this->_options[$key] = $value;
return $this; }
} //return self
/** return $this;
* Set get params }
*
* @param array $params /**
* @return $this * Set get params
*/ *
public function setPostParams($params) * @param array $params
{ * @return $this
if (is_array($params)) { */
$this->setOption( public function setGetParams($params)
CURLOPT_POSTFIELDS, {
http_build_query($params) if (is_array($params)) {
); foreach ($params as $key => $value) {
} $this->_getParams[$key] = $value;
//return self }
return $this; }
} //return self
/** return $this;
* Set raw post data allows you to post any data format. }
*
* @param mixed $data /**
* @return $this * Set get params
*/ *
public function setRawPostData($data) * @param array $params
{ * @return $this
$this->setOption( */
CURLOPT_POSTFIELDS, public function setPostParams($params)
$data {
); if (is_array($params)) {
//return self $this->setOption(
return $this; CURLOPT_POSTFIELDS,
} http_build_query($params)
/** );
* Set get params }
* //return self
* @param string $data return $this;
* @return $this }
*/
public function setRequestBody($data) /**
{ * Set raw post data allows you to post any data format.
if (is_string($data)) { *
$this->setOption( * @param mixed $data
CURLOPT_POSTFIELDS, * @return $this
$data */
); public function setRawPostData($data)
} {
//return self $this->setOption(
return $this; CURLOPT_POSTFIELDS,
} $data
/** );
* Get URL - return URL parsed with given params //return self
* return $this;
* @return string The full URL with parsed get params }
*/
public function getUrl() /**
{ * Set get params
if (Count($this->_getParams) > 0) { *
return $this->_baseUrl.'?'.http_build_query($this->_getParams); * @param string $data
} else { * @return $this
return $this->_baseUrl; */
} public function setRequestBody($data)
} {
/** if (is_string($data)) {
* Set curl options $this->setOption(
* CURLOPT_POSTFIELDS,
* @param array $options $data
* );
* @return $this }
*/ //return self
public function setOptions($options) return $this;
{ }
$this->_options = $options + $this->_options;
return $this; /**
} * Get URL - return URL parsed with given params
/** *
* Set multiple headers for request. * @return string The full URL with parsed get params
* */
* @param array $headers public function getUrl()
* {
* @return $this if (Count($this->_getParams) > 0) {
*/ return $this->_baseUrl . '?' . http_build_query($this->_getParams);
public function setHeaders($headers) } else {
{ return $this->_baseUrl;
if (is_array($headers)) { }
//init }
$parsedHeader = [];
//collect currently set headers /**
foreach ($this->getRequestHeaders() as $header => $value) { * Set curl options
array_push($parsedHeader, $header.':'.$value); *
} * @param array $options
//parse header into right format key:value *
foreach ($headers as $header => $value) { * @return $this
array_push($parsedHeader, $header.':'.$value); */
} public function setOptions($options)
//set headers {
$this->setOption( $this->_options = $options + $this->_options;
CURLOPT_HTTPHEADER, return $this;
$parsedHeader }
);
} /**
return $this; * Set multiple headers for request.
} *
/** * @param array $headers
* Set a single header for request. *
* * @return $this
* @param string $header */
* @param string $value public function setHeaders($headers)
* {
* @return $this if (is_array($headers)) {
*/ //init
public function setHeader($header, $value) $parsedHeader = [];
{ //collect currently set headers
//init foreach ($this->getRequestHeaders() as $header => $value) {
$parsedHeader = []; array_push($parsedHeader, $header . ':' . $value);
//collect currently set headers }
foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) { //parse header into right format key:value
array_push($parsedHeader, $headerToSet.':'.$valueToSet); foreach ($headers as $header => $value) {
} array_push($parsedHeader, $header . ':' . $value);
//add override new header }
if (strlen($header) > 0) { //set headers
array_push($parsedHeader, $header.':'.$value); $this->setOption(
} CURLOPT_HTTPHEADER,
//set headers $parsedHeader
$this->setOption( );
CURLOPT_HTTPHEADER, }
$parsedHeader return $this;
); }
return $this;
} /**
/** * Set a single header for request.
* Unset a single header. *
* * @param string $header
* @param string $header * @param string $value
* *
* @return $this * @return $this
*/ */
public function unsetHeader($header) public function setHeader($header, $value)
{ {
//init //init
$parsedHeader = []; $parsedHeader = [];
//collect currently set headers and filter "unset" header param. //collect currently set headers
foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) { foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) {
if ($header !== $headerToSet) { array_push($parsedHeader, $headerToSet . ':' . $valueToSet);
array_push($parsedHeader, $headerToSet.':'.$valueToSet); }
} //add override new header
} if (strlen($header) > 0) {
//set headers array_push($parsedHeader, $header . ':' . $value);
$this->setOption( }
CURLOPT_HTTPHEADER, //set headers
$parsedHeader $this->setOption(
); CURLOPT_HTTPHEADER,
return $this; $parsedHeader
} );
/** return $this;
* Get all request headers as key:value array }
*
* @return array /**
*/ * Unset a single header.
public function getRequestHeaders() *
{ * @param string $header
//Init *
$requestHeaders = $this->getOption(CURLOPT_HTTPHEADER); * @return $this
$parsedRequestHeaders = []; */
if (is_array($requestHeaders)) { public function unsetHeader($header)
foreach ($requestHeaders as $headerValue) { {
list ($key, $value) = explode(':', $headerValue, 2); //init
$parsedRequestHeaders[$key] = $value; $parsedHeader = [];
} //collect currently set headers and filter "unset" header param.
} foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) {
return $parsedRequestHeaders; if ($header !== $headerToSet) {
} array_push($parsedHeader, $headerToSet . ':' . $valueToSet);
/** }
* Get specific request header as key:value array }
* //set headers
* @param string $headerKey $this->setOption(
* CURLOPT_HTTPHEADER,
* @return string|null $parsedHeader
*/ );
public function getRequestHeader($headerKey) return $this;
{ }
//Init
$parsedRequestHeaders = $this->getRequestHeaders(); /**
return isset($parsedRequestHeaders[$headerKey]) ? $parsedRequestHeaders[$headerKey] : null; * Get all request headers as key:value array
} *
/** * @return array
* Unset a single curl option */
* public function getRequestHeaders()
* @param string $key {
* //Init
* @return $this $requestHeaders = $this->getOption(CURLOPT_HTTPHEADER);
*/ $parsedRequestHeaders = [];
public function unsetOption($key) if (is_array($requestHeaders)) {
{ foreach ($requestHeaders as $headerValue) {
//reset a single option if its set already list ($key, $value) = explode(':', $headerValue, 2);
if (isset($this->_options[$key])) { $parsedRequestHeaders[$key] = $value;
unset($this->_options[$key]); }
} }
return $this; return $parsedRequestHeaders;
} }
/**
* Unset all curl option, excluding default options. /**
* * Get specific request header as key:value array
* @return $this *
*/ * @param string $headerKey
public function unsetOptions() *
{ * @return string|null
//reset all options */
if (isset($this->_options)) { public function getRequestHeader($headerKey)
$this->_options = []; {
} //Init
return $this; $parsedRequestHeaders = $this->getRequestHeaders();
} return isset($parsedRequestHeaders[$headerKey]) ? $parsedRequestHeaders[$headerKey] : null;
/** }
* Total reset of options, responses, etc.
* /**
* @return $this * Unset a single curl option
*/ *
public function reset() * @param string $key
{ *
if ($this->curl !== null) { * @return $this
curl_close($this->curl); //stop curl */
} public function unsetOption($key)
//reset all options {
if (isset($this->_options)) { //reset a single option if its set already
$this->_options = []; if (isset($this->_options[$key])) {
} unset($this->_options[$key]);
//reset response & status params }
$this->curl = null; return $this;
$this->errorCode = null; }
$this->response = null;
$this->responseCode = null; /**
$this->responseCharset = null; * Unset all curl option, excluding default options.
$this->responseLength = -1; *
$this->responseType = null; * @return $this
$this->errorText = null; */
$this->_postParams = []; public function unsetOptions()
$this->_getParams = []; {
return $this; //reset all options
} if (isset($this->_options)) {
/** $this->_options = [];
* Return a single option }
* return $this;
* @param string|integer $key }
* @return mixed|boolean
*/ /**
public function getOption($key) * Total reset of options, responses, etc.
{ *
//get merged options depends on default and user options * @return $this
$mergesOptions = $this->getOptions(); */
//return value or false if key is not set. public function reset()
return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false; {
} if ($this->curl !== null) {
/** curl_close($this->curl); //stop curl
* Return merged curl options and keep keys! }
* //reset all options
* @return array if (isset($this->_options)) {
*/ $this->_options = [];
public function getOptions() }
{ //reset response & status params
return $this->_options + $this->_defaultOptions; $this->curl = null;
} $this->errorCode = null;
/** $this->response = null;
* Get curl info according to http://php.net/manual/de/function.curl-getinfo.php $this->responseCode = null;
* $this->responseCharset = null;
* @param null $opt $this->responseLength = -1;
* @return array|mixed $this->responseType = null;
*/ $this->errorText = null;
public function getInfo($opt = null) $this->_postParams = [];
{ $this->_getParams = [];
if ($this->curl !== null && $opt === null) { return $this;
return curl_getinfo($this->curl); }
} elseif ($this->curl !== null && $opt !== null) {
return curl_getinfo($this->curl, $opt); /**
} else { * Return a single option
return []; *
} * @param string|integer $key
} * @return mixed|boolean
/** */
* Performs HTTP request public function getOption($key)
* {
* @param string $method //get merged options depends on default and user options
* @param boolean $raw if response body contains JSON and should be decoded -> helper. $mergesOptions = $this->getOptions();
* //return value or false if key is not set.
* @throws Exception if request failed return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false;
* }
* @return mixed
*/ /**
protected function _httpRequest($method, $raw = false) * Return merged curl options and keep keys!
{ *
//set request type and writer function * @return array
$this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method)); */
//check if method is head and set no body public function getOptions()
if ($method === 'HEAD') { {
$this->setOption(CURLOPT_NOBODY, true); return $this->_options + $this->_defaultOptions;
$this->unsetOption(CURLOPT_WRITEFUNCTION); }
}
//setup error reporting and profiling /**
if (YII_DEBUG) { * Get curl info according to http://php.net/manual/de/function.curl-getinfo.php
Yii::trace('Start sending cURL-Request: '.$this->getUrl().'\n', __METHOD__); *
Yii::beginProfile($method.' '.$this->_baseUrl.'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__); * @param null $opt
} * @return array|mixed
/** */
* proceed curl public function getInfo($opt = null)
*/ {
$curlOptions = $this->getOptions(); if ($this->curl !== null && $opt === null) {
$this->curl = curl_init($this->getUrl()); return curl_getinfo($this->curl);
curl_setopt_array($this->curl, $curlOptions); } elseif ($this->curl !== null && $opt !== null) {
return curl_getinfo($this->curl, $opt);
} else {
return [];
}
}
/**
* Performs HTTP request
*
* @param string $method
* @param boolean $raw if response body contains JSON and should be decoded -> helper.
*
* @throws Exception if request failed
*
* @return mixed
*/
protected function _httpRequest($method, $raw = false)
{
//set request type and writer function
$this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method));
//check if method is head and set no body
if ($method === 'HEAD') {
$this->setOption(CURLOPT_NOBODY, true);
$this->unsetOption(CURLOPT_WRITEFUNCTION);
}
//setup error reporting and profiling
if (YII_DEBUG) {
Yii::trace('Start sending cURL-Request: ' . $this->getUrl() . '\n', __METHOD__);
Yii::beginProfile($method . ' ' . $this->_baseUrl . '#' . md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
}
/**
* proceed curl
*/
$curlOptions = $this->getOptions();
$this->curl = curl_init($this->getUrl());
curl_setopt_array($this->curl, $curlOptions);
if (true == $this->timeout_ms && true == $this->connect_timeout_ms) {
curl_setopt($this->curl, CURLOPT_TIMEOUT_MS, $this->timeout_ms);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, $this->timeout_ms);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT_MS, $this->connect_timeout_ms);
}
//curl_setopt($this->curl, CURLOPT_TIMEOUT,40); //curl_setopt($this->curl, CURLOPT_TIMEOUT,40);
$response = curl_exec($this->curl); $response = curl_exec($this->curl);
//check if curl was successful //check if curl was successful
if ($response === false) { if ($response === false) {
//set error code //set error code
$this->errorCode = curl_errno($this->curl); $this->errorCode = curl_errno($this->curl);
$this->errorText = curl_strerror($this->errorCode); $this->errorText = curl_strerror($this->errorCode);
switch ($this->errorCode) { switch ($this->errorCode) {
// 7, 28 = timeout // 7, 28 = timeout
case 7: case 7:
case 28: case 28:
$this->responseCode = 'timeout'; $this->responseCode = 'timeout';
return false; return false;
break; break;
default: default:
return false; return false;
break; break;
} }
} }
//extract header / body data if CURLOPT_HEADER are set to true //extract header / body data if CURLOPT_HEADER are set to true
if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) { if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) {
$this->response = $this->_extractCurlBody($response); $this->response = $this->_extractCurlBody($response);
$this->responseHeaders = $this->_extractCurlHeaders($response); $this->responseHeaders = $this->_extractCurlHeaders($response);
} else { } else {
$this->response = $response; $this->response = $response;
} }
// Extract additional curl params // Extract additional curl params
$this->_extractAdditionalCurlParameter(); $this->_extractAdditionalCurlParameter();
//end yii debug profile //end yii debug profile
if (YII_DEBUG) { if (YII_DEBUG) {
Yii::endProfile($method.' '.$this->getUrl().'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__); Yii::endProfile($method . ' ' . $this->getUrl() . '#' . md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
} }
//check responseCode and return data/status //check responseCode and return data/status
if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') { if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') {
return true; return true;
} else { } else {
$this->response = $raw ? $this->response : Json::decode($this->response); $this->response = $raw ? $this->response : Json::decode($this->response);
return $this->response; return $this->response;
} }
} }
/**
* Extract additional curl params protected class helper /**
*/ * Extract additional curl params protected class helper
protected function _extractAdditionalCurlParameter () */
{ protected function _extractAdditionalCurlParameter()
/** {
* retrieve response code /**
*/ * retrieve response code
$this->responseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE); */
/** $this->responseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
* try extract response type & charset. /**
*/ * try extract response type & charset.
$this->responseType = curl_getinfo($this->curl, CURLINFO_CONTENT_TYPE); */
if (!is_null($this->responseType) && count(explode(';', $this->responseType)) > 1) { $this->responseType = curl_getinfo($this->curl, CURLINFO_CONTENT_TYPE);
list($this->responseType, $possibleCharset) = explode(';', $this->responseType); if (!is_null($this->responseType) && count(explode(';', $this->responseType)) > 1) {
//extract charset list($this->responseType, $possibleCharset) = explode(';', $this->responseType);
if (preg_match('~^charset=(.+?)$~', trim($possibleCharset), $matches) && isset($matches[1])) { //extract charset
$this->responseCharset = strtolower($matches[1]); if (preg_match('~^charset=(.+?)$~', trim($possibleCharset), $matches) && isset($matches[1])) {
} $this->responseCharset = strtolower($matches[1]);
} }
/** }
* try extract response length /**
*/ * try extract response length
$this->responseLength = curl_getinfo($this->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD); */
if((int)$this->responseLength == -1) { $this->responseLength = curl_getinfo($this->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$this->responseLength = strlen($this->response); if ((int)$this->responseLength == -1) {
} $this->responseLength = strlen($this->response);
} }
/** }
* Extract body curl data from response
* /**
* @param string $response * Extract body curl data from response
* @return string *
*/ * @param string $response
protected function _extractCurlBody ($response) * @return string
{ */
return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE)); protected function _extractCurlBody($response)
} {
/** return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE));
* Extract header curl data from response }
*
* @param string $response /**
* @return array * Extract header curl data from response
*/ *
protected function _extractCurlHeaders ($response) * @param string $response
{ * @return array
//Init */
$headers = []; protected function _extractCurlHeaders($response)
$headerText = substr($response, 0, strpos($response, "\r\n\r\n")); {
foreach (explode("\r\n", $headerText) as $i => $line) { //Init
if ($i === 0) { $headers = [];
$headers['http_code'] = $line; $headerText = substr($response, 0, strpos($response, "\r\n\r\n"));
} else { foreach (explode("\r\n", $headerText) as $i => $line) {
list ($key, $value) = explode(':', $line, 2); if ($i === 0) {
$headers[$key] = ltrim($value); $headers['http_code'] = $line;
} } else {
} list ($key, $value) = explode(':', $line, 2);
return $headers; $headers[$key] = ltrim($value);
} }
}
return $headers;
}
} }
\ No newline at end of file
...@@ -20,7 +20,7 @@ class Chain33Service ...@@ -20,7 +20,7 @@ class Chain33Service
public function __construct($parameter = []) public function __construct($parameter = [])
{ {
if(empty($parameter)){ if (empty($parameter)) {
$this->node_params = Yii::$app->params['chain33']; $this->node_params = Yii::$app->params['chain33'];
} else { } else {
$this->node_params = $parameter; $this->node_params = $parameter;
...@@ -31,8 +31,8 @@ class Chain33Service ...@@ -31,8 +31,8 @@ class Chain33Service
{ {
$config = $this->node_params; $config = $this->node_params;
$scheme = $config['scheme'] ?? 'http'; $scheme = $config['scheme'] ?? 'http';
$host = $config['host'] ?? '127.0.0.1'; $host = $config['host'] ?? '127.0.0.1';
$port = (string)$config['port'] ?? ''; $port = (string)$config['port'] ?? '';
if ($port) { if ($port) {
return $scheme . '://' . $host . ':' . $port; return $scheme . '://' . $host . ':' . $port;
} else { } else {
...@@ -44,9 +44,9 @@ class Chain33Service ...@@ -44,9 +44,9 @@ class Chain33Service
{ {
$data = [ $data = [
'jsonrpc' => '2.0', 'jsonrpc' => '2.0',
'id' => 0, 'id' => 0,
'method' => $method, 'method' => $method,
'params' => [], 'params' => [],
]; ];
if (!empty($params)) { if (!empty($params)) {
$data['params'][] = $params; $data['params'][] = $params;
...@@ -56,7 +56,11 @@ class Chain33Service ...@@ -56,7 +56,11 @@ class Chain33Service
public function send($params = [], $method = 'Chain33.Query') public function send($params = [], $method = 'Chain33.Query')
{ {
$ch = new Curl(); $timeout = [
'connect_timeout' => 50000,
'timeout_ms' => 40000
];
$ch = new Curl($timeout);
$jsonrpc = self::jsonRpcBuild($params, $method); $jsonrpc = self::jsonRpcBuild($params, $method);
$ch->setHeader('Content-Type', 'application/json'); $ch->setHeader('Content-Type', 'application/json');
$ch->setRawPostData($jsonrpc); $ch->setRawPostData($jsonrpc);
...@@ -124,7 +128,7 @@ class Chain33Service ...@@ -124,7 +128,7 @@ class Chain33Service
* 获取地址下的所有token资产 * 获取地址下的所有token资产
* *
* @param string|array $address * @param string|array $address
* @param string $symbol * @param string $symbol
* @return array * @return array
*/ */
public function getAccountTokenAssets($address, $symbol) public function getAccountTokenAssets($address, $symbol)
...@@ -133,8 +137,8 @@ class Chain33Service ...@@ -133,8 +137,8 @@ class Chain33Service
$address = [$address]; $address = [$address];
} }
$params = [ $params = [
"addresses" => $address, "addresses" => $address,
"execer" => "user.p.guodun.token", "execer" => "user.p.guodun.token",
"tokenSymbol" => $symbol "tokenSymbol" => $symbol
]; ];
return $this->send($params, 'token.GetTokenBalance'); return $this->send($params, 'token.GetTokenBalance');
...@@ -147,18 +151,18 @@ class Chain33Service ...@@ -147,18 +151,18 @@ class Chain33Service
* @param $to * @param $to
* @param $amount * @param $amount
* @param string $note * @param string $note
* @param bool $isToken * @param bool $isToken
* @param string $tokenSymbol * @param string $tokenSymbol
* @return array * @return array
*/ */
public function extractToken($from, $to, $amount, $note = '', $isToken = true, $tokenSymbol = '') public function extractToken($from, $to, $amount, $note = '', $isToken = true, $tokenSymbol = '')
{ {
$params = [ $params = [
"from" => $to, "from" => $to,
"to" => $from, "to" => $from,
"amount" => -$amount, "amount" => -$amount,
"note" => $note, "note" => $note,
"isToken" => $isToken ? true : false, "isToken" => $isToken ? true : false,
"tokenSymbol" => strtoupper($tokenSymbol) "tokenSymbol" => strtoupper($tokenSymbol)
]; ];
return $this->send($params, 'Chain33.SendToAddress'); return $this->send($params, 'Chain33.SendToAddress');
...@@ -171,18 +175,18 @@ class Chain33Service ...@@ -171,18 +175,18 @@ class Chain33Service
* @param $to * @param $to
* @param $amount * @param $amount
* @param string $note * @param string $note
* @param bool $isToken * @param bool $isToken
* @param string $tokenSymbol * @param string $tokenSymbol
* @return array * @return array
*/ */
public function transToken($from, $to, $amount, $note = '', $isToken = true, $tokenSymbol = '') public function transToken($from, $to, $amount, $note = '', $isToken = true, $tokenSymbol = '')
{ {
$params = [ $params = [
"from" => $from, "from" => $from,
"to" => $to, "to" => $to,
"amount" => $amount, "amount" => $amount,
"note" => $note, "note" => $note,
"isToken" => $isToken ? true : false, "isToken" => $isToken ? true : false,
"tokenSymbol" => strtoupper($tokenSymbol) "tokenSymbol" => strtoupper($tokenSymbol)
]; ];
return $this->send($params, 'Chain33.SendToAddress'); return $this->send($params, 'Chain33.SendToAddress');
...@@ -191,25 +195,25 @@ class Chain33Service ...@@ -191,25 +195,25 @@ class Chain33Service
public function createTokenRawTransaction($to, $amount, $isToken, $tokenSymbol, $fee, $note, $execer) public function createTokenRawTransaction($to, $amount, $isToken, $tokenSymbol, $fee, $note, $execer)
{ {
$params = [ $params = [
"to" => $to, "to" => $to,
"amount" => $amount, "amount" => $amount,
"isToken" => $isToken, "isToken" => $isToken,
"tokenSymbol" => $tokenSymbol, "tokenSymbol" => $tokenSymbol,
"fee" => $fee, "fee" => $fee,
"note" => $note, "note" => $note,
"execer" => $execer, "execer" => $execer,
]; ];
return $this->send($params, 'Chain33.CreateRawTransaction'); return $this->send($params, 'Chain33.CreateRawTransaction');
} }
public function createRawTransaction($to, $amount, $fee, $note,$execer) public function createRawTransaction($to, $amount, $fee, $note, $execer)
{ {
$params = [ $params = [
"to" => $to, "to" => $to,
"amount" => $amount, "amount" => $amount,
"fee" => $fee, "fee" => $fee,
"note" => $note, "note" => $note,
"execer" => $execer, "execer" => $execer,
]; ];
...@@ -274,11 +278,11 @@ class Chain33Service ...@@ -274,11 +278,11 @@ class Chain33Service
public function structureTrade($amount, $execName, $fee, $isToken = True, $to, $tokenSymbol = '') public function structureTrade($amount, $execName, $fee, $isToken = True, $to, $tokenSymbol = '')
{ {
$params = [ $params = [
"amount" => $amount, "amount" => $amount,
"execName" => $execName, "execName" => $execName,
"fee" => $fee, "fee" => $fee,
"isToken" => $isToken ? true : false, "isToken" => $isToken ? true : false,
"to" => $to, "to" => $to,
"tokenSymbol" => strtoupper($tokenSymbol) "tokenSymbol" => strtoupper($tokenSymbol)
]; ];
return $this->send($params, 'Chain33.CreateRawTransaction'); return $this->send($params, 'Chain33.CreateRawTransaction');
...@@ -287,9 +291,9 @@ class Chain33Service ...@@ -287,9 +291,9 @@ class Chain33Service
public function signTrade($addr, $expire = '2h', $txHex) public function signTrade($addr, $expire = '2h', $txHex)
{ {
$params = [ $params = [
"addr" => $addr, "addr" => $addr,
"expire" => $expire, "expire" => $expire,
"txHex" => $txHex "txHex" => $txHex
]; ];
return $this->send($params, 'Chain33.SignRawTx'); return $this->send($params, 'Chain33.SignRawTx');
} }
...@@ -297,7 +301,7 @@ class Chain33Service ...@@ -297,7 +301,7 @@ class Chain33Service
public function sendTrade($data) public function sendTrade($data)
{ {
$params = [ $params = [
"data" => $data, "data" => $data,
]; ];
return $this->send($params, 'Chain33.SendTransaction'); return $this->send($params, 'Chain33.SendTransaction');
} }
...@@ -329,12 +333,12 @@ class Chain33Service ...@@ -329,12 +333,12 @@ class Chain33Service
public function getTxByAddr($addr, $flag, $count, $direction, $height, $index) public function getTxByAddr($addr, $flag, $count, $direction, $height, $index)
{ {
$params = [ $params = [
'addr' => $addr, 'addr' => $addr,
'flag' => $flag, 'flag' => $flag,
'count' => $count, 'count' => $count,
'direction' => $direction, 'direction' => $direction,
'height' => $height, 'height' => $height,
'index' => $index 'index' => $index
]; ];
return $this->send($params, 'Chain33.GetTxByAddr'); return $this->send($params, 'Chain33.GetTxByAddr');
} }
...@@ -359,9 +363,9 @@ class Chain33Service ...@@ -359,9 +363,9 @@ class Chain33Service
public function unLockWallet($password) public function unLockWallet($password)
{ {
$params = [ $params = [
'passwd' => $password, 'passwd' => $password,
'walletorticket' => false, 'walletorticket' => false,
'timeout' => 30 'timeout' => 30
]; ];
return $this->send($params, 'Chain33.UnLock'); return $this->send($params, 'Chain33.UnLock');
} }
......
...@@ -51,7 +51,6 @@ class CrossChainController extends Controller ...@@ -51,7 +51,6 @@ class CrossChainController extends Controller
'scheme' => $transfer_url[0], 'scheme' => $transfer_url[0],
'host' => str_replace('//', '', $transfer_url[1]), 'host' => str_replace('//', '', $transfer_url[1]),
'port' => isset($transfer_url[2]) ? $transfer_url[2] : '', 'port' => isset($transfer_url[2]) ? $transfer_url[2] : '',
'timeout' => 100
]; ];
$service = new Chain33Service($node_params); $service = new Chain33Service($node_params);
......
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