Skip to content

Commit

Permalink
Reuse curl handle
Browse files Browse the repository at this point in the history
  • Loading branch information
ob-stripe committed Dec 11, 2018
1 parent e82a210 commit 083bb50
Showing 1 changed file with 67 additions and 7 deletions.
74 changes: 67 additions & 7 deletions lib/HttpClient/CurlClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ public static function instance()

protected $userAgentInfo;

protected $enablePersistentConnections = true;

protected $curlHandle = null;

/**
* CurlClient constructor.
*
Expand All @@ -60,6 +64,11 @@ public function __construct($defaultOptions = null, $randomGenerator = null)
$this->initUserAgentInfo();
}

public function __destruct()
{
$this->closeCurlHandle();
}

public function initUserAgentInfo()
{
$curlVersion = curl_version();
Expand All @@ -79,6 +88,22 @@ public function getUserAgentInfo()
return $this->userAgentInfo;
}

/**
* @return boolean
*/
public function getEnablePersistentConnections()
{
return $this->enablePersistentConnections;
}

/**
* @param boolean $enable
*/
public function setEnablePersistentConnections($enable)
{
$this->enablePersistentConnections = $enable;
}

// USER DEFINED TIMEOUTS

const DEFAULT_TIMEOUT = 80;
Expand Down Expand Up @@ -216,17 +241,19 @@ private function executeRequestWithRetries($opts, $absUrl)
$rcode = 0;
$errno = 0;

$curl = curl_init();
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
$this->resetCurlHandle();
curl_setopt_array($this->curlHandle, $opts);
$rbody = curl_exec($this->curlHandle);

if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
$errno = curl_errno($this->curlHandle);
$message = curl_error($this->curlHandle);
} else {
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$rcode = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
}
if (!$this->getEnablePersistentConnections()) {
$this->closeCurlHandle();
}
curl_close($curl);

if ($this->shouldRetry($errno, $rcode, $numRetries)) {
$numRetries += 1;
Expand Down Expand Up @@ -338,4 +365,37 @@ private function sleepTime($numRetries)

return $sleepSeconds;
}

/**
* Initializes the curl handle. If already initialized, the handle is closed first.
*/
private function initCurlHandle()
{
$this->closeCurlHandle();
$this->curlHandle = curl_init();
}

/**
* Closes the curl handle if initialized. Do nothing if already closed.
*/
private function closeCurlHandle()
{
if (!is_null($this->curlHandle)) {
curl_close($this->curlHandle);
$this->curlHandle = null;
}
}

/**
* Resets the curl handle. If the handle is not already initialized, or if persistent
* connections are disabled, the handle is reinitialized instead.
*/
private function resetCurlHandle()
{
if (!is_null($this->curlHandle) && $this->getEnablePersistentConnections()) {
curl_reset($this->curlHandle);
} else {
$this->initCurlHandle();
}
}
}

0 comments on commit 083bb50

Please sign in to comment.