diff options
author | beardyman <nornholdj@gmail.com> | 2015-09-15 20:43:30 -0400 |
---|---|---|
committer | beardyman <nornholdj@gmail.com> | 2015-09-15 20:43:30 -0400 |
commit | c0b9e8b6cb7b1d616941b657958126b551b22eef (patch) | |
tree | 98829e5b048cf9328f6211719f7e87886472dbe4 /lib/SparkPost | |
parent | aeea514f81c652257b64e606c771cc51249db49c (diff) | |
download | php-sparkpost-c0b9e8b6cb7b1d616941b657958126b551b22eef.zip php-sparkpost-c0b9e8b6cb7b1d616941b657958126b551b22eef.tar.gz php-sparkpost-c0b9e8b6cb7b1d616941b657958126b551b22eef.tar.bz2 |
Refactored to use http adapter instead of guzzle directly
Diffstat (limited to 'lib/SparkPost')
-rw-r--r-- | lib/SparkPost/APIResource.php | 159 | ||||
-rw-r--r-- | lib/SparkPost/SparkPost.php | 84 | ||||
-rw-r--r-- | lib/SparkPost/Transmission.php | 42 |
3 files changed, 148 insertions, 137 deletions
diff --git a/lib/SparkPost/APIResource.php b/lib/SparkPost/APIResource.php index 469ba7e..be3d788 100644 --- a/lib/SparkPost/APIResource.php +++ b/lib/SparkPost/APIResource.php @@ -1,65 +1,36 @@ <?php namespace SparkPost; -use Guzzle\Http\Client; -use Guzzle\Http\Exception\ClientErrorResponseException; +use Ivory\HttpAdapter\HttpAdapterException; /** * @desc SDK interface for managing SparkPost API endpoints */ class APIResource { - + /** * @desc name of the API endpoint, mainly used for URL construction. * @var string */ public static $endpoint; - - /** - * @desc singleton holder to create a guzzle http client - * @var \GuzzleHttp\Client - */ - protected static $request; - + /** * @desc Mapping for values passed into the send method to the values needed for the respective API * @var array */ protected static $parameterMappings = array(); - + /** * @desc Sets up default structure and default values for the model that is acceptable by the API * @var array */ protected static $structure = array(); - + /** * @desc Ensure that this class cannot be instansiated */ private function __construct() {} /** - * @desc Creates and returns a guzzle http client. - * @return \GuzzleHttp\Client - */ - protected static function getHttpClient() { - if(!isset(self::$request)) { - self::$request = new Client(); - } - return self::$request; - } - - /** - * @desc Private Method helper to get the configuration values to create the base url for the current API endpoint - * - * @return string base url for the transmissions API - */ - protected static function getBaseUrl($config) { - $baseUrl = '/api/' . $config['version'] . '/' . static::$endpoint; - return $config['protocol'] . '://' . $config['host'] . ($config['port'] ? ':' . $config['port'] : '') . $baseUrl; - } - - - /** * @desc Private Method helper to reference parameter mappings and set the right value for the right parameter */ protected static function setMappedValue (&$model, $mapKey, $value) { @@ -74,7 +45,7 @@ class APIResource { } else { return; } - + $path = explode('.', $mapPath); $temp = &$model; foreach( $path as $key ) { @@ -84,57 +55,30 @@ class APIResource { $temp = &$temp[$key]; } $temp = $value; - + } - + protected static function buildRequestModel( $requestConfig, $model=array() ) { foreach($requestConfig as $key=>$value) { self::setMappedValue($model, $key, $value); } return $model; } - + /** - * @desc Method for issuing POST requests - * - * @return array API repsonse represented as key-value pairs + * TODO: Docs */ - public static function sendRequest( $requestConfig ) { - $hostConfig = SparkPost::getConfig(); - $request = self::getHttpClient(); - - //create model from $transmissionConfig - $model = static::$structure; - $requestModel = self::buildRequestModel( $requestConfig, $model ); - - //send the request - try { - $response = $request->post( - self::getBaseUrl($hostConfig), - array('authorization' => $hostConfig['key']), - json_encode($requestModel), - array("verify"=>$hostConfig['strictSSL']) - )->send(); - - return $response->json(); - } - /* - * Handles 4XX responses - */ - catch (ClientErrorResponseException $exception) { - $response = $exception->getResponse(); - $responseArray = $response->json(); - throw new \Exception(json_encode($responseArray['errors'])); - } - /* - * Handles 5XX Errors, Configuration Errors, and a catch all for other errors - */ - catch (\Exception $exception) { - throw new \Exception("Unable to contact ".ucfirst(static::$endpoint)." API: ". $exception->getMessage()); - } + public static function create(Array $body=[]) { + return self::callResource( 'post', '/', ['body'=>$options]); + } + + /** + * TODO: Docs + */ + public static function update(String $resourcePath, Array $body=[]) { + return self::callResource( 'post', $resourcePath, ['body'=>$options]); } - /** * @desc Wrapper method for issuing GET request to current API endpoint * @@ -142,10 +86,10 @@ class APIResource { * @param array $options (optional) query string parameters * @return array Result set of transmissions found */ - public static function fetchResource( $resourcePath=null, $options=array() ) { + public static function get(String $resourcePath=null, Array $options=[] ) { return self::callResource( 'get', $resourcePath, $options ); } - + /** * @desc Wrapper method for issuing DELETE request to current API endpoint * @@ -153,10 +97,10 @@ class APIResource { * @param array $options (optional) query string parameters * @return array Result set of transmissions found */ - public static function deleteResource( $resourcePath=null, $options=array() ) { + public static function delete(String $resourcePath=null, Array $options=[] ) { return self::callResource( 'delete', $resourcePath, $options ); } - + /** * @desc Private Method for issuing GET and DELETE request to current API endpoint * @@ -170,41 +114,48 @@ class APIResource { * @param array $options (optional) query string parameters * @return array Result set of action performed on resource */ - private static function callResource( $action, $resourcePath=null, $options=array() ) { - - if( !in_array( $action, array('get', 'delete') ) ) throw new \Exception('Invalid resource action'); - - //build the url - $hostConfig = SparkPost::getConfig(); - $url = self::getBaseUrl($hostConfig); + private static function callResource( $action, $resourcePath=null, $options=[] ) { + $action = strtoupper($action); // normalize + + if( !in_array($action, ['POST', 'PUT', 'GET', 'DELETE'])) { + throw new \Exception('Invalid resource action'); + } + + $url = '/'.static::$endpoint; + $body = null; if (!is_null($resourcePath)){ - $url .= '/'.$resourcePath; + $url .= $url.$resourcePath; } - + // untested: - if( !empty($options) ) { - $queryString = http_build_query($options); + if( !empty($options['query'])) { + $queryString = http_build_query($options['query']); $url .= '?'.$queryString; } - - $request = self::getHttpClient(); - + + if( !empty($options['body']) ) { + $model = static::$structure; + $requestModel = self::buildRequestModel( $requestConfig, $options['body'] ); + $body = json_encode($requestModel); + } + //make request try { - $response = $request->{$action}($url, array('authorization' => $hostConfig['key']), array("verify"=>$hostConfig['strictSSL']))->send(); - return $response->json(); + $httpAdapter = SparkPost::getHttpAdapter(); + $response = SparkPost::getHttpAdapter()->send($url, $action, SparkPost::getHttpHeaders(), $body); + return json_decode($response->getBody()->getContents(), true); } /* * Handles 4XX responses */ - catch (ClientErrorResponseException $exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - if($statusCode === 404) { - throw new \Exception("The specified resource does not exist", 404); - } - throw new \Exception("Received bad response from ".ucfirst(static::$endpoint)." API: ". $statusCode ); - } + // catch (HttpAdapterException $exception) { + // $response = $exception->getResponse(); + // $statusCode = $response->getStatusCode(); + // if($statusCode === 404) { + // throw new \Exception("The specified resource does not exist", 404); + // } + // throw new \Exception("Received bad response from ".ucfirst(static::$endpoint)." API: ". $statusCode ); + // } /* * Handles 5XX Errors, Configuration Errors, and a catch all for other errors */ @@ -212,5 +163,5 @@ class APIResource { throw new \Exception("Unable to contact ".ucfirst(static::$endpoint)." API: ". $exception->getMessage()); } } - + } diff --git a/lib/SparkPost/SparkPost.php b/lib/SparkPost/SparkPost.php index 755df46..3b54ada 100644 --- a/lib/SparkPost/SparkPost.php +++ b/lib/SparkPost/SparkPost.php @@ -1,30 +1,34 @@ <?php namespace SparkPost; +use Ivory\HttpAdapter; +use Ivory\HttpAdapter\Configuration; class SparkPost { - + private static $config; + private static $httpAdapter; + private static $defaults = array( 'host'=>'api.sparkpost.com', 'protocol'=>'https', 'port'=>443, 'strictSSL'=>true, 'key'=>'', - 'version'=>'v1' + 'version'=>'v1' ); - + /** * Enforce that this object can't be instansiated */ private function __construct(){} - + /** * Allows the user to pass in values to override the defaults and set their API key * @param Array $configMap - Hashmap that contains config values for the SDK to connect to SparkPost * @throws \Exception */ - public static function setConfig(array $configMap) { - //check for API key because its required + public static function setConfig($httpAdapter, array $configMap) { + //check for API key because its required if (isset($configMap['key'])){ $key = trim($configMap['key']); if(empty($key)){ @@ -33,28 +37,88 @@ class SparkPost { } else { throw new \Exception('You must provide an API key'); } + // TODO: need to figure out how to enforce this + // if (!$httpAdapter instanceOf HttpAdapterInterface) { + // throw new \Exception('First Argument must be a valid Ivory\HttpAdapter'); + // } + self::$config = self::$defaults; + + self::$httpAdapter = $httpAdapter; + foreach ($configMap as $configOption => $configValue) { if(key_exists($configOption, self::$config)) { self::$config[$configOption] = $configValue; } } + + self::$httpAdapter->setConfiguration(self::getHttpConfig(self::$config)); + } + + + /** + * @desc Merges passed in headers with default headers for http requests + * @return Array - headers to be set on http requests + */ + public static function getHttpHeaders(Array $headers = null) { + $defaultOptions = [ + 'Authorization' => self::$config['key'], + 'Content-Type' => 'application/json', + ]; + + // Merge passed in headers with defaults + if (!is_null($headers)) { + foreach ($headers as $header => $value) { + $defaultOptions[$header] = $value; + } + } + return $defaultOptions; + } + + + /** + * @desc Helper function for getting the configuration for http requests + * @return \Ivory\HttpAdapter\Configuration + */ + // TODO: Need to figure out how to set strictSSL + private static function getHttpConfig($config) { + // get composer.json to extract version number + $composerFile = file_get_contents(dirname(__FILE__) . "/../../composer.json"); + $composer = json_decode($composerFile, true); + + // create Configuration for http adapter + $httpConfig = new Configuration(); + $baseUrl = $config['protocol'] . '://' . $config['host'] . ($config['port'] ? ':' . $config['port'] : '') . '/api/' . $config['version']; + $httpConfig->setBaseUri($baseUrl); + $httpConfig->setUserAgent('php-sparkpost/' . $composer['version']); + return $httpConfig; } - + /** * Retrieves the configuration that was previously setup by the user * @throws \Exception */ public static function getConfig() { - if (self::$config === null) { + if (self::$config === null) { throw new \Exception('No configuration has been provided'); } return self::$config; } - + public static function unsetConfig() { self::$config = NULL; } + + /** + * Retrieves the Http Adapter that was previously setup by the user + * @throws \Exception + */ + public static function getHttpAdapter() { + if (self::$config === null) { + throw new \Exception('No Http Adapter has been provided'); + } + return self::$httpAdapter; + } } -?>
\ No newline at end of file +?> diff --git a/lib/SparkPost/Transmission.php b/lib/SparkPost/Transmission.php index 4e54f1d..82cc11d 100644 --- a/lib/SparkPost/Transmission.php +++ b/lib/SparkPost/Transmission.php @@ -7,11 +7,11 @@ use Guzzle\Http\Exception\ClientErrorResponseException; * @desc SDK interface for managing transmissions */ class Transmission extends APIResource { - + public static $endpoint = 'transmissions'; - + /** - * @desc Mapping for values passed into the send method to the values needed for the Transmission API + * @desc Mapping for values passed into the send method to the values needed for the Transmission API * @var array */ protected static $parameterMappings = array( @@ -34,7 +34,7 @@ class Transmission extends APIResource { 'trackClicks'=>'options.click_tracking', 'useDraftTemplate'=>'use_draft_template' ); - + /** * @desc Sets up default structure and default values for the model that is acceptable by the API * @var array @@ -42,20 +42,20 @@ class Transmission extends APIResource { protected static $structure = array( 'return_path'=>"default@sparkpostmail.com", 'content'=>array( - 'html'=>null, + 'html'=>null, 'text'=>null, 'email_rfc822'=>null ), 'use_draft_template'=>false ); - + /** * @desc Method for issuing POST request to the Transmissions API * * This method assumes that all the appropriate fields have - * been populated by the user through configuration. Acceptable - * configuration values are: - * 'campaign': string, + * been populated by the user through configuration. Acceptable + * configuration values are: + * 'campaign': string, * 'metadata': array, * 'substitutionData': array, * 'description': string, @@ -71,42 +71,38 @@ class Transmission extends APIResource { * 'template': string, * 'trackOpens': boolean, * 'trackClicks': boolean, - * 'useDraftTemplate': boolean + * 'useDraftTemplate': boolean * * @return array API repsonse represented as key-value pairs */ public static function send( $transmissionConfig ) { - return self::sendRequest( $transmissionConfig ); + return self::create( $transmissionConfig ); } - + /** * @desc Method for retrieving information about all transmissions * Wrapper method for a cleaner interface - * + * * @return array result Set of transmissions */ public static function all( $campaignID=null, $templateID=null ) { $options = array(); if( $campaignID !== NULL ) $options['campaign_id'] = $campaignID; if( $templateID !== NULL ) $options['template_id'] = $templateID; - - return self::fetchResource( null, $options ); + + return self::get( null, $options ); } - + /** * @desc Method for retrieving information about a single transmission * Wrapper method for a cleaner interface - * + * * @param string $transmissionID Identifier of the transmission to be found * @return array result Single transmission represented in key-value pairs */ public static function find($transmissionID) { - return self::fetchResource($transmissionID); - } - - public static function delete( $transmissionID ) { - return self::deleteResource($transmissionID); + return self::get($transmissionID); } } -?>
\ No newline at end of file +?> |