summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--README.md59
-rw-r--r--composer.json14
-rw-r--r--composer.lock552
-rw-r--r--examples/transmission/get_all_transmissions.php8
-rw-r--r--examples/transmission/get_transmission.php8
-rw-r--r--examples/transmission/rfc822.php26
-rw-r--r--examples/transmission/send_transmission_all_fields.php39
-rw-r--r--examples/transmission/simple_send.php32
-rw-r--r--examples/transmission/stored_recipients_inline_content.php12
-rw-r--r--examples/transmission/stored_template_send.php28
-rw-r--r--examples/unwrapped/create_template.php23
-rw-r--r--lib/SendGridCompatibility/SendGrid.php16
-rw-r--r--lib/SparkPost/APIResource.php236
-rw-r--r--lib/SparkPost/SparkPost.php185
-rw-r--r--lib/SparkPost/Transmission.php64
-rw-r--r--test/unit/APIResourceTest.php255
-rw-r--r--test/unit/SparkPostTest.php122
-rw-r--r--test/unit/TestUtils/ClassUtils.php56
-rw-r--r--test/unit/TransmissionTest.php218
-rw-r--r--test/unit/bootstrap.php2
21 files changed, 1230 insertions, 727 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:
diff --git a/README.md b/README.md
index 4801134..9005e01 100644
--- a/README.md
+++ b/README.md
@@ -24,25 +24,54 @@ require 'vendor/autoload.php';
use SparkPost\SparkPost;
```
+## 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:
+```
+use SparkPost\SparkPost;
+use GuzzleHttp\Client;
+use Ivory\HttpAdapter\Guzzle6HttpAdapter;
+
+$httpAdapter = new Guzzle6HttpAdapter(new Client());
+$sparky = new SparkPost($httpAdapter, ['key'=>'YOUR API KEY']);
+```
+
## Getting Started: Your First Mailing
```
-SparkPost::setConfig(["key"=>"YOUR API KEY"]);
+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'=>array('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);
}
```
diff --git a/composer.json b/composer.json
index d3ea663..a100cde 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/"
+ "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/transmission/get_all_transmissions.php b/examples/transmission/get_all_transmissions.php
index fb62ec7..7baf4f1 100644
--- a/examples/transmission/get_all_transmissions.php
+++ b/examples/transmission/get_all_transmissions.php
@@ -7,12 +7,14 @@ $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();
+ $results = $sparky->transmission->all();
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/get_transmission.php b/examples/transmission/get_transmission.php
index b4781d7..1e749b9 100644
--- a/examples/transmission/get_transmission.php
+++ b/examples/transmission/get_transmission.php
@@ -7,12 +7,14 @@ $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');
+ $results = $sparky->transmission->find('Your Transmission ID');
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/rfc822.php b/examples/transmission/rfc822.php
index 8163693..b11b34f 100644
--- a/examples/transmission/rfc822.php
+++ b/examples/transmission/rfc822.php
@@ -7,21 +7,23 @@ $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"
- ));
+ $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();
diff --git a/examples/transmission/send_transmission_all_fields.php b/examples/transmission/send_transmission_all_fields.php
index 28edbcc..044dcc2 100644
--- a/examples/transmission/send_transmission_all_fields.php
+++ b/examples/transmission/send_transmission_all_fields.php
@@ -7,39 +7,42 @@ $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(
+ $results = $sparky->transmission->send([
"campaign"=>"my-campaign",
- "metadata"=>array(
+ "metadata"=>[
"sample_campaign"=>true,
"type"=>"these are custom fields"
- ),
- "substitutionData"=>array(
+ ],
+ "substitutionData"=>[
"name"=>"Test Name"
- ),
+ ],
"description"=>"my description",
"replyTo"=>"reply@test.com",
- "customHeaders"=>array(
+ "customHeaders"=>[
"X-Custom-Header"=>"Sample Custom Header"
- ),
+ ],
"trackOpens"=>false,
"trackClicks"=>false,
- "from"=>"From Envelope <from@example.com>",
+ "from"=>"From Envelope <from@sparkpostbox.com>",
"html"=>"<p>Hello World! Your name is: {{name}}</p>",
"text"=>"Hello World!",
"subject"=>"Example Email: {{name}}",
- "recipients"=>array(
- array(
- "address"=>array(
- "email"=>"john.doe@sample.com"
- )
- )
- )
- ));
+ "recipients"=>[
+ [
+ "address"=>[
+ "email"=>"john.doe@example.com"
+ ]
+ ]
+ ]
+ ]);
+
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/simple_send.php b/examples/transmission/simple_send.php
index eafc176..6dc3719 100644
--- a/examples/transmission/simple_send.php
+++ b/examples/transmission/simple_send.php
@@ -7,24 +7,26 @@ $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"
- )
- )
- )
- ));
+ $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();
diff --git a/examples/transmission/stored_recipients_inline_content.php b/examples/transmission/stored_recipients_inline_content.php
index a2dd8aa..3e53507 100644
--- a/examples/transmission/stored_recipients_inline_content.php
+++ b/examples/transmission/stored_recipients_inline_content.php
@@ -7,20 +7,22 @@ $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(
+ $results = $sparky->transmission->send([
"campaign"=>"my-campaign",
- "from"=>"From Envelope <from@example.com>",
+ "from"=>"From Envelope <from@sparkpostbox.com>",
"html"=>"<p>Hello World! Your name is: {{name}}</p>",
"text"=>"Hello World!",
"subject"=>"Example Email: {{name}}",
"recipientList"=>'Example List'
- ));
+ ]);
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
diff --git a/examples/transmission/stored_template_send.php b/examples/transmission/stored_template_send.php
index 52dbb27..936d292 100644
--- a/examples/transmission/stored_template_send.php
+++ b/examples/transmission/stored_template_send.php
@@ -7,22 +7,24 @@ $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"
- ));
+ $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();
diff --git a/examples/unwrapped/create_template.php b/examples/unwrapped/create_template.php
index 0e24fd6..e28f158 100644
--- a/examples/unwrapped/create_template.php
+++ b/examples/unwrapped/create_template.php
@@ -7,21 +7,26 @@ $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';
+ $sparky->setupUnwrapped('templates');
- $templateConfig = array(
+ $templateConfig = [
'name' => 'Summer Sale!',
- 'content.from' => 'marketing@bounces.company.example',
- 'content.subject' => 'Summer deals',
- 'content.html' => '<b>Check out these deals!</b>',
- );
- $results = APIResource::sendRequest($templateConfig);
+ 'id'=>'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();
diff --git a/lib/SendGridCompatibility/SendGrid.php b/lib/SendGridCompatibility/SendGrid.php
index a85337a..b92457b 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) {
+ 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);
}
- Configuration::setConfig($opts);
+
+ $this->sparky = new SparkPost($httpAdapter, $opts);
}
-
+
public function send(Email $email) {
- Trasmission::send($email->toSparkPostTransmission());
+ $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..4c4cf08 100644
--- a/lib/SparkPost/APIResource.php
+++ b/lib/SparkPost/APIResource.php
@@ -1,68 +1,54 @@
<?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.
+ * This is public to provide an interface
+ *
* @var string
*/
- public static $endpoint;
-
- /**
- * @desc singleton holder to create a guzzle http client
- * @var \GuzzleHttp\Client
- */
- protected static $request;
-
+ public $endpoint;
+
/**
* @desc Mapping for values passed into the send method to the values needed for the respective API
* @var array
*/
- protected static $parameterMappings = 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 = array();
-
- /**
- * @desc Ensure that this class cannot be instansiated
- */
- private function __construct() {}
+ protected static $structure = [];
+
+ /**
+ * @desc SparkPost reference for httpAdapters and configs
+ */
+ protected $sparkpost;
/**
- * @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
+ * @desc Initializes config and httpAdapter for use later.
+ * @param $sparkpost SparkPost\SparkPost provides api configuration information
*/
- protected static function getBaseUrl($config) {
- $baseUrl = '/api/' . $config['version'] . '/' . static::$endpoint;
- return $config['protocol'] . '://' . $config['host'] . ($config['port'] ? ':' . $config['port'] : '') . $baseUrl;
- }
-
-
+ 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 static function setMappedValue (&$model, $mapKey, $value) {
+ protected function setMappedValue (&$model, $mapKey, $value) {
//get mapping
if( empty(static::$parameterMappings) ) {
// if parameterMappings is empty we can assume that no wrapper is defined
@@ -74,7 +60,7 @@ class APIResource {
} else {
return;
}
-
+
$path = explode('.', $mapPath);
$temp = &$model;
foreach( $path as $key ) {
@@ -84,79 +70,100 @@ class APIResource {
$temp = &$temp[$key];
}
$temp = $value;
-
+
}
-
- protected static function buildRequestModel( $requestConfig, $model=array() ) {
- foreach($requestConfig as $key=>$value) {
- self::setMappedValue($model, $key, $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 Method for issuing POST requests
- *
- * @return array API repsonse represented as key-value pairs
+ * @desc posts to the api with a supplied body
+ * @param body post body for the request
+ * @return array Result of the request
*/
- public static function sendRequest( $requestConfig ) {
- $hostConfig = SparkPost::getConfig();
- $request = self::getHttpClient();
-
- //create model from $transmissionConfig
- $model = static::$structure;
- $requestModel = self::buildRequestModel( $requestConfig, $model );
-
- //send the request
- try {
- $response = $request->post(
- self::getBaseUrl($hostConfig),
- array('authorization' => $hostConfig['key']),
- json_encode($requestModel),
- array("verify"=>$hostConfig['strictSSL'])
- )->send();
-
- return $response->json();
- }
- /*
- * Handles 4XX responses
- */
- catch (ClientErrorResponseException $exception) {
- $response = $exception->getResponse();
- $responseArray = $response->json();
- throw new \Exception(json_encode($responseArray['errors']));
- }
- /*
- * Handles 5XX Errors, Configuration Errors, and a catch all for other errors
- */
- catch (\Exception $exception) {
- throw new \Exception("Unable to contact ".ucfirst(static::$endpoint)." API: ". $exception->getMessage());
- }
+ public 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 set of transmissions found
+ * @return array Result of the request
*/
- public static function fetchResource( $resourcePath=null, $options=array() ) {
- return self::callResource( 'get', $resourcePath, $options );
+ 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 set of transmissions found
+ * @return array Result of the request
*/
- public static function deleteResource( $resourcePath=null, $options=array() ) {
- return self::callResource( 'delete', $resourcePath, $options );
+ 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
*
@@ -170,47 +177,38 @@ class APIResource {
* @param array $options (optional) query string parameters
* @return array Result set of action performed on resource
*/
- private static function callResource( $action, $resourcePath=null, $options=array() ) {
-
- if( !in_array( $action, array('get', 'delete') ) ) throw new \Exception('Invalid resource action');
-
- //build the url
- $hostConfig = SparkPost::getConfig();
- $url = self::getBaseUrl($hostConfig);
- if (!is_null($resourcePath)){
- $url .= '/'.$resourcePath;
- }
-
- // untested:
- if( !empty($options) ) {
- $queryString = http_build_query($options);
- $url .= '?'.$queryString;
+ private function callResource( $action, $resourcePath=null, $options=[] ) {
+ $action = strtoupper($action); // normalize
+
+ if( !in_array($action, ['POST', 'PUT', 'GET', 'DELETE'])) {
+ throw new \Exception('Invalid resource action');
}
-
- $request = self::getHttpClient();
-
+
+ $url = $this->buildUrl($resourcePath, $options);
+ $body = $this->buildBody($options);
+
//make request
try {
- $response = $request->{$action}($url, array('authorization' => $hostConfig['key']), array("verify"=>$hostConfig['strictSSL']))->send();
- return $response->json();
+ $response = $this->sparkpost->httpAdapter->send($url, $action, $this->sparkpost->getHttpHeaders(), $body);
+ return json_decode($response->getBody()->getContents(), true);
}
/*
* Handles 4XX responses
- */
- catch (ClientErrorResponseException $exception) {
- $response = $exception->getResponse();
- $statusCode = $response->getStatusCode();
+ */
+ catch (HttpAdapterException $exception) {
+ $response = $exception->getResponse();
+ $statusCode = $response->getStatusCode();
if($statusCode === 404) {
throw new \Exception("The specified resource does not exist", 404);
}
- throw new \Exception("Received bad response from ".ucfirst(static::$endpoint)." API: ". $statusCode );
+ 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(static::$endpoint)." API: ". $exception->getMessage());
+ 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..83200c0 100644
--- a/lib/SparkPost/SparkPost.php
+++ b/lib/SparkPost/SparkPost.php
@@ -1,60 +1,137 @@
<?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
+ * @return Array - headers to be set on http requests
+ */
+ public function getHttpHeaders(Array $headers = null) {
+ $defaultOptions = [
+ 'Authorization' => $this->config['key'],
+ 'Content-Type' => 'application/json',
+ ];
+
+ // Merge passed in headers with defaults
+ if (!is_null($headers)) {
+ foreach ($headers as $header => $value) {
+ $defaultOptions[$header] = $value;
+ }
+ }
+ return $defaultOptions;
+ }
+
+
+ /**
+ * @desc Helper function for getting the configuration for http requests
+ * @return \Ivory\HttpAdapter\Configuration
+ */
+ 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..3b3c056 100644
--- a/lib/SparkPost/Transmission.php
+++ b/lib/SparkPost/Transmission.php
@@ -7,14 +7,14 @@ use Guzzle\Http\Exception\ClientErrorResponseException;
* @desc SDK interface for managing transmissions
*/
class Transmission extends APIResource {
-
- public static $endpoint = 'transmissions';
-
+
+ public $endpoint = 'transmissions';
+
/**
- * @desc Mapping for values passed into the send method to the values needed for the Transmission API
+ * @desc Mapping for values passed into the send method to the values needed for the Transmission API
* @var array
*/
- protected static $parameterMappings = array(
+ protected static $parameterMappings = [
'campaign'=>'campaign_id',
'metadata'=>'metadata',
'substitutionData'=>'substitution_data',
@@ -33,29 +33,29 @@ class Transmission extends APIResource {
'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(
+ protected static $structure = [
'return_path'=>"default@sparkpostmail.com",
- 'content'=>array(
- 'html'=>null,
+ '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,
+ * been populated by the user through configuration. Acceptable
+ * configuration values are:
+ * 'campaign': string,
* 'metadata': array,
* 'substitutionData': array,
* 'description': string,
@@ -71,42 +71,38 @@ class Transmission extends APIResource {
* 'template': string,
* 'trackOpens': boolean,
* 'trackClicks': boolean,
- * 'useDraftTemplate': boolean
+ * 'useDraftTemplate': boolean
*
* @return array API repsonse represented as key-value pairs
*/
- public static function send( $transmissionConfig ) {
- return self::sendRequest( $transmissionConfig );
+ 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 static function all( $campaignID=null, $templateID=null ) {
- $options = array();
+ public function all( $campaignID=null, $templateID=null ) {
+ $options = [];
if( $campaignID !== NULL ) $options['campaign_id'] = $campaignID;
if( $templateID !== NULL ) $options['template_id'] = $templateID;
-
- return self::fetchResource( null, $options );
+
+ 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 static function find($transmissionID) {
- return self::fetchResource($transmissionID);
- }
-
- public static function delete( $transmissionID ) {
- return self::deleteResource($transmissionID);
+ public function find($transmissionID) {
+ return $this->get($transmissionID);
}
}
-?> \ No newline at end of file
+?>
diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php
index fc85fa3..132d6e2 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;
- }
-
+
+ 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() {
- 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'));
- }
-
+ $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/SparkPostTest.php b/test/unit/SparkPostTest.php
index f40461d..aeda7d7 100644
--- a/test/unit/SparkPostTest.php
+++ b/test/unit/SparkPostTest.php
@@ -2,60 +2,82 @@
namespace SparkPost\Test;
use SparkPost\SparkPost;
+use Ivory\HttpAdapter\CurlHttpAdapter;
+use SparkPost\Test\TestUtils\ClassUtils;
+use \Mockery;
class SparkPostTest extends \PHPUnit_Framework_TestCase {
-
+
+ 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 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']);
+ 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 testGetHeadersOverride() {
+ $results = $this->resource->getHttpHeaders(['Content-Type'=>'application/xml']);
+ $this->assertEquals('application/xml', $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..f09db7d 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..835369b 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
+?>