diff options
-rw-r--r-- | examples/transmission/get_all_transmissions.php | 5 | ||||
-rw-r--r-- | examples/transmission/get_transmission.php | 12 | ||||
-rw-r--r-- | examples/transmission/rfc822.php | 29 | ||||
-rw-r--r-- | examples/transmission/send_transmission_all_fields.php | 45 | ||||
-rw-r--r-- | examples/transmission/simple_send.php | 37 | ||||
-rw-r--r-- | examples/transmission/stored_recipients_inline_content.php | 15 | ||||
-rw-r--r-- | examples/transmission/stored_template_send.php | 29 | ||||
-rw-r--r-- | examples/unwrapped/create_template.php | 27 | ||||
-rw-r--r-- | lib/SparkPost/APIResource.php | 43 | ||||
-rw-r--r-- | lib/SparkPost/SparkPost.php | 96 | ||||
-rw-r--r-- | test/unit/APIResourceTest.php | 223 | ||||
-rw-r--r-- | test/unit/SparkPostTest.php | 88 |
12 files changed, 380 insertions, 269 deletions
diff --git a/examples/transmission/get_all_transmissions.php b/examples/transmission/get_all_transmissions.php index 54cb376..1e1882b 100644 --- a/examples/transmission/get_all_transmissions.php +++ b/examples/transmission/get_all_transmissions.php @@ -7,13 +7,12 @@ use SparkPost\Transmission; use GuzzleHttp\Client; use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; +$key = 'YOUR API KEY'; $httpAdapter = new Guzzle6HttpAdapter(new Client()); -SparkPost::setConfig($httpAdapter, ['key'=>$key]); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { $results = Transmission::all(); - var_dump($results); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); diff --git a/examples/transmission/get_transmission.php b/examples/transmission/get_transmission.php index 574388c..84cd227 100644 --- a/examples/transmission/get_transmission.php +++ b/examples/transmission/get_transmission.php @@ -3,14 +3,18 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; + +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); try { - $results = Transmission::find('Your Transmission Id'); + $results = Transmission::find('Your Transmission ID'); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/transmission/rfc822.php b/examples/transmission/rfc822.php index b97bbb9..ec932e7 100644 --- a/examples/transmission/rfc822.php +++ b/examples/transmission/rfc822.php @@ -3,23 +3,26 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { - $results = Transmission::send(array( - 'recipients'=>array( - array( - 'address'=>array( - 'email'=>'john.doe@sample.com' - ) - ) - ), - 'rfc822'=>"Content-Type: text/plain\nFrom: From Envelope <from@example.com>\nSubject: Example Email\n\nHello World" - )); + $results = Transmission::send([ + 'recipients'=>[ + [ + 'address'=>[ + 'email'=>'john.doe@example.com' + ] + ] + ], + 'rfc822'=>"Content-Type: text/plain\nFrom: From Envelope <from@sparkpostbox.com>\nSubject: Example Email\n\nHello World" + ]); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/transmission/send_transmission_all_fields.php b/examples/transmission/send_transmission_all_fields.php index 30f7793..3bd9315 100644 --- a/examples/transmission/send_transmission_all_fields.php +++ b/examples/transmission/send_transmission_all_fields.php @@ -3,41 +3,48 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); + +// TODO: update all from emails to = sandbox domain try{ - $results = Transmission::send(array( + $results = Transmission::send([ "campaign"=>"my-campaign", - "metadata"=>array( + "metadata"=>[ "sample_campaign"=>true, "type"=>"these are custom fields" - ), - "substitutionData"=>array( + ], + "substitutionData"=>[ "name"=>"Test Name" - ), + ], "description"=>"my description", "replyTo"=>"reply@test.com", - "customHeaders"=>array( + "customHeaders"=>[ "X-Custom-Header"=>"Sample Custom Header" - ), + ], "trackOpens"=>false, "trackClicks"=>false, - "from"=>"From Envelope <from@example.com>", + "from"=>"From Envelope <from@sparkpostbox.com>", "html"=>"<p>Hello World! Your name is: {{name}}</p>", "text"=>"Hello World!", "subject"=>"Example Email: {{name}}", - "recipients"=>array( - array( - "address"=>array( - "email"=>"john.doe@sample.com" - ) - ) - ) - )); + "recipients"=>[ + [ + "address"=>[ + "email"=>"john.doe@example.com" + ] + ] + ] + ]); + + var_dump($results); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/transmission/simple_send.php b/examples/transmission/simple_send.php index 8149238..caaf962 100644 --- a/examples/transmission/simple_send.php +++ b/examples/transmission/simple_send.php @@ -1,29 +1,32 @@ <?php -namespace Examples\Transmisson; +namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { - $results = Transmission::send(array( - "from"=>"From Envelope <from@example.com>", - "html"=>"<p>Hello World!</p>", - "text"=>"Hello World!", - "subject"=>"Example Email", - "recipients"=>array( - array( - "address"=>array( - "email"=>"john.doe@example.com" - ) - ) - ) - )); + $results = Transmission::send([ + "from"=>"From Envelope <from@sparkpostbox.com>", + "html"=>"<p>Hello World!</p>", + "text"=>"Hello World!", + "subject"=>"Example Email", + "recipients"=>[ + [ + "address"=>[ + "email"=>"john.doe@example.com" + ] + ] + ] + ]); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/transmission/stored_recipients_inline_content.php b/examples/transmission/stored_recipients_inline_content.php index dbb7c1d..42e40df 100644 --- a/examples/transmission/stored_recipients_inline_content.php +++ b/examples/transmission/stored_recipients_inline_content.php @@ -3,23 +3,26 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { - $results = Transmission::send(array( + $results = Transmission::send([ "campaign"=>"my-campaign", - "from"=>"From Envelope <from@example.com>", + "from"=>"From Envelope <from@sparkpostbox.com>", "html"=>"<p>Hello World! Your name is: {{name}}</p>", "text"=>"Hello World!", "subject"=>"Example Email: {{name}}", "recipientList"=>'Example List' - )); + ]); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/transmission/stored_template_send.php b/examples/transmission/stored_template_send.php index cda6de6..82be209 100644 --- a/examples/transmission/stored_template_send.php +++ b/examples/transmission/stored_template_send.php @@ -3,24 +3,27 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { - $results = Transmission::send(array( - "from"=>"From Envelope <from@example.com>", - "recipients"=>array( - array( - "address"=>array( - "email"=>"john.doe@sample.com" - ) - ) - ), + $results = Transmission::send([ + "from"=>"From Envelope <from@sparkpostbox.com>", + "recipients"=>[ + [ + "address"=>[ + "email"=>"john.doe@example.com" + ] + ] + ], "template"=>"my-template" - )); + ]); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/examples/unwrapped/create_template.php b/examples/unwrapped/create_template.php index 717430f..ee4ff6c 100644 --- a/examples/unwrapped/create_template.php +++ b/examples/unwrapped/create_template.php @@ -3,23 +3,30 @@ namespace Examples\Unwrapped; require_once (dirname(__FILE__).'/../bootstrap.php'); use SparkPost\SparkPost; use SparkPost\APIResource; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -$key = 'YOURAPIKEY'; -SparkPost::setConfig(array('key'=>$key)); +$key = 'YOUR API KEY'; +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +SparkPost::configure($httpAdapter, ['key'=>$key]); try { // define the endpoint APIResource::$endpoint = 'templates'; - - $templateConfig = array( + + $templateConfig = [ 'name' => 'Summer Sale!', - 'content.from' => 'marketing@bounces.company.example', - 'content.subject' => 'Summer deals', - 'content.html' => '<b>Check out these deals!</b>', - ); - $results = APIResource::sendRequest($templateConfig); + 'id'=>'summer-sale', + 'content'=> [ + 'from' => 'john.doe@sparkpostbox.com', + 'subject' => 'Summer deals', + 'html' => '<b>Check out these deals!</b>' + ] + ]; + $results = APIResource::create($templateConfig); + var_dump($results); echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?>
\ No newline at end of file +?> diff --git a/lib/SparkPost/APIResource.php b/lib/SparkPost/APIResource.php index be3d788..260d5e2 100644 --- a/lib/SparkPost/APIResource.php +++ b/lib/SparkPost/APIResource.php @@ -58,7 +58,10 @@ class APIResource { } - protected static function buildRequestModel( $requestConfig, $model=array() ) { + /** + * TODO: Docs + */ + protected static function buildRequestModel(Array $requestConfig, Array $model=[] ) { foreach($requestConfig as $key=>$value) { self::setMappedValue($model, $key, $value); } @@ -69,14 +72,14 @@ class APIResource { * TODO: Docs */ public static function create(Array $body=[]) { - return self::callResource( 'post', '/', ['body'=>$options]); + return self::callResource( 'post', null, ['body'=>$body]); } /** * TODO: Docs */ - public static function update(String $resourcePath, Array $body=[]) { - return self::callResource( 'post', $resourcePath, ['body'=>$options]); + public static function update( $resourcePath, Array $body=[]) { + return self::callResource( 'put', $resourcePath, ['body'=>$body]); } /** @@ -86,8 +89,8 @@ class APIResource { * @param array $options (optional) query string parameters * @return array Result set of transmissions found */ - public static function get(String $resourcePath=null, Array $options=[] ) { - return self::callResource( 'get', $resourcePath, $options ); + public static function get( $resourcePath=null, Array $query=[] ) { + return self::callResource( 'get', $resourcePath, ['query'=>$query] ); } /** @@ -97,8 +100,8 @@ class APIResource { * @param array $options (optional) query string parameters * @return array Result set of transmissions found */ - public static function delete(String $resourcePath=null, Array $options=[] ) { - return self::callResource( 'delete', $resourcePath, $options ); + public static function delete( $resourcePath=null, Array $query=[] ) { + return self::callResource( 'delete', $resourcePath, ['query'=>$query] ); } /** @@ -121,10 +124,10 @@ class APIResource { throw new \Exception('Invalid resource action'); } - $url = '/'.static::$endpoint; + $url = '/' . static::$endpoint . '/'; $body = null; if (!is_null($resourcePath)){ - $url .= $url.$resourcePath; + $url .= $resourcePath; } // untested: @@ -135,7 +138,7 @@ class APIResource { if( !empty($options['body']) ) { $model = static::$structure; - $requestModel = self::buildRequestModel( $requestConfig, $options['body'] ); + $requestModel = self::buildRequestModel( $options['body'], $model ); $body = json_encode($requestModel); } @@ -147,15 +150,15 @@ class APIResource { } /* * Handles 4XX responses - */ - // 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 ); - // } + */ + catch (HttpAdapterException $exception) { + $response = $exception->getBody(); + $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 */ diff --git a/lib/SparkPost/SparkPost.php b/lib/SparkPost/SparkPost.php index 3b54ada..5bcb815 100644 --- a/lib/SparkPost/SparkPost.php +++ b/lib/SparkPost/SparkPost.php @@ -1,6 +1,7 @@ <?php namespace SparkPost; use Ivory\HttpAdapter; +use Ivory\HttpAdapter\HttpAdapterInterface; use Ivory\HttpAdapter\Configuration; class SparkPost { @@ -22,47 +23,64 @@ class SparkPost { */ private function __construct(){} + /** + * @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; + } + + /** + * @desc Convenience function for setting the httpAdapter and config in one step + * + * @param Ivory\HttpAdapter $httpAdapter - an adapter for making http requests + * @param Array $settingsConfig - Hashmap that contains config values for the SDK to connect to SparkPost + */ + public static function configure($httpAdapter, $settingsConfig) { + //need to set the config prior to setting up the adapter because of default settings for the adapter + self::setConfig($settingsConfig); + self::setHttpAdapter($httpAdapter); + } + /** * 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 + * @param Array $settingsConfig - Hashmap that contains config values for the SDK to connect to SparkPost * @throws \Exception */ - 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)){ - throw new \Exception('You must provide an API key'); - } - } else { + public static function setConfig(Array $settingsConfig) { + // Validate API key because its required + if (!isset($settingsConfig['key']) || empty(trim($settingsConfig['key']))){ 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) { + // set config, overriding defaults + foreach ($settingsConfig 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'], + 'Authorization' => self::getConfig()['key'], 'Content-Type' => 'application/json', ]; @@ -75,25 +93,6 @@ class SparkPost { 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 @@ -105,16 +104,31 @@ class SparkPost { return self::$config; } + /** + * TODO: Docs + */ public static function unsetConfig() { self::$config = NULL; } + /** + * TODO: Docs + */ + public static function setHttpAdapter($httpAdapter) { + if (!$httpAdapter instanceOf HttpAdapterInterface) { + throw new \Exception('$httpAdapter paramter must be a valid Ivory\HttpAdapter'); + } + + self::$httpAdapter = $httpAdapter; + self::$httpAdapter->setConfiguration(self::getHttpConfig(self::getConfig())); + } + /** * Retrieves the Http Adapter that was previously setup by the user * @throws \Exception */ public static function getHttpAdapter() { - if (self::$config === null) { + if (self::$httpAdapter === null) { throw new \Exception('No Http Adapter has been provided'); } return self::$httpAdapter; diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php index fc85fa3..c9f83be 100644 --- a/test/unit/APIResourceTest.php +++ b/test/unit/APIResourceTest.php @@ -8,14 +8,14 @@ use Guzzle\Http\Message\Response; class APIResourceTest extends \PHPUnit_Framework_TestCase { - + private $client = null; - + /** * Allows access to private methods - * + * * This is needed to mock the GuzzleHttp\Client responses - * + * * @param string $name * @return ReflectionMethod */ @@ -25,120 +25,119 @@ class APIResourceTest extends \PHPUnit_Framework_TestCase { $method->setAccessible(true); return $method; } - + /** * (non-PHPdoc) * @before * @see PHPUnit_Framework_TestCase::setUp() */ public function setUp() { - SparkPost::setConfig(array('key'=>'blah')); - $this->client = self::getMethod('getHttpClient')->invoke(null); //so we can bootstrap api responses + SparkPost::getHttpHeaders = function ($headers) {return ['what'=>'what']}; APIResource::$endpoint = 'someValidEndpoint'; // when using APIResource directly an endpoint needs to be set. } - - /** - * @desc Ensures that the configuration class is not instantiable. - */ - public function testConstructorCannotBeCalled() { - $class = new \ReflectionClass('\SparkPost\Transmission'); - $this->assertFalse($class->isInstantiable()); - } - - /** - * @desc tests happy path - */ - public function testFetchWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}, {"test":"two"}]}')); - $this->client->addSubscriber($mock); - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'), array('test'=>'two'))), APIResource::fetchResource()); - } - - /** - * @desc tests happy path - */ - public function testDeleteWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}]}')); - $this->client->addSubscriber($mock); - - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'))), APIResource::deleteResource('someId')); - } - - /** - * @desc tests 404 bad response - * @expectedException Exception - * @expectedExceptionMessage The specified resource does not exist - */ - public function testFetchWith404Response() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(404, array())); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests unknown bad response - * @expectedException Exception - * @expectedExceptionMessage Received bad response from SomeValidEndpoint API: 400 - */ - public function testFetchWithOtherBadResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array())); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / - */ - public function testFetchForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests happy path - */ - public function testSuccessfulSend() { - $body = array("result"=>array("transmission_id"=>"11668787484950529"), "status"=>array("message"=> "ok","code"=> "1000")); - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), json_encode($body))); - $this->client->addSubscriber($mock); - - - $this->assertEquals($body, APIResource::sendRequest(array('text'=>'awesome email'))); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessage ["This is a fake error"] - */ - public function testSendFor400Exception() { - $body = array('errors'=>array('This is a fake error')); - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array(), json_encode($body))); - $this->client->addSubscriber($mock); - APIResource::sendRequest(array('text'=>'awesome email')); - } - - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / - */ - public function testSendForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - APIResource::sendRequest(array('text'=>'awesome email')); - } - + // + // /** + // * @desc Ensures that the configuration class is not instantiable. + // */ + // public function testConstructorCannotBeCalled() { + // $class = new \ReflectionClass('\SparkPost\Transmission'); + // $this->assertFalse($class->isInstantiable()); + // } + // + // /** + // * @desc tests happy path + // */ + // public function testFetchWithGoodResponse() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}, {"test":"two"}]}')); + // $this->client->addSubscriber($mock); + // $this->assertEquals(array("results"=>array(array('test'=>'This is a test'), array('test'=>'two'))), APIResource::fetchResource()); + // } + // + // /** + // * @desc tests happy path + // */ + // public function testDeleteWithGoodResponse() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}]}')); + // $this->client->addSubscriber($mock); + // + // $this->assertEquals(array("results"=>array(array('test'=>'This is a test'))), APIResource::deleteResource('someId')); + // } + // + // /** + // * @desc tests 404 bad response + // * @expectedException Exception + // * @expectedExceptionMessage The specified resource does not exist + // */ + // public function testFetchWith404Response() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(404, array())); + // $this->client->addSubscriber($mock); + // APIResource::fetchResource('someId'); + // } + // + // /** + // * @desc tests unknown bad response + // * @expectedException Exception + // * @expectedExceptionMessage Received bad response from SomeValidEndpoint API: 400 + // */ + // public function testFetchWithOtherBadResponse() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(400, array())); + // $this->client->addSubscriber($mock); + // APIResource::fetchResource('someId'); + // } + // + // /** + // * @desc tests bad response + // * @expectedException Exception + // * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / + // */ + // public function testFetchForCatchAllException() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(500)); + // $this->client->addSubscriber($mock); + // APIResource::fetchResource('someId'); + // } + // + // /** + // * @desc tests happy path + // */ + // public function testSuccessfulSend() { + // $body = array("result"=>array("transmission_id"=>"11668787484950529"), "status"=>array("message"=> "ok","code"=> "1000")); + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(200, array(), json_encode($body))); + // $this->client->addSubscriber($mock); + // + // + // $this->assertEquals($body, APIResource::sendRequest(array('text'=>'awesome email'))); + // } + // + // /** + // * @desc tests bad response + // * @expectedException Exception + // * @expectedExceptionMessage ["This is a fake error"] + // */ + // public function testSendFor400Exception() { + // $body = array('errors'=>array('This is a fake error')); + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(400, array(), json_encode($body))); + // $this->client->addSubscriber($mock); + // APIResource::sendRequest(array('text'=>'awesome email')); + // } + // + // + // /** + // * @desc tests bad response + // * @expectedException Exception + // * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / + // */ + // public function testSendForCatchAllException() { + // $mock = new MockPlugin(); + // $mock->addResponse(new Response(500)); + // $this->client->addSubscriber($mock); + // APIResource::sendRequest(array('text'=>'awesome email')); + // } + } diff --git a/test/unit/SparkPostTest.php b/test/unit/SparkPostTest.php index f40461d..43e499f 100644 --- a/test/unit/SparkPostTest.php +++ b/test/unit/SparkPostTest.php @@ -2,17 +2,38 @@ namespace SparkPost\Test; use SparkPost\SparkPost; +use Ivory\HttpAdapter\CurlHttpAdapter; class SparkPostTest extends \PHPUnit_Framework_TestCase { - + + /** + * Allows access to private properties in the Transmission class + * + * @param string $name + * @param {*} + * @return ReflectionMethod + */ + private static function setPrivateProperty($name, $value) { + $class = new \ReflectionClass('\SparkPost\SparkPost'); + $prop = $class->getProperty($name); + $prop->setAccessible(true); + $prop->setValue($value); + } + + + public function setUp() { + $this->setPrivateProperty('config', null); + $this->setPrivateProperty('httpAdapter', null); + } + /** * @desc Ensures that the configuration class is not instantiable. */ public function testConstructorCannotBeCalled() { $class = new \ReflectionClass('\SparkPost\SparkPost'); - $this->assertFalse($class->isInstantiable()); + $this->assertFalse($class->isInstantiable()); } - + /** * @desc Tests that an exception is thrown when a library tries to recieve the config and it has not yet been set. * Since its a singleton this test must come before any setConfig tests. @@ -23,31 +44,31 @@ class SparkPostTest extends \PHPUnit_Framework_TestCase { SparkPost::unsetConfig(); SparkPost::getConfig(); } - + /** * @desc Tests that the api key is set when setting the config * @expectedException Exception * @expectedExceptionMessage You must provide an API key */ public function testSetConfigAPIKeyNotSetException() { - SparkPost::setConfig(array('something'=>'other than an API Key')); + SparkPost::setConfig(['something'=>'other than an API Key']); } - + /** * @desc Tests that the api key is set when setting the config and that its not empty * @expectedException Exception * @expectedExceptionMessage You must provide an API key */ public function testSetConfigAPIKeyEmptyException() { - SparkPost::setConfig(array('key'=>'')); + SparkPost::setConfig(['key'=>'']); } - + /** * @desc Tests overridable values are set while invalid values are ignored */ public function testSetConfigMultipleValuesAndGetConfig() { - SparkPost::setConfig(array('key'=>'lala', 'version'=>'v8', 'port'=>1024, 'someOtherValue'=>'fakeValue')); - + SparkPost::setConfig(['key'=>'lala', 'version'=>'v8', 'port'=>1024, 'someOtherValue'=>'fakeValue']); + $testConfig = SparkPost::getConfig(); $this->assertEquals('lala', $testConfig['key']); $this->assertEquals('v8', $testConfig['version']); @@ -57,5 +78,50 @@ class SparkPostTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('api.sparkpost.com', $testConfig['host']); $this->assertEquals(true, $testConfig['strictSSL']); } + + /** + * @desc tests getting an unset + * @expectedException Exception + * @expectedExceptionMessageRegExp /No Http Adapter/ + */ + public function testGetHttpAdapterForIsset() { + SparkPost::getHttpAdapter(); + } + + /** + * @desc tests failing validation for http adapters + * @expectedException Exception + * @expectedExceptionMessageRegExp /must be a valid Ivory\\HttpAdapter/ + */ + public function testSetInvalidHttpAdapter() { + SparkPost::setHttpAdapter(new \stdClass()); + } + + public function testSetAndGetValidHttpAdapter() { + SparkPost::setConfig(['key'=>'lala']); + SparkPost::setHttpAdapter(new CurlHttpAdapter()); + $this->assertEquals('Ivory\HttpAdapter\CurlHttpAdapter', get_class(Sparkpost::getHttpAdapter())); + } + + public function testConfigure() { + SparkPost::configure(new CurlHttpAdapter(), ['key'=>'lala']); + $this->assertEquals('Ivory\HttpAdapter\CurlHttpAdapter', get_class(Sparkpost::getHttpAdapter())); + } + + public function testDefaultHeaders() { + $key = 'lala'; + SparkPost::setConfig(['key'=>$key]); + $this->assertEquals($key, Sparkpost::getHttpHeaders()['Authorization']); + $this->assertEquals('application/json', Sparkpost::getHttpHeaders()['Content-Type']); + } + + public function testOverrideDefaultHeaders() { + $key = 'lala'; + $headers=['Content-Type'=>'my/type']; + SparkPost::setConfig(['key'=>$key]); + $this->assertEquals($key, Sparkpost::getHttpHeaders($headers)['Authorization']); + $this->assertEquals('my/type', Sparkpost::getHttpHeaders($headers)['Content-Type']); + } + } -?>
\ No newline at end of file +?> |