diff options
author | Jordan Nornhold <nornholdj@gmail.com> | 2015-10-10 10:10:24 -0400 |
---|---|---|
committer | Jordan Nornhold <nornholdj@gmail.com> | 2015-10-10 10:10:24 -0400 |
commit | 7c39c1e35afb32845859289e8a0cd8eaceece5f2 (patch) | |
tree | a3b7e904158fe2145673a1d54676672096675a5f | |
parent | c2e4758d8df8cf7e20451ea3196f2dc918e245e1 (diff) | |
parent | 63022bf7bceb6aa7116159fd347be769594fa8b4 (diff) | |
download | php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.zip php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.tar.gz php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.tar.bz2 |
Merge pull request #22 from SparkPost/http-adapter-update
Http adapter update
26 files changed, 1817 insertions, 1328 deletions
diff --git a/.travis.yml b/.travis.yml index 0de6d9d..0547235 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: php php: - '5.5' - - '5.4' + - '5.6' install: - composer install before_script: @@ -2,6 +2,6 @@ php-sparkpost is maintained by Message Systems. # Contributors -* Jordan Nornhold <jordan.norhold@messagesystems.com> +* Jordan Nornhold <jordan.nornhold@messagesystems.com>, @beardyman * Rich Leland <rich.leland@messagesystems.com>, @richleland * Matthew April <matthew.japril@gmail.com> @@ -19,36 +19,67 @@ Next, run the Composer command to install the SparkPost PHP SDK: composer require sparkpost/php-sparkpost ``` After installing, you need to require Composer's autoloader: -``` +```php require 'vendor/autoload.php'; use SparkPost\SparkPost; ``` -## Getting Started: Your First Mailing +## Setting up a Request Adapter +Because of dependency collision, we have opted to use a request adapter rather than +requiring a request library. This means that your application will need to pass in +a request adapter to the constructor of the SparkPost Library. We use the [Ivory HTTP Adapter] (https://github.com/egeloen/ivory-http-adapter) in SparkPost. Please visit their repo +for a list of supported adapters. If you don't currently use a request library, you will +need to require one and create an adapter from it and pass it along. The example below uses the +GuzzleHttp Client Library. + +An Adapter can be setup like so: +```php +use SparkPost\SparkPost; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; + +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>'YOUR API KEY']); ``` -SparkPost::setConfig(["key"=>"YOUR API KEY"]); + +## Getting Started: Your First Mailing +```php +require 'vendor/autoload.php'; + +use SparkPost\SparkPost; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; + +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>'YOUR API KEY']); try { - // Build your email and send it! - Transmission::send(array('campaign'=>'first-mailing', - 'from'=>'you@your-company.com', - 'subject'=>'First SDK Mailing', - 'html'=>'<html><body><h1>Congratulations, {{name}}!</h1><p>You just sent your very first mailing!</p></body></html>', - 'text'=>'Congratulations, {{name}}!! You just sent your very first mailing!', - 'substitutionData'=>array('name'=>'YOUR FIRST NAME'), - 'recipients'=>array(array('address'=>array('name'=>'YOUR FULL NAME', 'email'=>'YOUR EMAIL ADDRESS' ))) - )); - - echo 'Woohoo! You just sent your first mailing!'; -} catch (Exception $err) { - echo 'Whoops! Something went wrong'; - var_dump($err); + // Build your email and send it! + $results = $sparky->transmission->send([ + 'from'=>'From Envelope <from@sparkpostbox.com>', + 'html'=>'<html><body><h1>Congratulations, {{name}}!</h1><p>You just sent your very first mailing!</p></body></html>', + 'text'=>'Congratulations, {{name}}!! You just sent your very first mailing!', + 'substitutionData'=>['name'=>'YOUR FIRST NAME'] + 'subject'=>'First Mailing From PHP', + 'recipients'=>[ + [ + 'address'=>[ + 'name'=>'YOUR FULL NAME', + 'email'=>'YOUR EMAIL ADDRESS' + ] + ] + ] + ]); + echo 'Woohoo! You just sent your first mailing!'; +} catch (\Exception $err) { + echo 'Whoops! Something went wrong'; + var_dump($err); } ``` ## Learn More * For more detailed examples, check our examples: - * [Transmissions](https://github.com/SparkPost/php-sparkpost/tree/master/examples/transmission) + * [Transmissions](https://github.com/SparkPost/php-sparkpost/tree/master/examples/transmission) * Read our REST API documentation - <http://www.sparkpost.com/docs/introduction> ## Field Descriptions diff --git a/composer.json b/composer.json index d3ea663..211fa90 100644 --- a/composer.json +++ b/composer.json @@ -2,6 +2,7 @@ "name": "sparkpost/php-sparkpost", "description": "SDK for interfacing with SparkPost APIs", "license": "Apache 2.0", + "version": "0.2.0", "authors": [ { "name": "Message Systems, Inc." @@ -14,17 +15,20 @@ "test": "phpunit ./test/unit/" }, "require": { - "php": ">=5.3.0", - "guzzlehttp/guzzle": "3.8.1" + "php": ">=5.5.0", + "egeloen/http-adapter": "*" }, "require-dev": { - "phpunit/phpunit": "4.3.*", - "satooshi/php-coveralls": "dev-master" + "phpunit/phpunit": "4.3.*", + "guzzlehttp/guzzle": "6.*", + "mockery/mockery": "^0.9.4", + "satooshi/php-coveralls": "dev-master" }, "autoload": { - "psr-4": { - "SparkPost\\": "lib/SparkPost/", - "SparkPost\\SendGridCompatibility\\": "lib/SendGridCompatibility/" - } + "psr-4": { + "SparkPost\\": "lib/SparkPost/", + "SparkPost\\SendGridCompatibility\\": "lib/SendGridCompatibility/", + "SparkPost\\Test\\TestUtils\\": "test/unit/TestUtils/" + } } } diff --git a/composer.lock b/composer.lock index 7d6230f..da4ff55 100644 --- a/composer.lock +++ b/composer.lock @@ -4,71 +4,66 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "2957391d0aa06089732d538ec48c07c5", - "content-hash": "5c512cd48cf3be9560dd10f0f71ea709", + "hash": "3e19d00ab9d875ecad4120ce327766dd", + "content-hash": "781dee6a3f19ff78fcac2dc4814ea1cd", "packages": [ { - "name": "guzzlehttp/guzzle", - "version": "v3.8.1", + "name": "egeloen/http-adapter", + "version": "0.8.0", "source": { "type": "git", - "url": "https://github.com/guzzle/guzzle.git", - "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba" + "url": "https://github.com/egeloen/ivory-http-adapter.git", + "reference": "9641f11487ec26b24c6bbcee4f267cf62f60b855" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/4de0618a01b34aa1c8c33a3f13f396dcd3882eba", - "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba", + "url": "https://api.github.com/repos/egeloen/ivory-http-adapter/zipball/9641f11487ec26b24c6bbcee4f267cf62f60b855", + "reference": "9641f11487ec26b24c6bbcee4f267cf62f60b855", "shasum": "" }, "require": { - "ext-curl": "*", - "php": ">=5.3.3", - "symfony/event-dispatcher": ">=2.1" - }, - "replace": { - "guzzle/batch": "self.version", - "guzzle/cache": "self.version", - "guzzle/common": "self.version", - "guzzle/http": "self.version", - "guzzle/inflection": "self.version", - "guzzle/iterator": "self.version", - "guzzle/log": "self.version", - "guzzle/parser": "self.version", - "guzzle/plugin": "self.version", - "guzzle/plugin-async": "self.version", - "guzzle/plugin-backoff": "self.version", - "guzzle/plugin-cache": "self.version", - "guzzle/plugin-cookie": "self.version", - "guzzle/plugin-curlauth": "self.version", - "guzzle/plugin-error-response": "self.version", - "guzzle/plugin-history": "self.version", - "guzzle/plugin-log": "self.version", - "guzzle/plugin-md5": "self.version", - "guzzle/plugin-mock": "self.version", - "guzzle/plugin-oauth": "self.version", - "guzzle/service": "self.version", - "guzzle/stream": "self.version" + "php": ">=5.4.8", + "zendframework/zend-diactoros": "^1.1" }, "require-dev": { - "doctrine/cache": "*", - "monolog/monolog": "1.*", - "phpunit/phpunit": "3.7.*", - "psr/log": "1.0.*", - "symfony/class-loader": "*", - "zendframework/zend-cache": "<2.3", - "zendframework/zend-log": "<2.3" + "cakephp/cakephp": "^3.0.3", + "ext-curl": "*", + "guzzle/guzzle": "^3.9.4@dev", + "guzzlehttp/guzzle": "^4.1.4|^5.0|^6.0", + "kriswallsmith/buzz": "^0.13", + "nategood/httpful": "^0.2.17", + "phpunit/phpunit": "^4.0", + "phpunit/phpunit-mock-objects": "dev-matcher-verify as 2.3.x-dev", + "psr/log": "^1.0", + "react/dns": "^0.4.1", + "react/http-client": "^0.4", + "satooshi/php-coveralls": "^0.6", + "symfony/event-dispatcher": "^2.0", + "zendframework/zend-http": "^2.3.4", + "zendframework/zendframework1": ">=1.12.9,<=1.12.14|^1.12.16" + }, + "suggest": { + "ext-curl": "Allows you to use the cURL adapter", + "ext-http": "Allows you to use the PECL adapter", + "guzzle/guzzle": "Allows you to use the Guzzle 3 adapter", + "guzzlehttp/guzzle": "Allows you to use the Guzzle 4 adapter", + "kriswallsmith/buzz": "Allows you to use the Buzz adapter", + "nategood/httpful": "Allows you to use the httpful adapter", + "psr/log": "Allows you to use the logger event subscriber", + "symfony/event-dispatcher": "Allows you to use the event lifecycle", + "symfony/stopwatch": "Allows you to use the stopwatch http adapter and event subscriber", + "zendframework/zend-http": "Allows you to use the Zend 2 adapter", + "zendframework/zendframework1": "Allows you to use the Zend 1 adapter" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.8-dev" + "dev-master": "0.8-dev" } }, "autoload": { - "psr-0": { - "Guzzle": "src/", - "Guzzle\\Tests": "tests/" + "psr-4": { + "Ivory\\HttpAdapter\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -77,66 +72,45 @@ ], "authors": [ { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, - { - "name": "Guzzle Community", - "homepage": "https://github.com/guzzle/guzzle/contributors" + "name": "Eric GELOEN", + "email": "geloen.eric@gmail.com" } ], - "description": "Guzzle is a PHP HTTP client library and framework for building RESTful web service clients", - "homepage": "http://guzzlephp.org/", + "description": "Issue HTTP request for PHP 5.3+.", "keywords": [ - "client", - "curl", - "framework", "http", - "http client", - "rest", - "web service" + "http-adapter", + "http-client", + "psr-7" ], - "time": "2014-01-28 22:29:15" + "time": "2015-08-12 09:35:40" }, { - "name": "symfony/event-dispatcher", - "version": "v2.7.5", + "name": "psr/http-message", + "version": "1.0", "source": { "type": "git", - "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9" + "url": "https://github.com/php-fig/http-message.git", + "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", - "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", + "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", "shasum": "" }, "require": { - "php": ">=5.3.9" - }, - "require-dev": { - "psr/log": "~1.0", - "symfony/config": "~2.0,>=2.0.5", - "symfony/dependency-injection": "~2.6", - "symfony/expression-language": "~2.6", - "symfony/phpunit-bridge": "~2.7", - "symfony/stopwatch": "~2.3" - }, - "suggest": { - "symfony/dependency-injection": "", - "symfony/http-kernel": "" + "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { - "Symfony\\Component\\EventDispatcher\\": "" + "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -145,17 +119,70 @@ ], "authors": [ { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" } ], - "description": "Symfony EventDispatcher Component", - "homepage": "https://symfony.com", - "time": "2015-09-22 13:49:29" + "description": "Common interface for HTTP messages", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2015-05-04 20:22:00" + }, + { + "name": "zendframework/zend-diactoros", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/zendframework/zend-diactoros.git", + "reference": "e2f5c12916c74da384058d0dfbc7fbc0b03d1181" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/e2f5c12916c74da384058d0dfbc7fbc0b03d1181", + "reference": "e2f5c12916c74da384058d0dfbc7fbc0b03d1181", + "shasum": "" + }, + "require": { + "php": ">=5.4", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "~1.0.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.6", + "squizlabs/php_codesniffer": "^2.3.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev", + "dev-develop": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Zend\\Diactoros\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "description": "PSR HTTP Message implementations", + "homepage": "https://github.com/zendframework/zend-diactoros", + "keywords": [ + "http", + "psr", + "psr-7" + ], + "time": "2015-08-10 20:04:20" } ], "packages-dev": [ @@ -309,6 +336,287 @@ "time": "2015-03-18 18:23:50" }, { + "name": "guzzlehttp/guzzle", + "version": "6.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "66fd14b4d0b8f2389eaf37c5458608c7cb793a81" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/66fd14b4d0b8f2389eaf37c5458608c7cb793a81", + "reference": "66fd14b4d0b8f2389eaf37c5458608c7cb793a81", + "shasum": "" + }, + "require": { + "guzzlehttp/promises": "~1.0", + "guzzlehttp/psr7": "~1.1", + "php": ">=5.5.0" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "~4.0", + "psr/log": "~1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.1-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "time": "2015-09-08 17:36:26" + }, + { + "name": "guzzlehttp/promises", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "97fe7210def29451ec74923b27e552238defd75a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/97fe7210def29451ec74923b27e552238defd75a", + "reference": "97fe7210def29451ec74923b27e552238defd75a", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2015-08-15 19:37:21" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "4ef919b0cf3b1989523138b60163bbcb7ba1ff7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/4ef919b0cf3b1989523138b60163bbcb7ba1ff7e", + "reference": "4ef919b0cf3b1989523138b60163bbcb7ba1ff7e", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "PSR-7 message implementation", + "keywords": [ + "http", + "message", + "stream", + "uri" + ], + "time": "2015-08-15 19:32:36" + }, + { + "name": "hamcrest/hamcrest-php", + "version": "v1.2.2", + "source": { + "type": "git", + "url": "https://github.com/hamcrest/hamcrest-php.git", + "reference": "b37020aa976fa52d3de9aa904aa2522dc518f79c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/b37020aa976fa52d3de9aa904aa2522dc518f79c", + "reference": "b37020aa976fa52d3de9aa904aa2522dc518f79c", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "replace": { + "cordoval/hamcrest-php": "*", + "davedevelopment/hamcrest-php": "*", + "kodova/hamcrest-php": "*" + }, + "require-dev": { + "phpunit/php-file-iterator": "1.3.3", + "satooshi/php-coveralls": "dev-master" + }, + "type": "library", + "autoload": { + "classmap": [ + "hamcrest" + ], + "files": [ + "hamcrest/Hamcrest.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD" + ], + "description": "This is the PHP port of Hamcrest Matchers", + "keywords": [ + "test" + ], + "time": "2015-05-11 14:41:42" + }, + { + "name": "mockery/mockery", + "version": "0.9.4", + "source": { + "type": "git", + "url": "https://github.com/padraic/mockery.git", + "reference": "70bba85e4aabc9449626651f48b9018ede04f86b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/padraic/mockery/zipball/70bba85e4aabc9449626651f48b9018ede04f86b", + "reference": "70bba85e4aabc9449626651f48b9018ede04f86b", + "shasum": "" + }, + "require": { + "hamcrest/hamcrest-php": "~1.1", + "lib-pcre": ">=7.0", + "php": ">=5.3.2" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.9.x-dev" + } + }, + "autoload": { + "psr-0": { + "Mockery": "library/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Pádraic Brady", + "email": "padraic.brady@gmail.com", + "homepage": "http://blog.astrumfutura.com" + }, + { + "name": "Dave Marshall", + "email": "dave.marshall@atstsolutions.co.uk", + "homepage": "http://davedevelopment.co.uk" + } + ], + "description": "Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL). Designed as a drop in alternative to PHPUnit's phpunit-mock-objects library, Mockery is easy to integrate with PHPUnit and can operate alongside phpunit-mock-objects without the World ending.", + "homepage": "http://github.com/padraic/mockery", + "keywords": [ + "BDD", + "TDD", + "library", + "mock", + "mock objects", + "mockery", + "stub", + "test", + "test double", + "testing" + ], + "time": "2015-04-02 19:54:00" + }, + { "name": "phpunit/php-code-coverage", "version": "2.2.3", "source": { @@ -1217,6 +1525,64 @@ "time": "2015-09-25 08:32:23" }, { + "name": "symfony/event-dispatcher", + "version": "v2.7.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", + "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "~2.0,>=2.0.5", + "symfony/dependency-injection": "~2.6", + "symfony/expression-language": "~2.6", + "symfony/phpunit-bridge": "~2.7", + "symfony/stopwatch": "~2.3" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com", + "time": "2015-09-22 13:49:29" + }, + { "name": "symfony/filesystem", "version": "v2.7.5", "source": { @@ -1372,7 +1738,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=5.3.0" + "php": ">=5.5.0" }, "platform-dev": [] } diff --git a/examples/bootstrap.php b/examples/bootstrap.php index 8a5f839..774b159 100644 --- a/examples/bootstrap.php +++ b/examples/bootstrap.php @@ -1,3 +1,3 @@ <?php - require_once dirname(__FILE__).'/../vendor/autoload.php'; + require_once dirname(__FILE__).'/../vendor/autoload.php'; ?>
\ No newline at end of file diff --git a/examples/transmission/get_all_transmissions.php b/examples/transmission/get_all_transmissions.php index fb62ec7..afbe5aa 100644 --- a/examples/transmission/get_all_transmissions.php +++ b/examples/transmission/get_all_transmissions.php @@ -3,18 +3,20 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try { - $results = Transmission::all(); - echo 'Congrats you can use your SDK!'; + $results = $sparky->transmission->all(); + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/get_transmission.php b/examples/transmission/get_transmission.php index b4781d7..0bda953 100644 --- a/examples/transmission/get_transmission.php +++ b/examples/transmission/get_transmission.php @@ -3,18 +3,20 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try { - $results = Transmission::find('Your Transmission Id'); - echo 'Congrats you can use your SDK!'; + $results = $sparky->transmission->find('Your Transmission ID'); + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/rfc822.php b/examples/transmission/rfc822.php index 8163693..1054c57 100644 --- a/examples/transmission/rfc822.php +++ b/examples/transmission/rfc822.php @@ -3,27 +3,29 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-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" - )); - echo 'Congrats you can use your SDK!'; + $results = $sparky->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(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/send_transmission_all_fields.php b/examples/transmission/send_transmission_all_fields.php index 28edbcc..749f0cb 100644 --- a/examples/transmission/send_transmission_all_fields.php +++ b/examples/transmission/send_transmission_all_fields.php @@ -3,45 +3,48 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try{ - $results = Transmission::send(array( - "campaign"=>"my-campaign", - "metadata"=>array( - "sample_campaign"=>true, - "type"=>"these are custom fields" - ), - "substitutionData"=>array( - "name"=>"Test Name" - ), - "description"=>"my description", - "replyTo"=>"reply@test.com", - "customHeaders"=>array( - "X-Custom-Header"=>"Sample Custom Header" - ), - "trackOpens"=>false, - "trackClicks"=>false, - "from"=>"From Envelope <from@example.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" - ) - ) - ) - )); - echo 'Congrats you can use your SDK!'; + $results = $sparky->transmission->send([ + 'campaign'=>'my-campaign', + 'metadata'=>[ + 'sample_campaign'=>true, + 'type'=>'these are custom fields' + ], + 'substitutionData'=>[ + 'name'=>'Test Name' + ], + 'description'=>'my description', + 'replyTo'=>'reply@test.com', + 'customHeaders'=>[ + 'X-Custom-Header'=>'Sample Custom Header' + ], + 'trackOpens'=>false, + 'trackClicks'=>false, + 'from'=>'From Envelope <from@sparkpostbox.com>', + 'html'=>'<p>Hello World! Your name is: {{name}}</p>', + 'text'=>'Hello World!', + 'subject'=>'Example Email: {{name}}', + 'recipients'=>[ + [ + 'address'=>[ + 'email'=>'john.doe@example.com' + ] + ] + ] + ]); + + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/simple_send.php b/examples/transmission/simple_send.php index eafc176..5844ecc 100644 --- a/examples/transmission/simple_send.php +++ b/examples/transmission/simple_send.php @@ -3,30 +3,32 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-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" - ) - ) - ) - )); - echo 'Congrats you can use your SDK!'; + $results = $sparky->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(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/stored_recipients_inline_content.php b/examples/transmission/stored_recipients_inline_content.php index a2dd8aa..9348f9b 100644 --- a/examples/transmission/stored_recipients_inline_content.php +++ b/examples/transmission/stored_recipients_inline_content.php @@ -3,27 +3,29 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try { - $results = Transmission::send(array( - "campaign"=>"my-campaign", - "from"=>"From Envelope <from@example.com>", - "html"=>"<p>Hello World! Your name is: {{name}}</p>", - "text"=>"Hello World!", - "subject"=>"Example Email: {{name}}", - "recipientList"=>'Example List' - )); + $results = $sparky->transmission->send([ + 'campaign'=>'my-campaign', + '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!'; + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/examples/transmission/stored_template_send.php b/examples/transmission/stored_template_send.php index 52dbb27..2e22609 100644 --- a/examples/transmission/stored_template_send.php +++ b/examples/transmission/stored_template_send.php @@ -3,28 +3,30 @@ namespace Examples\Transmisson; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\Transmission; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try { - $results = Transmission::send(array( - "from"=>"From Envelope <from@example.com>", - "recipients"=>array( - array( - "address"=>array( - "email"=>"john.doe@sample.com" - ) - ) - ), - "template"=>"my-template" - )); - echo 'Congrats you can use your SDK!'; + $results = $sparky->transmission->send([ + 'from'=>'From Envelope <from@sparkpostbox.com>', + 'recipients'=>[ + [ + 'address'=>[ + 'email'=>'john.doe@example.com' + ] + ] + ], + 'template'=>'my-first-email' + ]); + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/examples/unwrapped/create_template.php b/examples/unwrapped/create_template.php index 0e24fd6..a3431d4 100644 --- a/examples/unwrapped/create_template.php +++ b/examples/unwrapped/create_template.php @@ -3,27 +3,32 @@ namespace Examples\Unwrapped; require_once (dirname(__FILE__).'/../bootstrap.php'); //pull in API key config -$configFile = file_get_contents(dirname(__FILE__) . "/../example-config.json"); +$configFile = file_get_contents(dirname(__FILE__) . '/../example-config.json'); $config = json_decode($configFile, true); use SparkPost\SparkPost; -use SparkPost\APIResource; +use GuzzleHttp\Client; +use Ivory\HttpAdapter\Guzzle6HttpAdapter; -SparkPost::setConfig(array('key'=>$config['api-key'])); +$httpAdapter = new Guzzle6HttpAdapter(new Client()); +$sparky = new SparkPost($httpAdapter, ['key'=>$config['api-key']]); try { - // define the endpoint - APIResource::$endpoint = 'templates'; + // define the endpoint + $sparky->setupUnwrapped('templates'); - $templateConfig = array( - '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); - echo 'Congrats you can use your SDK!'; + $templateConfig = [ + 'name' => 'Summer Sale!', + 'id'=>'jordan-test-summer-sale', + 'content'=> [ + 'from' => 'from@sparkpostbox.com', + 'subject' => 'Summer deals', + 'html' => '<b>Check out these deals!</b>' + ] + ]; + $results = $sparky->templates->create($templateConfig); + echo 'Congrats you can use your SDK!'; } catch (\Exception $exception) { - echo $exception->getMessage(); + echo $exception->getMessage(); } ?> diff --git a/lib/SendGridCompatibility/Email.php b/lib/SendGridCompatibility/Email.php index 5351324..251b7f2 100644 --- a/lib/SendGridCompatibility/Email.php +++ b/lib/SendGridCompatibility/Email.php @@ -2,198 +2,198 @@ namespace SparkPost\SendGridCompatibility; class Email { - public $model; - - - /** - * @desc Sets up the model for saving the configuration - */ - public function __construct() { - $this->model = array(); - } - - /** - * @desc adds addresses as recipients - * @param string $address - * @param string $name optional - * @return \SparkPost\SendGridCompatibility\Email - */ - public function addTo($address, $name = null) { - if (!isset($this->model['recipients'])) { - $this->model['recipients'] = array(); - } - - if(isset($name)) { - $address = array('address'=>array('email'=>$address, 'name'=>$name)); - } else { - $address = array('address'=>array('email'=>$address)); - } - - array_push($this->model['recipients'], $address); - return $this; - } - - /** - * @desc explicitly sets a list of addresses - * @param array $addresses - * @return \SparkPost\SendGridCompatibility\Email - */ - public function setTos(array $addresses) { - $this->model['recipients'] = $addresses; - return $this; - } - - /** - * @desc sets the from address - * @param string $address - * @return \MessageSystems\SendGridCompatibility\Email - */ - public function setFrom($address) { - $this->model['from'] = array('email' => $address); - return $this; - } - - /** - * @desc sets the name for the from address - * @param string $name - */ - public function setFromName($name) { - if(!isset($this->model['from'])){ - throw new \Exception('Must set "From" prior to setting "From Name".'); - } - $this->model['from']['name'] = $name; - return $this; - } - - /** - * @desc sets the reply to field - * @param string $address - * @return \MessageSystems\SendGridCompatibility\Email - */ - public function setReplyTo ($address) { - $this->model['replyTo'] = $address; - return $this; - } - - /** - * @desc throws an error because bcc fields are not yet implemented. - * @throws \Exception - * @param string $address - * @return \MessageSystems\SendGridCompatibility\Email - */ - public function addBcc($address) { - throw new \Exception('Adding bcc recipients is not yet supported, try adding them as a "to" address'); - } - - /** - * @desc sets the subject header - * @param string $subject - * @return \SparkPost\SendGridCompatibility\Email - */ - public function setSubject($subject) { - $this->model['subject'] = $subject; - return $this; - } - - /** - * @desc sets the text body - * @param string $text - * @return \SparkPost\SendGridCompatibility\Email - */ - public function setText($text) { - $this->model['text'] = $text; - return $this; - } - - /** - * @desc sets the html body - * @param string $html - * @return \SparkPost\SendGridCompatibility\Email - */ - public function setHtml($html) { - $this->model['html'] = $html; - return $this; - } - - /** - * @desc Throws an exception since adding categories is not yet supported - * @throws \Exception - * @param string $category - * @throws \Exception - */ - public function addCategory($category) { - throw new \Exception('Adding categories is not yet supported'); - } - - /** - * @desc Throws an exception since adding attachments is not yet supported - * @throws Exception - * @param mixed $attachment - */ - public function addAttachment($attachment) { - throw new \Exception('Adding attachments is not yet supported'); - } - - /** - * @desc Adds transmission level substitution data - * @param string $name - * @param mixed $values - * @return \SparkPost\SendGridCompatibility\Email - */ - public function addSubstitution($name, $values) { - if (!isset($this->model['substitutionData'])) { - $this->model['substitutionData'] = array(); - } - $this->model['substitutionData'][$name] = $values; - - return $this; - } - - /** - * @desc Adds transmission level substitution data - * @param string $name - * @param mixed $values - */ - public function addSection($name, $values) { - $this->addSubstitution($name, $values); - } - - /** - * @desc Throws an exception because arguments for third party systems is not supported - * @throws Exception - * @param mixed $value - */ - public function addUniqueArg($key, $value) { - throw new \Exception('Adding Unique Arguments is not yet supported'); - } - - /** - * @desc Throws an exception because arguments for third party systems is not supported - * @throws Exception - * @param mixed $values - */ - public function setUniqueArgs(array $values) { - throw new \Exception('Setting Unique Arguments is not yet supported'); - } - - /** - * @desc Adds custom headers to the email header - * @param string $name - * @param string $value - */ - public function addHeader($name, $value) { - if (!isset($this->model['customHeaders'])) { - $this->model['customHeaders'] = array(); - } - $this->model['customHeaders'][$name] = $value; - } - - /** - * @desc converts this object to a configuration for a SparkPost transmission - * @return array - */ - public function toSparkPostTransmission() { - return $this->model; - } + public $model; + + + /** + * @desc Sets up the model for saving the configuration + */ + public function __construct() { + $this->model = array(); + } + + /** + * @desc adds addresses as recipients + * @param string $address + * @param string $name optional + * @return \SparkPost\SendGridCompatibility\Email + */ + public function addTo($address, $name = null) { + if (!isset($this->model['recipients'])) { + $this->model['recipients'] = array(); + } + + if(isset($name)) { + $address = array('address'=>array('email'=>$address, 'name'=>$name)); + } else { + $address = array('address'=>array('email'=>$address)); + } + + array_push($this->model['recipients'], $address); + return $this; + } + + /** + * @desc explicitly sets a list of addresses + * @param array $addresses + * @return \SparkPost\SendGridCompatibility\Email + */ + public function setTos(array $addresses) { + $this->model['recipients'] = $addresses; + return $this; + } + + /** + * @desc sets the from address + * @param string $address + * @return \MessageSystems\SendGridCompatibility\Email + */ + public function setFrom($address) { + $this->model['from'] = array('email' => $address); + return $this; + } + + /** + * @desc sets the name for the from address + * @param string $name + */ + public function setFromName($name) { + if(!isset($this->model['from'])){ + throw new \Exception('Must set \'From\' prior to setting \'From Name\'.'); + } + $this->model['from']['name'] = $name; + return $this; + } + + /** + * @desc sets the reply to field + * @param string $address + * @return \MessageSystems\SendGridCompatibility\Email + */ + public function setReplyTo ($address) { + $this->model['replyTo'] = $address; + return $this; + } + + /** + * @desc throws an error because bcc fields are not yet implemented. + * @throws \Exception + * @param string $address + * @return \MessageSystems\SendGridCompatibility\Email + */ + public function addBcc($address) { + throw new \Exception('Adding bcc recipients is not yet supported, try adding them as a \'to\' address'); + } + + /** + * @desc sets the subject header + * @param string $subject + * @return \SparkPost\SendGridCompatibility\Email + */ + public function setSubject($subject) { + $this->model['subject'] = $subject; + return $this; + } + + /** + * @desc sets the text body + * @param string $text + * @return \SparkPost\SendGridCompatibility\Email + */ + public function setText($text) { + $this->model['text'] = $text; + return $this; + } + + /** + * @desc sets the html body + * @param string $html + * @return \SparkPost\SendGridCompatibility\Email + */ + public function setHtml($html) { + $this->model['html'] = $html; + return $this; + } + + /** + * @desc Throws an exception since adding categories is not yet supported + * @throws \Exception + * @param string $category + * @throws \Exception + */ + public function addCategory($category) { + throw new \Exception('Adding categories is not yet supported'); + } + + /** + * @desc Throws an exception since adding attachments is not yet supported + * @throws Exception + * @param mixed $attachment + */ + public function addAttachment($attachment) { + throw new \Exception('Adding attachments is not yet supported'); + } + + /** + * @desc Adds transmission level substitution data + * @param string $name + * @param mixed $values + * @return \SparkPost\SendGridCompatibility\Email + */ + public function addSubstitution($name, $values) { + if (!isset($this->model['substitutionData'])) { + $this->model['substitutionData'] = array(); + } + $this->model['substitutionData'][$name] = $values; + + return $this; + } + + /** + * @desc Adds transmission level substitution data + * @param string $name + * @param mixed $values + */ + public function addSection($name, $values) { + $this->addSubstitution($name, $values); + } + + /** + * @desc Throws an exception because arguments for third party systems is not supported + * @throws Exception + * @param mixed $value + */ + public function addUniqueArg($key, $value) { + throw new \Exception('Adding Unique Arguments is not yet supported'); + } + + /** + * @desc Throws an exception because arguments for third party systems is not supported + * @throws Exception + * @param mixed $values + */ + public function setUniqueArgs(array $values) { + throw new \Exception('Setting Unique Arguments is not yet supported'); + } + + /** + * @desc Adds custom headers to the email header + * @param string $name + * @param string $value + */ + public function addHeader($name, $value) { + if (!isset($this->model['customHeaders'])) { + $this->model['customHeaders'] = array(); + } + $this->model['customHeaders'][$name] = $value; + } + + /** + * @desc converts this object to a configuration for a SparkPost transmission + * @return array + */ + public function toSparkPostTransmission() { + return $this->model; + } } -?>
\ No newline at end of file +?> diff --git a/lib/SendGridCompatibility/SendGrid.php b/lib/SendGridCompatibility/SendGrid.php index a85337a..7f8697a 100644 --- a/lib/SendGridCompatibility/SendGrid.php +++ b/lib/SendGridCompatibility/SendGrid.php @@ -1,22 +1,24 @@ <?php namespace SparkPost\SendGridCompatibility; -use SparkPost\Transmission; +use SparkPost\SparkPost; use SparkPost\SendGridCompatibility\Email; -use SparkPost\Configuration; class SendGrid{ - public function __construct($username, $password, $options = null) { - //username isn't used in our system - $opts = array('key'=>$password); - if (!is_null($options)) { - $opts = array_merge($opts, $options); - } - Configuration::setConfig($opts); - } - - public function send(Email $email) { - Trasmission::send($email->toSparkPostTransmission()); - } + private $sparky; + + public function __construct($username, $password, $options = null, $httpAdapter) { + //username isn't used in our system + $opts = array('key'=>$password); + if (!is_null($options)) { + $opts = array_merge($opts, $options); + } + + $this->sparky = new SparkPost($httpAdapter, $opts); + } + + public function send(Email $email) { + $this->sparky->transmission->send($email->toSparkPostTransmission()); + } } -?>
\ No newline at end of file +?> diff --git a/lib/SparkPost/APIResource.php b/lib/SparkPost/APIResource.php index 469ba7e..a2cd5a6 100644 --- a/lib/SparkPost/APIResource.php +++ b/lib/SparkPost/APIResource.php @@ -1,216 +1,210 @@ <?php namespace SparkPost; -use Guzzle\Http\Client; -use Guzzle\Http\Exception\ClientErrorResponseException; +use Ivory\HttpAdapter\HttpAdapterException; +use SparkPost\SparkPost; /** * @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) { - //get mapping - if( empty(static::$parameterMappings) ) { - // if parameterMappings is empty we can assume that no wrapper is defined - // for the current endpoint and we will use the mapKey to define the mappings directly - $mapPath = $mapKey; - }elseif(array_key_exists($mapKey, static::$parameterMappings)) { - // use only defined parameter mappings to construct $model - $mapPath = static::$parameterMappings[$mapKey]; - } else { - return; - } - - $path = explode('.', $mapPath); - $temp = &$model; - foreach( $path as $key ) { - if( !isset($temp[$key]) ){ - $temp[$key] = null; - } - $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 - */ - 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()); - } - } - - - /** - * @desc Wrapper method for issuing GET request to current API endpoint - * - * @param string $resourcePath (optional) string resource path of specific resource - * @param array $options (optional) query string parameters - * @return array Result set of transmissions found - */ - public static function fetchResource( $resourcePath=null, $options=array() ) { - return self::callResource( 'get', $resourcePath, $options ); - } - - /** - * @desc Wrapper method for issuing DELETE request to current API endpoint - * - * @param string $resourcePath (optional) string resource path of specific resource - * @param array $options (optional) query string parameters - * @return array Result set of transmissions found - */ - public static function deleteResource( $resourcePath=null, $options=array() ) { - return self::callResource( 'delete', $resourcePath, $options ); - } - - /** - * @desc Private Method for issuing GET and DELETE request to current API endpoint - * - * This method is responsible for getting the collection _and_ - * a specific entity from the API endpoint - * - * If resourcePath parameter is omitted, then we fetch the collection - * - * @param string $action HTTP method type - * @param string $resourcePath (optional) string resource path of specific resource - * @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); - if (!is_null($resourcePath)){ - $url .= '/'.$resourcePath; - } - - // untested: - if( !empty($options) ) { - $queryString = http_build_query($options); - $url .= '?'.$queryString; - } - - $request = self::getHttpClient(); - - //make request - try { - $response = $request->{$action}($url, array('authorization' => $hostConfig['key']), array("verify"=>$hostConfig['strictSSL']))->send(); - return $response->json(); - } - /* - * 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 ); - } - /* - * 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()); - } - } - + + /** + * @desc name of the API endpoint, mainly used for URL construction. + * This is public to provide an interface + * + * @var string + */ + public $endpoint; + + /** + * @desc Mapping for values passed into the send method to the values needed for the respective API + * @var array + */ + protected static $parameterMappings = []; + + /** + * @desc Sets up default structure and default values for the model that is acceptable by the API + * @var array + */ + protected static $structure = []; + + /** + * @desc SparkPost reference for httpAdapters and configs + */ + protected $sparkpost; + + /** + * @desc Initializes config and httpAdapter for use later. + * @param $sparkpost SparkPost\SparkPost provides api configuration information + */ + public function __construct(SparkPost $sparkpost) { + $this->sparkpost = $sparkpost; + } + + /** + * @desc Private Method helper to reference parameter mappings and set the right value for the right parameter + * + * @param array $model (pass by reference) the set of values to map + * @param string $mapKey a dot syntax path determining which value to set + * @param mixed $value value for the given path + */ + protected function setMappedValue(&$model, $mapKey, $value) { + //get mapping + if( empty(static::$parameterMappings) ) { + // if parameterMappings is empty we can assume that no wrapper is defined + // for the current endpoint and we will use the mapKey to define the mappings directly + $mapPath = $mapKey; + }elseif(array_key_exists($mapKey, static::$parameterMappings)) { + // use only defined parameter mappings to construct $model + $mapPath = static::$parameterMappings[$mapKey]; + } else { + return; + } + + $path = explode('.', $mapPath); + $temp = &$model; + foreach( $path as $key ) { + if( !isset($temp[$key]) ){ + $temp[$key] = null; + } + $temp = &$temp[$key]; + } + $temp = $value; + + } + + /** + * @desc maps values from the passed in model to those needed for the request + * @param $requestConfig the passed in model + * @param $model the set of defaults + * @return array A model ready for the body of a request + */ + protected function buildRequestModel(Array $requestConfig, Array $model=[] ) { + foreach($requestConfig as $key => $value) { + $this->setMappedValue($model, $key, $value); + } + return $model; + } + + /** + * @desc posts to the api with a supplied body + * @param body post body for the request + * @return array Result of the request + */ + public function create(Array $body=[]) { + return $this->callResource( 'post', null, ['body'=>$body]); + } + + /** + * @desc Makes a put request to the api with a supplied body + * @param body Put body for the request + * @return array Result of the request + */ + public function update( $resourcePath, Array $body=[]) { + return $this->callResource( 'put', $resourcePath, ['body'=>$body]); + } + + /** + * @desc Wrapper method for issuing GET request to current API endpoint + * + * @param string $resourcePath (optional) string resource path of specific resource + * @param array $options (optional) query string parameters + * @return array Result of the request + */ + public function get( $resourcePath=null, Array $query=[] ) { + return $this->callResource( 'get', $resourcePath, ['query'=>$query] ); + } + + /** + * @desc Wrapper method for issuing DELETE request to current API endpoint + * + * @param string $resourcePath (optional) string resource path of specific resource + * @param array $options (optional) query string parameters + * @return array Result of the request + */ + public function delete( $resourcePath=null, Array $query=[] ) { + return $this->callResource( 'delete', $resourcePath, ['query'=>$query] ); + } + + + /** + * @desc assembles a URL for a request + * @param string $resourcePath path after the initial endpoint + * @param array options array with an optional value of query with values to build a querystring from. + * @return string the assembled URL + */ + private function buildUrl($resourcePath, $options) { + $url = join(['/', $this->endpoint, '/']); + if (!is_null($resourcePath)){ + $url .= $resourcePath; + } + + if( !empty($options['query'])) { + $queryString = http_build_query($options['query']); + $url .= '?'.$queryString; + } + + return $url; + } + + + /** + * @desc Prepares a body for put and post requests + * @param array options array with an optional value of body with values to build a request body from. + * @return string|null A json encoded string or null if no body was provided + */ + private function buildBody($options) { + $body = null; + if( !empty($options['body']) ) { + $model = static::$structure; + $requestModel = $this->buildRequestModel( $options['body'], $model ); + $body = json_encode($requestModel); + } + return $body; + } + + + /** + * @desc Private Method for issuing GET and DELETE request to current API endpoint + * + * This method is responsible for getting the collection _and_ + * a specific entity from the API endpoint + * + * If resourcePath parameter is omitted, then we fetch the collection + * + * @param string $action HTTP method type + * @param string $resourcePath (optional) string resource path of specific resource + * @param array $options (optional) query string parameters + * @return array Result set of action performed on resource + */ + private function callResource( $action, $resourcePath=null, $options=[] ) { + $action = strtoupper($action); // normalize + + $url = $this->buildUrl($resourcePath, $options); + $body = $this->buildBody($options); + + //make request + try { + $response = $this->sparkpost->httpAdapter->send($url, $action, $this->sparkpost->getHttpHeaders(), $body); + return json_decode($response->getBody()->getContents(), true); + } + /* + * 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($this->endpoint).' API: '. $statusCode ); + } + /* + * Handles 5XX Errors, Configuration Errors, and a catch all for other errors + */ + catch (\Exception $exception) { + throw new \Exception('Unable to contact '.ucfirst($this->endpoint).' API: '. $exception->getMessage()); + } + } + } diff --git a/lib/SparkPost/SparkPost.php b/lib/SparkPost/SparkPost.php index 755df46..f88d847 100644 --- a/lib/SparkPost/SparkPost.php +++ b/lib/SparkPost/SparkPost.php @@ -1,60 +1,130 @@ <?php namespace SparkPost; +use Ivory\HttpAdapter\Configuration; +use Ivory\HttpAdapter\HttpAdapterInterface; class SparkPost { - - private static $config; - private static $defaults = array( - 'host'=>'api.sparkpost.com', - 'protocol'=>'https', - 'port'=>443, - 'strictSSL'=>true, - 'key'=>'', - '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 - if (isset($configMap['key'])){ - $key = trim($configMap['key']); - if(empty($key)){ - throw new \Exception('You must provide an API key'); - } - } else { - throw new \Exception('You must provide an API key'); - } - self::$config = self::$defaults; - foreach ($configMap as $configOption => $configValue) { - if(key_exists($configOption, self::$config)) { - self::$config[$configOption] = $configValue; - } - } - } - - /** - * Retrieves the configuration that was previously setup by the user - * @throws \Exception - */ - public static function getConfig() { - if (self::$config === null) { - throw new \Exception('No configuration has been provided'); - } - return self::$config; - } - - public static function unsetConfig() { - self::$config = NULL; - } + + public $transmission; + + /** + * @dec connection config for making requests. + */ + private $config; + + /** + * @desc Ivory\HttpAdapter\HttpAdapterInterface to make requests through. + */ + public $httpAdapter; + + /** + * @desc Default config values. Passed in values will override these. + */ + private static $apiDefaults = [ + 'host'=>'api.sparkpost.com', + 'protocol'=>'https', + 'port'=>443, + 'strictSSL'=>true, + 'key'=>'', + 'version'=>'v1' + ]; + + /** + * @desc sets up httpAdapter and config + * + * Sets up instances of sub libraries. + * + * @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 function __construct($httpAdapter, $settingsConfig) { + //config needs to be setup before adapter because of default adapter settings + $this->setConfig($settingsConfig); + $this->setHttpAdapter($httpAdapter); + + $this->transmission = new Transmission($this); + } + + + + /** + * Creates an unwrapped api interface for endpoints that aren't yet supported. + * The new resource is attached to this object as well as returned + * @return SparkPost\APIResource - the unwrapped resource + */ + public function setupUnwrapped ($endpoint) { + $this->{$endpoint} = new APIResource($this); + $this->{$endpoint}->endpoint = $endpoint; + + return $this->{$endpoint}; + } + + /** + * @desc Merges passed in headers with default headers for http requests + */ + public function getHttpHeaders() { + $defaultOptions = [ + 'Authorization' => $this->config['key'], + 'Content-Type' => 'application/json', + ]; + + return $defaultOptions; + } + + + /** + * @desc Helper function for getting the configuration for http requests + * @return \Ivory\HttpAdapter\Configuration + */ + private 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 Validates and sets up the httpAdapter + * @param $httpAdapter Ivory\HttpAdapter\HttpAdapterInterface to make requests through. + * @throws \Exception + */ + public function setHttpAdapter($httpAdapter) { + if (!$httpAdapter instanceOf HttpAdapterInterface) { + throw new \Exception('$httpAdapter paramter must be a valid Ivory\HttpAdapter'); + } + + $this->httpAdapter = $httpAdapter; + $this->httpAdapter->setConfiguration($this->getHttpConfig($this->config)); + } + + + /** + * Allows the user to pass in values to override the defaults and set their API key + * @param Array $settingsConfig - Hashmap that contains config values for the SDK to connect to SparkPost + * @throws \Exception + */ + public 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'); + } + + $this->config = self::$apiDefaults; + + // set config, overriding defaults + foreach ($settingsConfig as $configOption => $configValue) { + if(key_exists($configOption, $this->config)) { + $this->config[$configOption] = $configValue; + } + } + } } -?>
\ No newline at end of file +?> diff --git a/lib/SparkPost/Transmission.php b/lib/SparkPost/Transmission.php index 4e54f1d..613ec12 100644 --- a/lib/SparkPost/Transmission.php +++ b/lib/SparkPost/Transmission.php @@ -7,106 +7,102 @@ 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 - * @var array - */ - protected static $parameterMappings = array( - 'campaign'=>'campaign_id', - 'metadata'=>'metadata', - 'substitutionData'=>'substitution_data', - 'description'=>'description', - 'returnPath'=>'return_path', - 'replyTo'=>'content.reply_to', - 'subject'=>'content.subject', - 'from'=>'content.from', - 'html'=>'content.html', - 'text'=>'content.text', - 'rfc822'=>'content.email_rfc822', - 'customHeaders'=>'content.headers', - 'recipients'=>'recipients', - 'recipientList'=>'recipients.list_id', - 'template'=>'content.template_id', - 'trackOpens'=>'options.open_tracking', - '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 - */ - protected static $structure = array( - 'return_path'=>"default@sparkpostmail.com", - 'content'=>array( - '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, - * 'metadata': array, - * 'substitutionData': array, - * 'description': string, - * 'replyTo': string, - * 'subject': string, - * 'from': string, - * 'html': string, - * 'text': string, - * 'rfc822': string, - * 'customHeaders': array, - * 'recipients': array, - * 'recipientList': string, - * 'template': string, - * 'trackOpens': boolean, - * 'trackClicks': boolean, - * 'useDraftTemplate': boolean - * - * @return array API repsonse represented as key-value pairs - */ - public static function send( $transmissionConfig ) { - return self::sendRequest( $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 ); - } - - /** - * @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); - } + + public $endpoint = 'transmissions'; + + /** + * @desc Mapping for values passed into the send method to the values needed for the Transmission API + * @var array + */ + protected static $parameterMappings = [ + 'campaign'=>'campaign_id', + 'metadata'=>'metadata', + 'substitutionData'=>'substitution_data', + 'description'=>'description', + 'returnPath'=>'return_path', + 'replyTo'=>'content.reply_to', + 'subject'=>'content.subject', + 'from'=>'content.from', + 'html'=>'content.html', + 'text'=>'content.text', + 'rfc822'=>'content.email_rfc822', + 'customHeaders'=>'content.headers', + 'recipients'=>'recipients', + 'recipientList'=>'recipients.list_id', + 'template'=>'content.template_id', + 'trackOpens'=>'options.open_tracking', + '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 + */ + protected static $structure = [ + 'return_path'=>'default@sparkpostmail.com', + 'content'=>[ + '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, + * 'metadata': array, + * 'substitutionData': array, + * 'description': string, + * 'replyTo': string, + * 'subject': string, + * 'from': string, + * 'html': string, + * 'text': string, + * 'rfc822': string, + * 'customHeaders': array, + * 'recipients': array, + * 'recipientList': string, + * 'template': string, + * 'trackOpens': boolean, + * 'trackClicks': boolean, + * 'useDraftTemplate': boolean + * + * @return array API repsonse represented as key-value pairs + */ + public function send( $transmissionConfig ) { + return $this->create( $transmissionConfig ); + } + + /** + * @desc Method for retrieving information about all transmissions + * Wrapper method for a cleaner interface + * + * @return array result Set of transmissions + */ + public function all( $campaignID=null, $templateID=null ) { + $options = []; + if( $campaignID !== NULL ) $options['campaign_id'] = $campaignID; + if( $templateID !== NULL ) $options['template_id'] = $templateID; + + return $this->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 function find($transmissionID) { + return $this->get($transmissionID); + } } -?>
\ No newline at end of file +?> diff --git a/phpunit.xml b/phpunit.xml index 3ca0cc3..66d3657 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,37 +1,38 @@ <phpunit - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd" - backupGlobals="true" - backupStaticAttributes="false" - bootstrap="test/unit/bootstrap.php" - cacheTokens="false" - colors="always" - convertErrorsToExceptions="true" - convertNoticesToExceptions="true" - convertWarningsToExceptions="true" - forceCoversAnnotation="false" - mapTestClassNameToCoveredClassName="false" - printerClass="PHPUnit_TextUI_ResultPrinter" - processIsolation="false" - stopOnError="false" - stopOnFailure="false" - stopOnIncomplete="false" - stopOnSkipped="false" - stopOnRisky="false" - testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader" - timeoutForSmallTests="1" - timeoutForMediumTests="10" - timeoutForLargeTests="60" - verbose="false"> + xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' + xsi:noNamespaceSchemaLocation='http://schema.phpunit.de/4.5/phpunit.xsd' + backupGlobals='true' + backupStaticAttributes='false' + bootstrap='test/unit/bootstrap.php' + cacheTokens='false' + colors='always' + convertErrorsToExceptions='true' + convertNoticesToExceptions='true' + convertWarningsToExceptions='true' + forceCoversAnnotation='false' + mapTestClassNameToCoveredClassName='false' + printerClass='PHPUnit_TextUI_ResultPrinter' + processIsolation='false' + stopOnError='false' + stopOnFailure='false' + stopOnIncomplete='false' + stopOnSkipped='false' + stopOnRisky='false' + testSuiteLoaderClass='PHPUnit_Runner_StandardTestSuiteLoader' + timeoutForSmallTests='1' + timeoutForMediumTests='10' + timeoutForLargeTests='60' + verbose='false'> <logging> - <log type="coverage-html" target="test/output/report"/> - <log type="coverage-clover" target="test/output/clover.xml"/> + <log type='coverage-html' target='test/output/report'/> + <log type='coverage-clover' target='test/output/clover.xml'/> </logging> <filter> <blacklist> <directory>./vendor</directory> + <directory>./test</directory> </blacklist> </filter> </phpunit> diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php index fc85fa3..8253b1e 100644 --- a/test/unit/APIResourceTest.php +++ b/test/unit/APIResourceTest.php @@ -1,144 +1,135 @@ <?php namespace SparkPost\Test; - use SparkPost\APIResource; -use SparkPost\SparkPost; -use Guzzle\Plugin\Mock\MockPlugin; -use Guzzle\Http\Message\Response; - +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; 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 - */ - private static function getMethod($name) { - $class = new \ReflectionClass('\SparkPost\APIResource'); - $method = $class->getMethod($name); - $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 - 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')); - } - + + private static $utils; + private $adapterMock; + private $resource; + + private function getExceptionMock($statusCode) { + $exception = new \Ivory\HttpAdapter\HttpAdapterException(); + $response = Mockery::mock('Ivory\HttpAdapter\Message\ResponseInterface'); + $response->shouldReceive('getStatusCode')->andReturn($statusCode); + $exception->setResponse($response); + return $exception; + } + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + $this->sparkPostMock = Mockery::mock('SparkPost\SparkPost', function($mock) { + $mock->shouldReceive('getHttpHeaders')->andReturn([]); + }); + $this->sparkPostMock->httpAdapter = Mockery::mock(); + $this->resource = new APIResource($this->sparkPostMock); + self::$utils = new ClassUtils($this->resource); + self::$utils->setProperty($this->resource, 'sparkpost', $this->sparkPostMock); + } + + public function tearDown() + { + Mockery::close(); + } + + public function testConstructorSetsUpSparkPostObject() { + $this->sparkPostMock->newProp = 'new value'; + $this->assertEquals($this->sparkPostMock, self::$utils->getProperty($this->resource, 'sparkpost')); + } + + public function testCreate() { + $testInput = ['test'=>'body']; + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with(Mockery::type('string'), 'POST', Mockery::type('array'), json_encode($testInput))-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + + $this->assertEquals($testBody, $this->resource->create($testInput)); + } + + public function testUpdate() { + $testInput = ['test'=>'body']; + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'PUT', Mockery::type('array'), json_encode($testInput))-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->update('test', $testInput)); + } + + public function testGet() { + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->get('test')); + } + + public function testDelete() { + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'DELETE', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(''); + + $this->assertEquals(null, $this->resource->delete('test')); + } + + public function testAdapter404Exception() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow($this->getExceptionMock(404)); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/.*resource does not exist.*/', $e->getMessage()); + } + } + + public function testAdapter4XXException() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow($this->getExceptionMock(400)); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/Received bad response.*/', $e->getMessage()); + } + } + + public function testAdapter5XXException() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow(new \Exception('Something went wrong.')); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/Unable to contact.*API.*/', $e->getMessage()); + } + } + } diff --git a/test/unit/SendGridCompatibiility/EmailTest.php b/test/unit/SendGridCompatibiility/EmailTest.php index c60801c..2b86d7a 100644 --- a/test/unit/SendGridCompatibiility/EmailTest.php +++ b/test/unit/SendGridCompatibiility/EmailTest.php @@ -2,160 +2,160 @@ use SparkPost\SendGridCompatibility\Email; class SendGridCompatibilityEmailTest extends \PHPUnit_Framework_TestCase { - - private $email; - - public function setup() { - $this->email = new Email(); - } - - public function testConstruct() { - $email = new Email(); - - $this->assertInstanceOf('SparkPost\SendGridCompatibility\Email', $email); - $this->assertInternalType('array', $email->model); - } - - public function testAddTo() { - $fakeEmail = 'joe.schmoe@test.com'; - $this->email->addTo($fakeEmail); - - $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail))), $this->email->model['recipients']); - } - - public function testAddToWithName() { - $fakeEmail = 'joe.schmoe@test.com'; - $fakeName = 'Joe Schmoe'; - $this->email->addTo($fakeEmail, $fakeName); - - $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail, 'name'=>$fakeName))), $this->email->model['recipients']); - } - - public function testSetTos() { - $tos = array(); - array_push($tos, array('address'=>array('email'=>'joe.schmoe@test.com', 'name'=>'Joe Schmoe'))); - array_push($tos, array('address'=>array('email'=>'jill.schmoe@test.com', 'name'=>'Jill Schmoe'))); - $this->email->setTos($tos); - - $this->assertEquals($tos, $this->email->model['recipients']); - } - - public function testSetFrom() { - $this->email->setFrom('test@email.com'); - - $this->assertEquals(array('email'=>'test@email.com'), $this->email->model['from']); - } - - - public function testSetFromName() { - $this->email->setFrom('test@email.com'); - $this->email->setFromName('Test Bot'); - - $this->assertEquals(array('email'=>'test@email.com', 'name'=>'Test Bot'), $this->email->model['from']); - } - - /** - * @desc Tests that setting the fromName prior to setting the From field throws an exception - * @expectedException Exception - * @expectedExceptionMessage Must set "From" prior to setting "From Name". - */ - public function testSetFromNameWithoutAddress() { - $this->email->setFromName('Test Bot'); - } - - public function testSetReplyto() { - $this->email->setReplyTo('test@email.com'); - - $this->assertEquals('test@email.com', $this->email->model['replyTo']); - } - /** - * @expectedException Exception - * @expectedExceptionMessage Adding bcc recipients is not yet supported, try adding them as a "to" address - */ - public function testAddBcc() { - $this->email->addBcc('test@email.com'); - } - - public function testSetSubject() { - $this->email->setSubject('Awesome Subject'); - - $this->assertEquals('Awesome Subject', $this->email->model['subject']); - } - - public function testSetText() { - $value = 'This is some plain/text'; - $this->email->setText($value); - - $this->assertEquals($value, $this->email->model['text']); - } - - public function testSetHtml() { - $value = '<html><body><p>This is some html</p></body></html>'; - $this->email->setHtml($value); - - $this->assertEquals($value, $this->email->model['html']); - } - - /** - * @desc test that adding a category throws an exception since we don't support tags at transmission level yet - * @expectedException Exception - * @expectedExceptionMessage Adding categories is not yet supported - */ - public function testAddCategory() { - $this->email->addCategory(''); - } - - /** - * @desc Tests that setting an attachment throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Adding attachments is not yet supported - */ - public function testAddAttachment() { - $this->email->addAttachment('blah'); - } - - public function testAddSubstitution() { - $this->email->addSubstitution('item', 'baseball bat'); - - $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); - } - - public function testAddSection() { - $this->email->addSection('item', 'baseball bat'); - - $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); - } - - /** - * @desc Tests that setting an attachment throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Adding Unique Arguments is not yet supported - */ - public function testAddUniqueArguement() { - $this->email->addUniqueArg('blah', 'someblah'); - } - - - /** - * @desc Tests that setting an unique argument throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Setting Unique Arguments is not yet supported - */ - public function testSetUniqueArgs() { - $this->email->setUniqueArgs(array('blah', 'andBlah')); - } - - - public function testAddHeader() { - $value = 'My Header'; - $this->email->addHeader('X-header', $value); - - $this->assertEquals(array('X-header'=>$value), $this->email->model['customHeaders']); - } - - public function testToSparkPostTransmission() { - $this->assertInternalType('array', $this->email->toSparkPostTransmission()); - } + + private $email; + + public function setup() { + $this->email = new Email(); + } + + public function testConstruct() { + $email = new Email(); + + $this->assertInstanceOf('SparkPost\SendGridCompatibility\Email', $email); + $this->assertInternalType('array', $email->model); + } + + public function testAddTo() { + $fakeEmail = 'joe.schmoe@test.com'; + $this->email->addTo($fakeEmail); + + $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail))), $this->email->model['recipients']); + } + + public function testAddToWithName() { + $fakeEmail = 'joe.schmoe@test.com'; + $fakeName = 'Joe Schmoe'; + $this->email->addTo($fakeEmail, $fakeName); + + $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail, 'name'=>$fakeName))), $this->email->model['recipients']); + } + + public function testSetTos() { + $tos = array(); + array_push($tos, array('address'=>array('email'=>'joe.schmoe@test.com', 'name'=>'Joe Schmoe'))); + array_push($tos, array('address'=>array('email'=>'jill.schmoe@test.com', 'name'=>'Jill Schmoe'))); + $this->email->setTos($tos); + + $this->assertEquals($tos, $this->email->model['recipients']); + } + + public function testSetFrom() { + $this->email->setFrom('test@email.com'); + + $this->assertEquals(array('email'=>'test@email.com'), $this->email->model['from']); + } + + + public function testSetFromName() { + $this->email->setFrom('test@email.com'); + $this->email->setFromName('Test Bot'); + + $this->assertEquals(array('email'=>'test@email.com', 'name'=>'Test Bot'), $this->email->model['from']); + } + + /** + * @desc Tests that setting the fromName prior to setting the From field throws an exception + * @expectedException Exception + * @expectedExceptionMessage Must set 'From' prior to setting 'From Name'. + */ + public function testSetFromNameWithoutAddress() { + $this->email->setFromName('Test Bot'); + } + + public function testSetReplyto() { + $this->email->setReplyTo('test@email.com'); + + $this->assertEquals('test@email.com', $this->email->model['replyTo']); + } + /** + * @expectedException Exception + * @expectedExceptionMessage Adding bcc recipients is not yet supported, try adding them as a 'to' address + */ + public function testAddBcc() { + $this->email->addBcc('test@email.com'); + } + + public function testSetSubject() { + $this->email->setSubject('Awesome Subject'); + + $this->assertEquals('Awesome Subject', $this->email->model['subject']); + } + + public function testSetText() { + $value = 'This is some plain/text'; + $this->email->setText($value); + + $this->assertEquals($value, $this->email->model['text']); + } + + public function testSetHtml() { + $value = '<html><body><p>This is some html</p></body></html>'; + $this->email->setHtml($value); + + $this->assertEquals($value, $this->email->model['html']); + } + + /** + * @desc test that adding a category throws an exception since we don't support tags at transmission level yet + * @expectedException Exception + * @expectedExceptionMessage Adding categories is not yet supported + */ + public function testAddCategory() { + $this->email->addCategory(''); + } + + /** + * @desc Tests that setting an attachment throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Adding attachments is not yet supported + */ + public function testAddAttachment() { + $this->email->addAttachment('blah'); + } + + public function testAddSubstitution() { + $this->email->addSubstitution('item', 'baseball bat'); + + $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); + } + + public function testAddSection() { + $this->email->addSection('item', 'baseball bat'); + + $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); + } + + /** + * @desc Tests that setting an attachment throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Adding Unique Arguments is not yet supported + */ + public function testAddUniqueArguement() { + $this->email->addUniqueArg('blah', 'someblah'); + } + + + /** + * @desc Tests that setting an unique argument throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Setting Unique Arguments is not yet supported + */ + public function testSetUniqueArgs() { + $this->email->setUniqueArgs(array('blah', 'andBlah')); + } + + + public function testAddHeader() { + $value = 'My Header'; + $this->email->addHeader('X-header', $value); + + $this->assertEquals(array('X-header'=>$value), $this->email->model['customHeaders']); + } + + public function testToSparkPostTransmission() { + $this->assertInternalType('array', $this->email->toSparkPostTransmission()); + } } -?>
\ No newline at end of file +?> diff --git a/test/unit/SparkPostTest.php b/test/unit/SparkPostTest.php index f40461d..101784a 100644 --- a/test/unit/SparkPostTest.php +++ b/test/unit/SparkPostTest.php @@ -2,60 +2,76 @@ namespace SparkPost\Test; use SparkPost\SparkPost; +use Ivory\HttpAdapter\CurlHttpAdapter; +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; class SparkPostTest extends \PHPUnit_Framework_TestCase { - - /** - * @desc Ensures that the configuration class is not instantiable. - */ - public function testConstructorCannotBeCalled() { - $class = new \ReflectionClass('\SparkPost\SparkPost'); - $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. - * @expectedException Exception - * @expectedExceptionMessage No configuration has been provided - */ - public function testGetConfigEmptyException() { - 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')); - } - - /** - * @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'=>'')); - } - - /** - * @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')); - - $testConfig = SparkPost::getConfig(); - $this->assertEquals('lala', $testConfig['key']); - $this->assertEquals('v8', $testConfig['version']); - $this->assertEquals(1024, $testConfig['port']); - $this->assertNotContains('someOtherValue', array_keys($testConfig)); - $this->assertEquals('https', $testConfig['protocol']); - $this->assertEquals('api.sparkpost.com', $testConfig['host']); - $this->assertEquals(true, $testConfig['strictSSL']); - } + + private static $utils; + private $adapterMock; + private $resource; + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + //setup mock for the adapter + $this->adapterMock = Mockery::mock('Ivory\HttpAdapter\HttpAdapterInterface', function($mock) { + $mock->shouldReceive('setConfiguration'); + $mock->shouldReceive('getConfiguration->getUserAgent')->andReturn('php-sparkpost/0.2.0'); + }); + + $this->resource = new SparkPost($this->adapterMock, ['key'=>'a key']); + self::$utils = new ClassUtils($this->resource); + self::$utils->setProperty($this->resource, 'httpAdapter', $this->adapterMock); + } + + public function tearDown(){ + Mockery::close(); + } + + /** + * @desc Ensures that the configuration class is not instantiable. + */ + public function testConstructorSetsUpTransmissions() { + $sparky = new SparkPost(new CurlHttpAdapter(), ['key'=>'a key']); + $this->assertEquals('SparkPost\Transmission', get_class($sparky->transmission)); + $adapter = self::$utils->getProperty($this->resource, 'httpAdapter'); + $this->assertRegExp('/php-sparkpost.*/', $adapter->getConfiguration()->getUserAgent()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /valid Ivory\\HttpAdapter/ + */ + public function testSetBadHTTPAdapter() { + $this->resource->setHttpAdapter(new \stdClass()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /API key/ + */ + public function testSetBadConfig() { + $this->resource->setConfig(['not'=>'a key']); + } + + + public function testGetHeaders() { + $results = $this->resource->getHttpHeaders(); + $this->assertEquals('a key', $results['Authorization']); + $this->assertEquals('application/json', $results['Content-Type']); + } + + public function testSetUnwrapped() { + $results = $this->resource->setupUnwrapped('ASweetEndpoint'); + $this->assertEquals($this->resource->ASweetEndpoint, $results); + $this->assertInstanceOf('SparkPost\APIResource', $results); + $this->assertEquals('ASweetEndpoint', $results->endpoint); + } + } -?>
\ No newline at end of file +?> diff --git a/test/unit/TestUtils/ClassUtils.php b/test/unit/TestUtils/ClassUtils.php new file mode 100644 index 0000000..26d264c --- /dev/null +++ b/test/unit/TestUtils/ClassUtils.php @@ -0,0 +1,56 @@ +<?php +namespace SparkPost\Test\TestUtils; + + +class ClassUtils { + + private $class; + + public function __construct($fqClassName) { + $this->class = new \ReflectionClass($fqClassName); + } + + /** + * Allows access to private methods + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @return ReflectionMethod + */ + public function getMethod($method) { + $method = $this->class->getMethod($name); + $method->setAccessible(true); + return $method; + } + + /** + * Allows access to private properties in the Transmission class + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @param {*} + * @return ReflectionMethod + */ + public function getProperty($instance, $property) { + $prop = $this->class->getProperty($property); + $prop->setAccessible(true); + return $prop->getValue($instance); + } + /** + * Allows access to private properties in the Transmission class + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @param {*} + * @return ReflectionMethod + */ + public function setProperty($instance, $property, $value) { + $prop = $this->class->getProperty($property); + $prop->setAccessible(true); + $prop->setValue($instance, $value); + } +} +?> diff --git a/test/unit/TransmissionTest.php b/test/unit/TransmissionTest.php index ca30b4a..d262ee0 100644 --- a/test/unit/TransmissionTest.php +++ b/test/unit/TransmissionTest.php @@ -1,144 +1,86 @@ <?php namespace SparkPost\Test; - use SparkPost\Transmission; -use SparkPost\SparkPost; -use Guzzle\Plugin\Mock\MockPlugin; -use Guzzle\Http\Message\Response; - +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; class TransmissionTest extends \PHPUnit_Framework_TestCase { - - private $client = null; - - /** - * Allows access to private methods in the Transmission class - * - * This is needed to mock the GuzzleHttp\Client responses - * - * @param string $name - * @return ReflectionMethod - */ - private static function getMethod($name) { - $class = new \ReflectionClass('\SparkPost\Transmission'); - $method = $class->getMethod($name); - $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 - } - - /** - * @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 testAllWithGoodResponse() { - $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'))), Transmission::all()); - } - - /** - * @desc tests happy path - */ - public function testFindWithGoodResponse() { - $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'))), Transmission::find('someId')); - } - - /** - * @desc tests 404 bad response - * @expectedException Exception - * @expectedExceptionMessage The specified resource does not exist - */ - public function testFindWith404Response() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(404, array())); - $this->client->addSubscriber($mock); - Transmission::find('someId'); - } - - /** - * @desc tests unknown bad response - * @expectedException Exception - * @expectedExceptionMessage Received bad response from Transmissions API: 400 - */ - public function testFindWithOtherBadResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array())); - $this->client->addSubscriber($mock); - Transmission::find('someId'); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact Transmissions API:.* / - */ - public function testFindForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - Transmission::find('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, Transmission::send(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); - Transmission::send(array('text'=>'awesome email')); - } - - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact Transmissions API:.* / - */ - public function testSendForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - Transmission::send(array('text'=>'awesome email')); - } - + + private static $utils; + private $sparkPostMock; + private $resource; + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + $this->sparkPostMock = Mockery::mock('SparkPost\SparkPost', function($mock) { + $mock->shouldReceive('getHttpHeaders')->andReturn([]); + }); + $this->sparkPostMock->httpAdapter = Mockery::mock(); + $this->resource = new Transmission($this->sparkPostMock); + self::$utils = new ClassUtils($this->resource); + } + + public function tearDown(){ + Mockery::close(); + } + + public function testSend() { + $responseMock = Mockery::mock(); + $body = ['text'=>'awesomesauce', 'content'=>['subject'=>'awesomeness']]; + $responseBody = ['results'=>'yay']; + + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions/', 'POST', Mockery::type('array'), Mockery::type('string'))-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->send($body)); + } + + public function testAllWithFilter() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*transmissions.*?campaign_id=campaign&template_id=template/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->all('campaign', 'template')); + } + + public function testAllWithOutFilter() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->all()); + } + + public function testFind() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions.*\/test/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->find('test')); + } + } -?>
\ No newline at end of file +?> diff --git a/test/unit/bootstrap.php b/test/unit/bootstrap.php index 7e73606..0b851be 100644 --- a/test/unit/bootstrap.php +++ b/test/unit/bootstrap.php @@ -1,3 +1,3 @@ <?php - require_once dirname(__FILE__).'/../../vendor/autoload.php'; -?>
\ No newline at end of file + require_once dirname(__FILE__).'/../../vendor/autoload.php'; +?> |