Skip to content

Commit

Permalink
Optimize by reusing the same curl handle
Browse files Browse the repository at this point in the history
  • Loading branch information
nganivet authored and Sunil Pawar committed Jul 19, 2018
1 parent b5b04fb commit 85a4a89
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions CRM/Sparkpost.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,22 @@

class CRM_Sparkpost {
const SPARKPOST_EXTENSION_SETTINGS = 'SparkPost Extension Settings';
// cURL handle cache - see http://stackoverflow.com/questions/18046637/should-i-close-curl-or-not
private static $ch = NULL;
// Indicates we need to try sending emails out through an alternate method
const FALLBACK = 1;

static private function _getHandle() {
if (self::$ch == NULL) {
self::$ch = curl_init();
curl_setopt(self::$ch, CURLOPT_FORBID_REUSE, FALSE);
curl_setopt(self::$ch, CURLOPT_FRESH_CONNECT, FALSE);
curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt(self::$ch, CURLOPT_HEADER, FALSE);
}
return self::$ch;
}

static function setSetting($setting, $value) {
// Encrypt API key before storing in database
if ($setting == 'sparkpost_apiKey') {
Expand Down Expand Up @@ -62,9 +75,13 @@ static function getSetting($setting = NULL) {

/**
* Calls the SparkPost REST API v1
* @param $path Method path
* @param $params Method parameters (translated as GET arguments)
* @param $content Method content (translated as POST arguments)
*
* @param $path string Method path
* @param $params array Method parameters (translated as GET arguments)
* @param $content array Method content (translated as POST arguments)
*
* @return mixed Sparkpost's API response (decoded from json)
* @throws \Exception
*
* @see https://developers.sparkpost.com/api/
*/
Expand All @@ -81,14 +98,12 @@ static function call($path, $params = array(), $content = array()) {
}

// Initialize connection and set headers
$ch = curl_init();
$ch = self::_getHandle();
curl_setopt($ch, CURLOPT_URL, "https://api.sparkpost.com/api/v1/$path");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$request_headers = array();
$request_headers[] = 'Content-Type: application/json';
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'User-Agent: CiviCRM SparkPost extension (com.cividesk.email.sparkpost)';
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

if (!empty($content)) {
Expand All @@ -112,7 +127,6 @@ static function call($path, $params = array(), $content = array()) {
throw new Exception('Sparkpost curl error: ', curl_error($ch));
}
$curl_info = curl_getinfo($ch);
curl_close($ch);

// Treat errors if any in the response ...
$response = json_decode($data);
Expand Down

0 comments on commit 85a4a89

Please sign in to comment.