|
| 1 | +<?php |
| 2 | +namespace SparkPost; |
| 3 | +use Guzzle\Http\Client; |
| 4 | +use Guzzle\Http\Exception\ClientErrorResponseException; |
| 5 | + |
| 6 | +/** |
| 7 | + * @desc SDK interface for managing SparkPost API endpoints |
| 8 | + */ |
| 9 | +class APIResource { |
| 10 | + |
| 11 | + /** |
| 12 | + * @desc name of the API endpoint, mainly used for URL construction. |
| 13 | + * @var string |
| 14 | + */ |
| 15 | + public static $endpoint; |
| 16 | + |
| 17 | + /** |
| 18 | + * @desc singleton holder to create a guzzle http client |
| 19 | + * @var \GuzzleHttp\Client |
| 20 | + */ |
| 21 | + protected static $request; |
| 22 | + |
| 23 | + /** |
| 24 | + * @desc Mapping for values passed into the send method to the values needed for the respective API |
| 25 | + * @var array |
| 26 | + */ |
| 27 | + protected static $parameterMappings = array(); |
| 28 | + |
| 29 | + /** |
| 30 | + * @desc Sets up default structure and default values for the model that is acceptable by the API |
| 31 | + * @var array |
| 32 | + */ |
| 33 | + protected static $structure = array(); |
| 34 | + |
| 35 | + /** |
| 36 | + * @desc Ensure that this class cannot be instansiated |
| 37 | + */ |
| 38 | + private function __construct() {} |
| 39 | + |
| 40 | + /** |
| 41 | + * @desc Creates and returns a guzzle http client. |
| 42 | + * @return \GuzzleHttp\Client |
| 43 | + */ |
| 44 | + protected static function getHttpClient() { |
| 45 | + if(!isset(self::$request)) { |
| 46 | + self::$request = new Client(); |
| 47 | + } |
| 48 | + return self::$request; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @desc Private Method helper to get the configuration values to create the base url for the current API endpoint |
| 53 | + * |
| 54 | + * @return string base url for the transmissions API |
| 55 | + */ |
| 56 | + protected static function getBaseUrl($config) { |
| 57 | + $baseUrl = '/api/' . $config['version'] . '/' . static::$endpoint; |
| 58 | + return $config['protocol'] . '://' . $config['host'] . ($config['port'] ? ':' . $config['port'] : '') . $baseUrl; |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + /** |
| 63 | + * @desc Private Method helper to reference parameter mappings and set the right value for the right parameter |
| 64 | + */ |
| 65 | + protected static function setMappedValue (&$model, $mapKey, $value) { |
| 66 | + //get mapping |
| 67 | + if( empty(static::$parameterMappings) ) { |
| 68 | + // if parameterMappings is empty we can assume that no wrapper is defined |
| 69 | + // for the current endpoint and we will use the mapKey to define the mappings directly |
| 70 | + $mapPath = $mapKey; |
| 71 | + }elseif(array_key_exists($mapKey, static::$parameterMappings)) { |
| 72 | + // use only defined parameter mappings to construct $model |
| 73 | + $mapPath = static::$parameterMappings[$mapKey]; |
| 74 | + } else { |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + $path = explode('.', $mapPath); |
| 79 | + $temp = &$model; |
| 80 | + foreach( $path as $key ) { |
| 81 | + if( !isset($temp[$key]) ){ |
| 82 | + $temp[$key] = null; |
| 83 | + } |
| 84 | + $temp = &$temp[$key]; |
| 85 | + } |
| 86 | + $temp = $value; |
| 87 | + |
| 88 | + } |
| 89 | + |
| 90 | + protected static function buildRequestModel( $requestConfig, $model=array() ) { |
| 91 | + foreach($requestConfig as $key=>$value) { |
| 92 | + self::setMappedValue($model, $key, $value); |
| 93 | + } |
| 94 | + return $model; |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * @desc Method for issuing POST requests |
| 99 | + * |
| 100 | + * @return array API repsonse represented as key-value pairs |
| 101 | + */ |
| 102 | + public static function sendRequest( $requestConfig ) { |
| 103 | + $hostConfig = SparkPost::getConfig(); |
| 104 | + $request = self::getHttpClient(); |
| 105 | + |
| 106 | + //create model from $transmissionConfig |
| 107 | + $model = static::$structure; |
| 108 | + $requestModel = self::buildRequestModel( $requestConfig, $model ); |
| 109 | + |
| 110 | + //send the request |
| 111 | + try { |
| 112 | + $response = $request->post( |
| 113 | + self::getBaseUrl($hostConfig), |
| 114 | + array('authorization' => $hostConfig['key']), |
| 115 | + json_encode($requestModel), |
| 116 | + array("verify"=>$hostConfig['strictSSL']) |
| 117 | + )->send(); |
| 118 | + |
| 119 | + return $response->json(); |
| 120 | + } |
| 121 | + /* |
| 122 | + * Handles 4XX responses |
| 123 | + */ |
| 124 | + catch (ClientErrorResponseException $exception) { |
| 125 | + $response = $exception->getResponse(); |
| 126 | + $responseArray = $response->json(); |
| 127 | + throw new \Exception(json_encode($responseArray['errors'])); |
| 128 | + } |
| 129 | + /* |
| 130 | + * Handles 5XX Errors, Configuration Errors, and a catch all for other errors |
| 131 | + */ |
| 132 | + catch (\Exception $exception) { |
| 133 | + throw new \Exception("Unable to contact ".ucfirst(static::$endpoint)." API: ". $exception->getMessage()); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + |
| 138 | + /** |
| 139 | + * @desc Wrapper method for issuing GET request to current API endpoint |
| 140 | + * |
| 141 | + * @param string $resourcePath (optional) string resource path of specific resource |
| 142 | + * @param array $options (optional) query string parameters |
| 143 | + * @return array Result set of transmissions found |
| 144 | + */ |
| 145 | + public static function fetchResource( $resourcePath=null, $options=array() ) { |
| 146 | + return self::callResource( 'get', $resourcePath, $options ); |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * @desc Wrapper method for issuing DELETE request to current API endpoint |
| 151 | + * |
| 152 | + * @param string $resourcePath (optional) string resource path of specific resource |
| 153 | + * @param array $options (optional) query string parameters |
| 154 | + * @return array Result set of transmissions found |
| 155 | + */ |
| 156 | + public static function deleteResource( $resourcePath=null, $options=array() ) { |
| 157 | + return self::callResource( 'delete', $resourcePath, $options ); |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * @desc Private Method for issuing GET and DELETE request to current API endpoint |
| 162 | + * |
| 163 | + * This method is responsible for getting the collection _and_ |
| 164 | + * a specific entity from the API endpoint |
| 165 | + * |
| 166 | + * If resourcePath parameter is omitted, then we fetch the collection |
| 167 | + * |
| 168 | + * @param string $action HTTP method type |
| 169 | + * @param string $resourcePath (optional) string resource path of specific resource |
| 170 | + * @param array $options (optional) query string parameters |
| 171 | + * @return array Result set of action performed on resource |
| 172 | + */ |
| 173 | + private static function callResource( $action, $resourcePath=null, $options=array() ) { |
| 174 | + |
| 175 | + if( !in_array( $action, array('get', 'delete') ) ) throw new \Exception('Invalid resource action'); |
| 176 | + |
| 177 | + //build the url |
| 178 | + $hostConfig = SparkPost::getConfig(); |
| 179 | + $url = self::getBaseUrl($hostConfig); |
| 180 | + if (!is_null($resourcePath)){ |
| 181 | + $url .= '/'.$resourcePath; |
| 182 | + } |
| 183 | + |
| 184 | + // untested: |
| 185 | + if( !empty($options) ) { |
| 186 | + $queryString = http_build_query($options); |
| 187 | + $url .= '?'.$queryString; |
| 188 | + } |
| 189 | + |
| 190 | + $request = self::getHttpClient(); |
| 191 | + |
| 192 | + //make request |
| 193 | + try { |
| 194 | + $response = $request->{$action}($url, array('authorization' => $hostConfig['key']), array("verify"=>$hostConfig['strictSSL']))->send(); |
| 195 | + return $response->json(); |
| 196 | + } |
| 197 | + /* |
| 198 | + * Handles 4XX responses |
| 199 | + */ |
| 200 | + catch (ClientErrorResponseException $exception) { |
| 201 | + $response = $exception->getResponse(); |
| 202 | + $statusCode = $response->getStatusCode(); |
| 203 | + if($statusCode === 404) { |
| 204 | + throw new \Exception("The specified resource does not exist", 404); |
| 205 | + } |
| 206 | + throw new \Exception("Received bad response from ".ucfirst(static::$endpoint)." API: ". $statusCode ); |
| 207 | + } |
| 208 | + /* |
| 209 | + * Handles 5XX Errors, Configuration Errors, and a catch all for other errors |
| 210 | + */ |
| 211 | + catch (\Exception $exception) { |
| 212 | + throw new \Exception("Unable to contact ".ucfirst(static::$endpoint)." API: ". $exception->getMessage()); |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | +} |
0 commit comments