diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1492202 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9583bff..1bc3c40 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,14 +50,15 @@ Follow the instructions at [xdebug.org](http://xdebug.org/wizard.php) - Provide documentation for any newly added code. - Provide tests for any newly added code. -- Follow [PSR-1](http://www.php-fig.org/psr/psr-1/) +- Follow [PSR-2](http://www.php-fig.org/psr/psr-2/) (_will be auto-enforced by php-cs-fixer in a later step_) 1. Create a new branch named after the issue you’ll be fixing (include the issue number as the branch name, example: Issue in GH is #8 then the branch name should be ISSUE-8) -2. Write corresponding tests and code (only what is needed to satisfy the issue and tests please) +1. Write corresponding tests and code (only what is needed to satisfy the issue and tests please) * Include your tests in the 'test' directory in an appropriate test file * Write code to satisfy the tests -3. Ensure automated tests pass -4. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to [AUTHORS](https://github.com/SparkPost/php-sparkpost/blob/master/AUTHORS.md). +1. Ensure automated tests pass +1. Run `composer run-script fix-style` to enforce PSR-2 style +1. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to [AUTHORS](https://github.com/SparkPost/php-sparkpost/blob/master/AUTHORS.md). ### Testing diff --git a/composer.json b/composer.json index be447ce..4ad389e 100644 --- a/composer.json +++ b/composer.json @@ -1,33 +1,35 @@ { - "name": "sparkpost/php-sparkpost", - "description": "Client library for interfacing with the SparkPost API.", - "license": "Apache 2.0", - "authors": [ - { - "name": "SparkPost" - } - ], - "minimum-stability": "stable", - "scripts": { - "post-install-cmd": "if [ ! -f 'examples/example-config.json' ]; then echo '{\n\t\"api-key\":\"Your API Key\"\n}' >> examples/example-config.json; fi", - "post-update-cmd": "if [ ! -f 'examples/example-config.json' ]; then echo '{\n\t\"api-key\":\"Your API Key\"\n}' >> examples/example-config.json; fi", - "test": "phpunit ./test/unit/" - }, - "require": { - "php": ">=5.5.0", - "egeloen/http-adapter": "*" - }, - "require-dev": { - "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\\Test\\TestUtils\\": "test/unit/TestUtils/" - } + "name": "sparkpost/php-sparkpost", + "description": "Client library for interfacing with the SparkPost API.", + "license": "Apache 2.0", + "authors": [ + { + "name": "SparkPost" } + ], + "minimum-stability": "stable", + "scripts": { + "post-install-cmd": "if [ ! -f 'examples/example-config.json' ]; then echo '{\n\t\"api-key\":\"Your API Key\"\n}' >> examples/example-config.json; fi", + "post-update-cmd": "if [ ! -f 'examples/example-config.json' ]; then echo '{\n\t\"api-key\":\"Your API Key\"\n}' >> examples/example-config.json; fi", + "test": "phpunit ./test/unit/", + "fix-style": "php-cs-fixer fix ." + }, + "require": { + "php": ">=5.5.0", + "egeloen/http-adapter": "*" + }, + "require-dev": { + "phpunit/phpunit": "4.3.*", + "guzzlehttp/guzzle": "6.*", + "mockery/mockery": "^0.9.4", + "satooshi/php-coveralls": "dev-master", + "fabpot/php-cs-fixer": "^1.11" + }, + "autoload": { + "psr-4": { + "SparkPost\\": "lib/SparkPost/", + "SparkPost\\SendGridCompatibility\\": "lib/SendGridCompatibility/", + "SparkPost\\Test\\TestUtils\\": "test/unit/TestUtils/" + } + } } diff --git a/composer.lock b/composer.lock index da4ff55..b1d62a9 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "3e19d00ab9d875ecad4120ce327766dd", - "content-hash": "781dee6a3f19ff78fcac2dc4814ea1cd", + "hash": "b07df33073385ce325ea9ef15b5f0da9", + "content-hash": "c5283ab83042f99acd4dd5b012446822", "packages": [ { "name": "egeloen/http-adapter", @@ -83,6 +83,7 @@ "http-client", "psr-7" ], + "abandoned": "php-http/httplug", "time": "2015-08-12 09:35:40" }, { @@ -136,16 +137,16 @@ }, { "name": "zendframework/zend-diactoros", - "version": "1.1.3", + "version": "1.3.3", "source": { "type": "git", "url": "https://github.com/zendframework/zend-diactoros.git", - "reference": "e2f5c12916c74da384058d0dfbc7fbc0b03d1181" + "reference": "4d54fde709664562eb63356f0250d527824d05de" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/e2f5c12916c74da384058d0dfbc7fbc0b03d1181", - "reference": "e2f5c12916c74da384058d0dfbc7fbc0b03d1181", + "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/4d54fde709664562eb63356f0250d527824d05de", + "reference": "4d54fde709664562eb63356f0250d527824d05de", "shasum": "" }, "require": { @@ -162,8 +163,8 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0-dev", - "dev-develop": "1.1-dev" + "dev-master": "1.3-dev", + "dev-develop": "1.4-dev" } }, "autoload": { @@ -182,7 +183,7 @@ "psr", "psr-7" ], - "time": "2015-08-10 20:04:20" + "time": "2016-01-04 21:37:32" } ], "packages-dev": [ @@ -240,24 +241,78 @@ ], "time": "2015-06-14 21:17:01" }, + { + "name": "fabpot/php-cs-fixer", + "version": "v1.11.2", + "source": { + "type": "git", + "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", + "reference": "41f70154642ec0f9ea9ea9c290943f3b5dfa76fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/41f70154642ec0f9ea9ea9c290943f3b5dfa76fc", + "reference": "41f70154642ec0f9ea9ea9c290943f3b5dfa76fc", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.3.6", + "sebastian/diff": "~1.1", + "symfony/console": "~2.3|~3.0", + "symfony/event-dispatcher": "~2.1|~3.0", + "symfony/filesystem": "~2.1|~3.0", + "symfony/finder": "~2.1|~3.0", + "symfony/process": "~2.3|~3.0", + "symfony/stopwatch": "~2.5|~3.0" + }, + "require-dev": { + "satooshi/php-coveralls": "0.7.*@dev" + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "autoload": { + "psr-4": { + "Symfony\\CS\\": "Symfony/CS/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "time": "2016-02-26 07:37:29" + }, { "name": "guzzle/guzzle", - "version": "v3.9.3", + "version": "v3.8.1", "source": { "type": "git", - "url": "https://github.com/guzzle/guzzle3.git", - "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9" + "url": "https://github.com/guzzle/guzzle.git", + "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/0645b70d953bc1c067bbc8d5bc53194706b628d9", - "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/4de0618a01b34aa1c8c33a3f13f396dcd3882eba", + "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba", "shasum": "" }, "require": { "ext-curl": "*", "php": ">=5.3.3", - "symfony/event-dispatcher": "~2.1" + "symfony/event-dispatcher": ">=2.1" }, "replace": { "guzzle/batch": "self.version", @@ -284,21 +339,18 @@ "guzzle/stream": "self.version" }, "require-dev": { - "doctrine/cache": "~1.3", - "monolog/monolog": "~1.0", + "doctrine/cache": "*", + "monolog/monolog": "1.*", "phpunit/phpunit": "3.7.*", - "psr/log": "~1.0", - "symfony/class-loader": "~2.1", - "zendframework/zend-cache": "2.*,<2.3", - "zendframework/zend-log": "2.*,<2.3" - }, - "suggest": { - "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated." + "psr/log": "1.0.*", + "symfony/class-loader": "*", + "zendframework/zend-cache": "<2.3", + "zendframework/zend-log": "<2.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.9-dev" + "dev-master": "3.8-dev" } }, "autoload": { @@ -322,7 +374,7 @@ "homepage": "https://github.com/guzzle/guzzle/contributors" } ], - "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library and framework for building RESTful web service clients", "homepage": "http://guzzlephp.org/", "keywords": [ "client", @@ -333,7 +385,7 @@ "rest", "web service" ], - "time": "2015-03-18 18:23:50" + "time": "2014-01-28 22:29:15" }, { "name": "guzzlehttp/guzzle", @@ -399,16 +451,16 @@ }, { "name": "guzzlehttp/promises", - "version": "1.0.2", + "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/guzzle/promises.git", - "reference": "97fe7210def29451ec74923b27e552238defd75a" + "reference": "b1e1c0d55f8083c71eda2c28c12a228d708294ea" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/promises/zipball/97fe7210def29451ec74923b27e552238defd75a", - "reference": "97fe7210def29451ec74923b27e552238defd75a", + "url": "https://api.github.com/repos/guzzle/promises/zipball/b1e1c0d55f8083c71eda2c28c12a228d708294ea", + "reference": "b1e1c0d55f8083c71eda2c28c12a228d708294ea", "shasum": "" }, "require": { @@ -446,20 +498,20 @@ "keywords": [ "promise" ], - "time": "2015-08-15 19:37:21" + "time": "2015-10-15 22:28:00" }, { "name": "guzzlehttp/psr7", - "version": "1.2.0", + "version": "1.2.3", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "4ef919b0cf3b1989523138b60163bbcb7ba1ff7e" + "reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/4ef919b0cf3b1989523138b60163bbcb7ba1ff7e", - "reference": "4ef919b0cf3b1989523138b60163bbcb7ba1ff7e", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/2e89629ff057ebb49492ba08e6995d3a6a80021b", + "reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b", "shasum": "" }, "require": { @@ -504,7 +556,7 @@ "stream", "uri" ], - "time": "2015-08-15 19:32:36" + "time": "2016-02-18 21:54:00" }, { "name": "hamcrest/hamcrest-php", @@ -618,16 +670,16 @@ }, { "name": "phpunit/php-code-coverage", - "version": "2.2.3", + "version": "2.2.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "ef1ca6835468857944d5c3b48fa503d5554cff2f" + "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/ef1ca6835468857944d5c3b48fa503d5554cff2f", - "reference": "ef1ca6835468857944d5c3b48fa503d5554cff2f", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/eabf68b476ac7d0f73793aada060f1c1a9bf8979", + "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979", "shasum": "" }, "require": { @@ -676,7 +728,7 @@ "testing", "xunit" ], - "time": "2015-09-14 06:51:16" + "time": "2015-10-06 15:47:00" }, { "name": "phpunit/php-file-iterator", @@ -1032,7 +1084,7 @@ }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/satooshi/php-coveralls/zipball/2fbf803803d179ab1082807308a67bbd5a760c70", + "url": "https://api.github.com/repos/satooshi/php-coveralls/zipball/50c60bb64054974f8ed7540ae6e75fd7981a5fd3", "reference": "2fbf803803d179ab1082807308a67bbd5a760c70", "shasum": "" }, @@ -1163,28 +1215,28 @@ }, { "name": "sebastian/diff", - "version": "1.3.0", + "version": "1.4.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3" + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3", - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e", + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { - "phpunit/phpunit": "~4.2" + "phpunit/phpunit": "~4.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.4-dev" } }, "autoload": { @@ -1207,24 +1259,24 @@ } ], "description": "Diff implementation", - "homepage": "http://www.github.com/sebastianbergmann/diff", + "homepage": "https://github.com/sebastianbergmann/diff", "keywords": [ "diff" ], - "time": "2015-02-22 15:13:53" + "time": "2015-12-08 07:14:41" }, { "name": "sebastian/environment", - "version": "1.3.2", + "version": "1.3.5", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "6324c907ce7a52478eeeaede764f48733ef5ae44" + "reference": "dc7a29032cf72b54f36dac15a1ca5b3a1b6029bf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/6324c907ce7a52478eeeaede764f48733ef5ae44", - "reference": "6324c907ce7a52478eeeaede764f48733ef5ae44", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/dc7a29032cf72b54f36dac15a1ca5b3a1b6029bf", + "reference": "dc7a29032cf72b54f36dac15a1ca5b3a1b6029bf", "shasum": "" }, "require": { @@ -1261,7 +1313,7 @@ "environment", "hhvm" ], - "time": "2015-08-03 06:14:51" + "time": "2016-02-26 18:40:46" }, { "name": "sebastian/exporter", @@ -1331,16 +1383,16 @@ }, { "name": "sebastian/recursion-context", - "version": "1.0.1", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba" + "reference": "913401df809e99e4f47b27cdd781f4a258d58791" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/994d4a811bafe801fb06dccbee797863ba2792ba", - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791", + "reference": "913401df809e99e4f47b27cdd781f4a258d58791", "shasum": "" }, "require": { @@ -1380,7 +1432,7 @@ ], "description": "Provides functionality to recursively process PHP variables", "homepage": "http://www.github.com/sebastianbergmann/recursion-context", - "time": "2015-06-21 08:04:50" + "time": "2015-11-11 19:50:13" }, { "name": "sebastian/version", @@ -1419,35 +1471,38 @@ }, { "name": "symfony/config", - "version": "v2.7.5", + "version": "v3.0.3", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "9698fdf0a750d6887d5e7729d5cf099765b20e61" + "reference": "79a97025f7bf4bbf8352b5df1905aa136a531066" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/9698fdf0a750d6887d5e7729d5cf099765b20e61", - "reference": "9698fdf0a750d6887d5e7729d5cf099765b20e61", + "url": "https://api.github.com/repos/symfony/config/zipball/79a97025f7bf4bbf8352b5df1905aa136a531066", + "reference": "79a97025f7bf4bbf8352b5df1905aa136a531066", "shasum": "" }, "require": { - "php": ">=5.3.9", - "symfony/filesystem": "~2.3" + "php": ">=5.5.9", + "symfony/filesystem": "~2.8|~3.0" }, - "require-dev": { - "symfony/phpunit-bridge": "~2.7" + "suggest": { + "symfony/yaml": "To use the yaml reference dumper" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Config\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1465,30 +1520,30 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2015-09-21 15:02:29" + "time": "2016-02-23 15:16:06" }, { "name": "symfony/console", - "version": "v2.7.5", + "version": "v3.0.3", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "06cb17c013a82f94a3d840682b49425cd00a2161" + "reference": "2ed5e2706ce92313d120b8fe50d1063bcfd12e04" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/06cb17c013a82f94a3d840682b49425cd00a2161", - "reference": "06cb17c013a82f94a3d840682b49425cd00a2161", + "url": "https://api.github.com/repos/symfony/console/zipball/2ed5e2706ce92313d120b8fe50d1063bcfd12e04", + "reference": "2ed5e2706ce92313d120b8fe50d1063bcfd12e04", "shasum": "" }, "require": { - "php": ">=5.3.9" + "php": ">=5.5.9", + "symfony/polyfill-mbstring": "~1.0" }, "require-dev": { "psr/log": "~1.0", - "symfony/event-dispatcher": "~2.1", - "symfony/phpunit-bridge": "~2.7", - "symfony/process": "~2.1" + "symfony/event-dispatcher": "~2.8|~3.0", + "symfony/process": "~2.8|~3.0" }, "suggest": { "psr/log": "For using the console logger", @@ -1498,13 +1553,16 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Console\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1522,32 +1580,31 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2015-09-25 08:32:23" + "time": "2016-02-28 16:24:34" }, { "name": "symfony/event-dispatcher", - "version": "v2.7.5", + "version": "v3.0.3", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9" + "reference": "4dd5df31a28c0f82b41cb1e1599b74b5dcdbdafa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", - "reference": "ae4dcc2a8d3de98bd794167a3ccda1311597c5d9", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/4dd5df31a28c0f82b41cb1e1599b74b5dcdbdafa", + "reference": "4dd5df31a28c0f82b41cb1e1599b74b5dcdbdafa", "shasum": "" }, "require": { - "php": ">=5.3.9" + "php": ">=5.5.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" + "symfony/config": "~2.8|~3.0", + "symfony/dependency-injection": "~2.8|~3.0", + "symfony/expression-language": "~2.8|~3.0", + "symfony/stopwatch": "~2.8|~3.0" }, "suggest": { "symfony/dependency-injection": "", @@ -1556,13 +1613,16 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1580,38 +1640,38 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2015-09-22 13:49:29" + "time": "2016-01-27 05:14:46" }, { "name": "symfony/filesystem", - "version": "v2.7.5", + "version": "v3.0.3", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "a17f8a17c20e8614c15b8e116e2f4bcde102cfab" + "reference": "23ae8f9648d0a7fe94a47c8e20e5bf37c489a451" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/a17f8a17c20e8614c15b8e116e2f4bcde102cfab", - "reference": "a17f8a17c20e8614c15b8e116e2f4bcde102cfab", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/23ae8f9648d0a7fe94a47c8e20e5bf37c489a451", + "reference": "23ae8f9648d0a7fe94a47c8e20e5bf37c489a451", "shasum": "" }, "require": { - "php": ">=5.3.9" - }, - "require-dev": { - "symfony/phpunit-bridge": "~2.7" + "php": ">=5.5.9" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Filesystem\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1629,38 +1689,195 @@ ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", - "time": "2015-09-09 17:42:36" + "time": "2016-02-23 15:16:06" + }, + { + "name": "symfony/finder", + "version": "v3.0.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "623bda0abd9aa29e529c8e9c08b3b84171914723" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/623bda0abd9aa29e529c8e9c08b3b84171914723", + "reference": "623bda0abd9aa29e529c8e9c08b3b84171914723", + "shasum": "" + }, + "require": { + "php": ">=5.5.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "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 Finder Component", + "homepage": "https://symfony.com", + "time": "2016-01-27 05:14:46" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "1289d16209491b584839022f29257ad859b8532d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/1289d16209491b584839022f29257ad859b8532d", + "reference": "1289d16209491b584839022f29257ad859b8532d", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2016-01-20 09:13:37" + }, + { + "name": "symfony/process", + "version": "v3.0.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "dfecef47506179db2501430e732adbf3793099c8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/dfecef47506179db2501430e732adbf3793099c8", + "reference": "dfecef47506179db2501430e732adbf3793099c8", + "shasum": "" + }, + "require": { + "php": ">=5.5.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "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 Process Component", + "homepage": "https://symfony.com", + "time": "2016-02-02 13:44:19" }, { "name": "symfony/stopwatch", - "version": "v2.7.5", + "version": "v3.0.3", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", - "reference": "08dd97b3f22ab9ee658cd16e6758f8c3c404336e" + "reference": "4a204804952ff267ace88cf499e0b4bb302a475e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/stopwatch/zipball/08dd97b3f22ab9ee658cd16e6758f8c3c404336e", - "reference": "08dd97b3f22ab9ee658cd16e6758f8c3c404336e", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/4a204804952ff267ace88cf499e0b4bb302a475e", + "reference": "4a204804952ff267ace88cf499e0b4bb302a475e", "shasum": "" }, "require": { - "php": ">=5.3.9" - }, - "require-dev": { - "symfony/phpunit-bridge": "~2.7" + "php": ">=5.5.9" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Stopwatch\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1678,38 +1895,38 @@ ], "description": "Symfony Stopwatch Component", "homepage": "https://symfony.com", - "time": "2015-09-22 13:49:29" + "time": "2016-01-03 15:35:16" }, { "name": "symfony/yaml", - "version": "v2.7.5", + "version": "v2.8.3", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "31cb2ad0155c95b88ee55fe12bc7ff92232c1770" + "reference": "2a4ee40acb880c56f29fb1b8886e7ffe94f3b995" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/31cb2ad0155c95b88ee55fe12bc7ff92232c1770", - "reference": "31cb2ad0155c95b88ee55fe12bc7ff92232c1770", + "url": "https://api.github.com/repos/symfony/yaml/zipball/2a4ee40acb880c56f29fb1b8886e7ffe94f3b995", + "reference": "2a4ee40acb880c56f29fb1b8886e7ffe94f3b995", "shasum": "" }, "require": { "php": ">=5.3.9" }, - "require-dev": { - "symfony/phpunit-bridge": "~2.7" - }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.7-dev" + "dev-master": "2.8-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Yaml\\": "" - } + }, + "exclude-from-classmap": [ + "/Tests/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1727,7 +1944,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2015-09-14 14:14:09" + "time": "2016-02-23 07:41:20" } ], "aliases": [], diff --git a/examples/bootstrap.php b/examples/bootstrap.php index 774b159..688d53e 100644 --- a/examples/bootstrap.php +++ b/examples/bootstrap.php @@ -1,3 +1,3 @@ \ No newline at end of file + +require_once dirname(__FILE__).'/../vendor/autoload.php'; diff --git a/examples/transmission/delete_transmission.php b/examples/transmission/delete_transmission.php index 9459066..f7d0530 100644 --- a/examples/transmission/delete_transmission.php +++ b/examples/transmission/delete_transmission.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->delete('transmission-id'); echo 'Transmission deleted!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/get_all_transmissions.php b/examples/transmission/get_all_transmissions.php index a465056..c037b2d 100644 --- a/examples/transmission/get_all_transmissions.php +++ b/examples/transmission/get_all_transmissions.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->all(); echo 'Congrats! You got a list of all your transmissions from SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/get_transmission.php b/examples/transmission/get_transmission.php index 879e9c3..5d59740 100644 --- a/examples/transmission/get_transmission.php +++ b/examples/transmission/get_transmission.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->find('Your Transmission ID'); echo 'Congrats! You retrieved your transmission from SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/rfc822.php b/examples/transmission/rfc822.php index 5ec5aef..df2b06b 100644 --- a/examples/transmission/rfc822.php +++ b/examples/transmission/rfc822.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->send([ - 'recipients'=>[ + 'recipients' => [ [ - 'address'=>[ - 'email'=>'john.doe@example.com' - ] - ] + 'address' => [ + 'email' => 'john.doe@example.com', + ], + ], ], - 'rfc822'=>"Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World" + 'rfc822' => "Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World", ]); echo 'Congrats! You sent an email using SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/send_transmission_all_fields.php b/examples/transmission/send_transmission_all_fields.php index 9db99d2..26cb96d 100644 --- a/examples/transmission/send_transmission_all_fields.php +++ b/examples/transmission/send_transmission_all_fields.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); $data = file_get_contents('/path/to/test.csv'); -try{ +try { $results = $sparky->transmission->send([ - 'campaign'=>'my-campaign', - 'metadata'=>[ - 'sample_campaign'=>true, - 'type'=>'these are custom fields' + 'campaign' => 'my-campaign', + 'metadata' => [ + 'sample_campaign' => true, + 'type' => 'these are custom fields', ], - 'substitutionData'=>[ - 'name'=>'Test Name' + 'substitutionData' => [ + 'name' => 'Test Name', ], - 'description'=>'my description', - 'replyTo'=>'reply@test.com', - 'customHeaders'=>[ - 'X-Custom-Header'=>'Sample Custom Header' + 'description' => 'my description', + 'replyTo' => 'reply@test.com', + 'customHeaders' => [ + 'X-Custom-Header' => 'Sample Custom Header', ], - 'trackOpens'=>false, - 'trackClicks'=>false, - 'sandbox'=>false, - 'inlineCss'=>true, - 'transactional'=>true, - 'startTime'=>'2016-03-17T08:00:00-04:00', - 'from'=>[ + 'trackOpens' => false, + 'trackClicks' => false, + 'sandbox' => false, + 'inlineCss' => true, + 'transactional' => true, + 'startTime' => '2016-03-17T08:00:00-04:00', + 'from' => [ 'name' => 'From Envelope', - 'email' => 'from@sparkpostbox.com' + 'email' => 'from@sparkpostbox.com', ], - 'html'=>'

Hello World! Your name is: {{name}}

', - 'text'=>'Hello World!', - 'subject'=>'Example Email: {{name}}', - 'recipients'=>[ + 'html' => '

Hello World! Your name is: {{name}}

', + 'text' => 'Hello World!', + 'subject' => 'Example Email: {{name}}', + 'recipients' => [ [ - 'address'=>[ - 'email'=>'john.doe@example.com' - ] - ] + 'address' => [ + 'email' => 'john.doe@example.com', + ], + ], ], - 'attachments'=>[ + 'attachments' => [ [ - 'type'=>'text/csv', - 'name'=>'testing.csv', - 'data'=>base64_encode($data) - ] - ] + 'type' => 'text/csv', + 'name' => 'testing.csv', + 'data' => base64_encode($data), + ], + ], ]); echo 'Congrats! You sent an email using SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/simple_send.php b/examples/transmission/simple_send.php index 5d2d6e3..6bd0336 100644 --- a/examples/transmission/simple_send.php +++ b/examples/transmission/simple_send.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->send([ - 'from'=>[ + 'from' => [ 'name' => 'From Envelope', - 'email' => 'from@sparkpostbox.com' + 'email' => 'from@sparkpostbox.com', ], - 'html'=>'

Hello World!

', - 'text'=>'Hello World!', - 'subject'=>'Example Email', - 'recipients'=>[ + 'html' => '

Hello World!

', + 'text' => 'Hello World!', + 'subject' => 'Example Email', + 'recipients' => [ [ - 'address'=>[ - 'email'=>'john.doe@example.com' - ] - ] - ] + 'address' => [ + 'email' => 'john.doe@example.com', + ], + ], + ], ]); echo 'Congrats! You sent an email using SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/stored_recipients_inline_content.php b/examples/transmission/stored_recipients_inline_content.php index 8b16456..503908b 100644 --- a/examples/transmission/stored_recipients_inline_content.php +++ b/examples/transmission/stored_recipients_inline_content.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { - $results = $sparky->transmission->send([ - 'campaign'=>'my-campaign', - 'from'=>[ + 'campaign' => 'my-campaign', + 'from' => [ 'name' => 'From Envelope', - 'email' => 'from@sparkpostbox.com' + 'email' => 'from@sparkpostbox.com', ], - 'html'=>'

Hello World! Your name is: {{name}}

', - 'text'=>'Hello World!', - 'subject'=>'Example Email: {{name}}', - 'recipientList'=>'Example List' + 'html' => '

Hello World! Your name is: {{name}}

', + 'text' => 'Hello World!', + 'subject' => 'Example Email: {{name}}', + 'recipientList' => 'Example List', ]); echo 'Congrats! You sent an email using SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/transmission/stored_template_send.php b/examples/transmission/stored_template_send.php index 4d4adfe..5ce48e4 100644 --- a/examples/transmission/stored_template_send.php +++ b/examples/transmission/stored_template_send.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $results = $sparky->transmission->send([ - 'from'=>[ + 'from' => [ 'name' => 'From Envelope', - 'email' => 'from@sparkpostbox.com' + 'email' => 'from@sparkpostbox.com', ], - 'recipients'=>[ + 'recipients' => [ [ - 'address'=>[ - 'email'=>'john.doe@example.com' - ] - ] + 'address' => [ + 'email' => 'john.doe@example.com', + ], + ], ], - 'template'=>'my-first-email' + 'template' => 'my-first-email', ]); echo 'Congrats! You sent an email using SparkPost!'; } catch (\Exception $exception) { - echo $exception->getAPIMessage() . "\n"; - echo $exception->getAPICode() . "\n"; - echo $exception->getAPIDescription() . "\n"; + echo $exception->getAPIMessage()."\n"; + echo $exception->getAPICode()."\n"; + echo $exception->getAPIDescription()."\n"; } -?> diff --git a/examples/unwrapped/create_template.php b/examples/unwrapped/create_template.php index 45239b0..89523f1 100644 --- a/examples/unwrapped/create_template.php +++ b/examples/unwrapped/create_template.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { // define the endpoint @@ -19,16 +21,15 @@ $templateConfig = [ 'name' => 'Summer Sale!', - 'id'=>'summer-sale', - 'content'=> [ + 'id' => 'summer-sale', + 'content' => [ 'from' => 'from@sparkpostbox.com', 'subject' => 'Summer deals', - 'html' => 'Check out these deals!' - ] + 'html' => 'Check out these deals!', + ], ]; $results = $sparky->templates->create($templateConfig); echo 'Congrats! You created a template using SparkPost!'; } catch (\Exception $exception) { echo $exception->getMessage(); } -?> diff --git a/examples/unwrapped/get_webhooks.php b/examples/unwrapped/get_webhooks.php index a71cb3f..e149b21 100644 --- a/examples/unwrapped/get_webhooks.php +++ b/examples/unwrapped/get_webhooks.php @@ -1,9 +1,11 @@ $config['api-key']]); +$sparky = new SparkPost($httpAdapter, ['key' => $config['api-key']]); try { $sparky->setupUnwrapped('webhooks'); @@ -22,4 +24,3 @@ } catch (\Exception $exception) { echo $exception->getMessage(); } -?> diff --git a/lib/SendGridCompatibility/Email.php b/lib/SendGridCompatibility/Email.php index 5065e1f..3ca2466 100644 --- a/lib/SendGridCompatibility/Email.php +++ b/lib/SendGridCompatibility/Email.php @@ -1,199 +1,259 @@ model = array(); - } - - /** - * adds addresses as recipients - * @param string $address - * @param string $name optional - * @return $this - */ - 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; - } - - /** - * explicitly sets a list of addresses - * @param array $addresses - * @return $this - */ - public function setTos(array $addresses) { - $this->model['recipients'] = $addresses; - return $this; - } - - /** - * sets the from address - * @param string $address - * @return $this - */ - public function setFrom($address) { - $this->model['from'] = array('email' => $address); - return $this; - } - - /** - * Sets the name for the from address - * @param string $name - * @return $this - * @throws \Exception - */ - 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; - } - - /** - * sets the reply to field - * @param string $address - * @return $this - */ - public function setReplyTo ($address) { - $this->model['replyTo'] = $address; - return $this; - } - - /** - * throws an error because bcc fields are not yet implemented. - * @throws \Exception - * @param string $address - * @return $this - */ - public function addBcc($address) { - throw new \Exception('Adding bcc recipients is not yet supported, try adding them as a \'to\' address'); - } - - /** - * sets the subject header - * @param string $subject - * @return $this - */ - public function setSubject($subject) { - $this->model['subject'] = $subject; - return $this; - } - - /** - * sets the text body - * @param string $text - * @return $this - */ - public function setText($text) { - $this->model['text'] = $text; - return $this; - } - - /** - * sets the html body - * @param string $html - * @return $this - */ - public function setHtml($html) { - $this->model['html'] = $html; - return $this; - } - - /** - * Throws an exception since adding categories is not yet supported - * @param string $category - * @throws \Exception - */ - public function addCategory($category) { - throw new \Exception('Adding categories is not yet supported'); - } - - /** - * 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'); - } - - /** - * Adds transmission level substitution data - * @param string $name - * @param mixed $values - * @return $this - */ - public function addSubstitution($name, $values) { - if (!isset($this->model['substitutionData'])) { - $this->model['substitutionData'] = array(); - } - $this->model['substitutionData'][$name] = $values; - - return $this; - } - - /** - * Adds transmission level substitution data - * @param string $name - * @param mixed $values - */ - public function addSection($name, $values) { - $this->addSubstitution($name, $values); - } - - /** - * 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'); - } - - /** - * 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'); - } - - /** - * 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; - } - - /** - * converts this object to a configuration for a SparkPost transmission - * @return array - */ - public function toSparkPostTransmission() { - return $this->model; - } +class Email +{ + public $model; + + /** + * Sets up the model for saving the configuration. + */ + public function __construct() + { + $this->model = array(); + } + + /** + * adds addresses as recipients. + * + * @param string $address + * @param string $name optional + * + * @return $this + */ + 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; + } + + /** + * explicitly sets a list of addresses. + * + * @param array $addresses + * + * @return $this + */ + public function setTos(array $addresses) + { + $this->model['recipients'] = $addresses; + + return $this; + } + + /** + * sets the from address. + * + * @param string $address + * + * @return $this + */ + public function setFrom($address) + { + $this->model['from'] = array('email' => $address); + + return $this; + } + + /** + * Sets the name for the from address. + * + * @param string $name + * + * @return $this + * + * @throws \Exception + */ + 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; + } + + /** + * sets the reply to field. + * + * @param string $address + * + * @return $this + */ + public function setReplyTo($address) + { + $this->model['replyTo'] = $address; + + return $this; + } + + /** + * throws an error because bcc fields are not yet implemented. + * + * @throws \Exception + * + * @param string $address + * + * @return $this + */ + public function addBcc($address) + { + throw new \Exception('Adding bcc recipients is not yet supported, try adding them as a \'to\' address'); + } + + /** + * sets the subject header. + * + * @param string $subject + * + * @return $this + */ + public function setSubject($subject) + { + $this->model['subject'] = $subject; + + return $this; + } + + /** + * sets the text body. + * + * @param string $text + * + * @return $this + */ + public function setText($text) + { + $this->model['text'] = $text; + + return $this; + } + + /** + * sets the html body. + * + * @param string $html + * + * @return $this + */ + public function setHtml($html) + { + $this->model['html'] = $html; + + return $this; + } + + /** + * Throws an exception since adding categories is not yet supported. + * + * @param string $category + * + * @throws \Exception + */ + public function addCategory($category) + { + throw new \Exception('Adding categories is not yet supported'); + } + + /** + * 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'); + } + + /** + * Adds transmission level substitution data. + * + * @param string $name + * @param mixed $values + * + * @return $this + */ + public function addSubstitution($name, $values) + { + if (!isset($this->model['substitutionData'])) { + $this->model['substitutionData'] = array(); + } + $this->model['substitutionData'][$name] = $values; + + return $this; + } + + /** + * Adds transmission level substitution data. + * + * @param string $name + * @param mixed $values + */ + public function addSection($name, $values) + { + $this->addSubstitution($name, $values); + } + + /** + * 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'); + } + + /** + * 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'); + } + + /** + * 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; + } + + /** + * converts this object to a configuration for a SparkPost transmission. + * + * @return array + */ + public function toSparkPostTransmission() + { + return $this->model; + } } -?> diff --git a/lib/SendGridCompatibility/SendGrid.php b/lib/SendGridCompatibility/SendGrid.php index 1671e6b..c5e84c1 100644 --- a/lib/SendGridCompatibility/SendGrid.php +++ b/lib/SendGridCompatibility/SendGrid.php @@ -1,23 +1,26 @@ $password); - if (!is_null($options)) { - $opts = array_merge($opts, $options); - } + 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); - } + $this->sparky = new SparkPost($httpAdapter, $opts); + } - public function send(Email $email) { - $this->sparky->transmission->send($email->toSparkPostTransmission()); - } + public function send(Email $email) + { + $this->sparky->transmission->send($email->toSparkPostTransmission()); + } } -?> diff --git a/lib/SparkPost/APIResource.php b/lib/SparkPost/APIResource.php index f593038..36b03a8 100644 --- a/lib/SparkPost/APIResource.php +++ b/lib/SparkPost/APIResource.php @@ -1,241 +1,265 @@ sparkpost = $sparkpost; - } - - /** - * 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; +class APIResource +{ + /** + * name of the API endpoint, mainly used for URL construction. + * This is public to provide an interface. + * + * @var string + */ + public $endpoint; + + /** + * Mapping for values passed into the send method to the values needed for the respective API. + * + * @var array + */ + protected static $parameterMappings = []; + + /** + * Sets up default structure and default values for the model that is acceptable by the API. + * + * @var array + */ + protected static $structure = []; + + /** + * SparkPost reference for httpAdapters and configs. + */ + protected $sparkpost; + + /** + * Initializes config and httpAdapter for use later. + * + * @param $sparkpost \SparkPost\SparkPost provides api configuration information + */ + public function __construct(SparkPost $sparkpost) + { + $this->sparkpost = $sparkpost; } - $path = explode('.', $mapPath); - $temp = &$model; - foreach( $path as $key ) { - if( !isset($temp[$key]) ){ - $temp[$key] = null; - } - $temp = &$temp[$key]; + /** + * 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; } - $temp = $value; - - } - - /** - * maps values from the passed in model to those needed for the request - * @param array $requestConfig the passed in model - * @param array $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); + + /** + * maps values from the passed in model to those needed for the request. + * + * @param array $requestConfig the passed in model + * @param array $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; } - return $model; - } - - /** - * posts to the api with a supplied body - * @param array $body post body for the request - * @return array Result of the request - */ - public function create(Array $body=[]) { - return $this->callResource( 'post', null, ['body'=>$body]); - } - - /** - * Makes a put request to the api with a supplied body - * @param $resourcePath - * @param array $body Put body for the request - * @return array Result of the request - * @throws APIResponseException - */ - public function update( $resourcePath, Array $body=[]) { - return $this->callResource( 'put', $resourcePath, ['body'=>$body]); - } - - /** - * Wrapper method for issuing GET request to current API endpoint - * - * @param string $resourcePath (optional) string resource path of specific resource - * @param array $query (optional) query string parameters - * @return array Result of the request - */ - public function get( $resourcePath=null, Array $query=[] ) { - return $this->callResource( 'get', $resourcePath, ['query'=>$query] ); - } - - /** - * Wrapper method for issuing DELETE request to current API endpoint - * - * @param string $resourcePath (optional) string resource path of specific resource - * @param array $query (optional) query string parameters - * @return array Result of the request - */ - public function delete( $resourcePath=null, Array $query=[] ) { - return $this->callResource( 'delete', $resourcePath, ['query'=>$query] ); - } - - - /** - * 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. Any - * query elements that are themselves arrays will be imploded into a comma separated list. - * @return string the assembled URL - */ - private function buildUrl($resourcePath, $options) { - $url = "/{$this->endpoint}/"; - if (!is_null($resourcePath)){ - $url .= $resourcePath; + + /** + * posts to the api with a supplied body. + * + * @param array $body post body for the request + * + * @return array Result of the request + */ + public function create(array $body = []) + { + return $this->callResource('post', null, ['body' => $body]); } - if( !empty($options['query'])) { - // check each query element - if it's an array, implode it to match the API-accepted format - foreach($options['query'] as &$element) { - if(is_array($element)) { - $element = implode(",", $element); - } - } + /** + * Makes a put request to the api with a supplied body. + * + * @param $resourcePath + * @param array $body Put body for the request + * + * @return array Result of the request + * + * @throws APIResponseException + */ + public function update($resourcePath, array $body = []) + { + return $this->callResource('put', $resourcePath, ['body' => $body]); + } - $queryString = http_build_query($options['query']); - $url .= '?'.$queryString; + /** + * Wrapper method for issuing GET request to current API endpoint. + * + * @param string $resourcePath (optional) string resource path of specific resource + * @param array $query (optional) query string parameters + * + * @return array Result of the request + */ + public function get($resourcePath = null, array $query = []) + { + return $this->callResource('get', $resourcePath, ['query' => $query]); } - return $url; - } - - - /** - * 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); + /** + * Wrapper method for issuing DELETE request to current API endpoint. + * + * @param string $resourcePath (optional) string resource path of specific resource + * @param array $query (optional) query string parameters + * + * @return array Result of the request + */ + public function delete($resourcePath = null, array $query = []) + { + return $this->callResource('delete', $resourcePath, ['query' => $query]); } - return $body; - } - - /** - * 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 - * @throws APIResponseException - */ - 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); - - $statusCode = $response->getStatusCode(); - - // Handle 4XX responses, 5XX responses will throw an HttpAdapterException - if ($statusCode < 400) { - return json_decode($response->getBody()->getContents(), true); - } - elseif ($statusCode === 403) { - $response = json_decode($response->getBody(), true); - throw new APIResponseException( - 'Request forbidden', - $statusCode, - isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : "Request forbidden", - isset($response['errors'][0]['code']) ? $response['errors'][0]['code'] : 1100, - isset($response['errors'][0]['description']) ? $response['errors'][0]['description'] : "Does this API Key have the correct permissions?" - ); - } - elseif ($statusCode === 404) { - throw new APIResponseException('The specified resource does not exist', 404); - } - else { - $response = json_decode($response->getBody(), true); - throw new APIResponseException( - 'Received bad response from ' . ucfirst($this->endpoint), - $statusCode, - isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : "", - isset($response['errors'][0]['code']) ? $response['errors'][0]['code'] : 0, - isset($response['errors'][0]['description']) ? $response['errors'][0]['description'] : "" - ); - } + + /** + * 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. Any + * query elements that are themselves arrays will be imploded into a comma separated list. + * + * @return string the assembled URL + */ + private function buildUrl($resourcePath, $options) + { + $url = "/{$this->endpoint}/"; + if (!is_null($resourcePath)) { + $url .= $resourcePath; + } + + if (!empty($options['query'])) { + // check each query element - if it's an array, implode it to match the API-accepted format + foreach ($options['query'] as &$element) { + if (is_array($element)) { + $element = implode(',', $element); + } + } + + $queryString = http_build_query($options['query']); + $url .= '?'.$queryString; + } + + return $url; } - /* - * Configuration Errors, and a catch all for other errors + /** + * 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 */ - catch (\Exception $exception) { - if($exception instanceof APIResponseException) { - throw $exception; - } + private function buildBody($options) + { + $body = null; + if (!empty($options['body'])) { + $model = static::$structure; + $requestModel = $this->buildRequestModel($options['body'], $model); + $body = json_encode($requestModel); + } - throw new APIResponseException('Unable to contact ' . ucfirst($this->endpoint) . ' API: '. $exception->getMessage(), $exception->getCode()); + return $body; } - } + /** + * 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 + * + * @throws APIResponseException + */ + 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); + + $statusCode = $response->getStatusCode(); + + // Handle 4XX responses, 5XX responses will throw an HttpAdapterException + if ($statusCode < 400) { + return json_decode($response->getBody()->getContents(), true); + } elseif ($statusCode === 403) { + $response = json_decode($response->getBody(), true); + throw new APIResponseException( + 'Request forbidden', + $statusCode, + isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : 'Request forbidden', + isset($response['errors'][0]['code']) ? $response['errors'][0]['code'] : 1100, + isset($response['errors'][0]['description']) ? $response['errors'][0]['description'] : 'Does this API Key have the correct permissions?' + ); + } elseif ($statusCode === 404) { + throw new APIResponseException('The specified resource does not exist', 404); + } else { + $response = json_decode($response->getBody(), true); + throw new APIResponseException( + 'Received bad response from '.ucfirst($this->endpoint), + $statusCode, + isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '', + isset($response['errors'][0]['code']) ? $response['errors'][0]['code'] : 0, + isset($response['errors'][0]['description']) ? $response['errors'][0]['description'] : '' + ); + } + } + + /* + * Configuration Errors, and a catch all for other errors + */ + catch (\Exception $exception) { + if ($exception instanceof APIResponseException) { + throw $exception; + } + + throw new APIResponseException('Unable to contact '.ucfirst($this->endpoint).' API: '.$exception->getMessage(), $exception->getCode()); + } + } } diff --git a/lib/SparkPost/APIResponseException.php b/lib/SparkPost/APIResponseException.php index bc0e782..a491b3c 100644 --- a/lib/SparkPost/APIResponseException.php +++ b/lib/SparkPost/APIResponseException.php @@ -2,54 +2,61 @@ namespace SparkPost; -class APIResponseException extends \Exception { - /** - * @var string - */ - protected $apiMessage; - - /** - * @var int - */ - protected $apiCode; - - /** - * @var string - */ - protected $apiDescription; - - /** - * Construct the exception. - */ - public function __construct($message = "", $code = 0, $apiMessage = "", $apiCode = 0, $apiDescription = "") { - $this->apiMessage = $apiMessage; - $this->apiCode = $apiCode; - $this->apiDescription = $apiDescription; - parent::__construct($message, $code); - } - - /** - * Gets the Exception message - * @return string the Exception message as a string. - */ - public function getAPIMessage() { - return $this->apiMessage; - } - - /** - * Gets the API Exception code. - * @return int the exception code as integer. - */ - public function getAPICode() { - return $this->apiCode; - } - - /** - * Gets the Exception description - * @return string the Exception description as a string. - */ - public function getAPIDescription() { - return $this->apiDescription; - } - +class APIResponseException extends \Exception +{ + /** + * @var string + */ + protected $apiMessage; + + /** + * @var int + */ + protected $apiCode; + + /** + * @var string + */ + protected $apiDescription; + + /** + * Construct the exception. + */ + public function __construct($message = '', $code = 0, $apiMessage = '', $apiCode = 0, $apiDescription = '') + { + $this->apiMessage = $apiMessage; + $this->apiCode = $apiCode; + $this->apiDescription = $apiDescription; + parent::__construct($message, $code); + } + + /** + * Gets the Exception message. + * + * @return string the Exception message as a string. + */ + public function getAPIMessage() + { + return $this->apiMessage; + } + + /** + * Gets the API Exception code. + * + * @return int the exception code as integer. + */ + public function getAPICode() + { + return $this->apiCode; + } + + /** + * Gets the Exception description. + * + * @return string the Exception description as a string. + */ + public function getAPIDescription() + { + return $this->apiDescription; + } } diff --git a/lib/SparkPost/MessageEvents.php b/lib/SparkPost/MessageEvents.php index 788b752..d44a30f 100644 --- a/lib/SparkPost/MessageEvents.php +++ b/lib/SparkPost/MessageEvents.php @@ -1,60 +1,64 @@ format(\DateTime::ATOM), 0, 16); - } - } + /** + * Method for issuing search requests to the Message Events API. + * + * The method passes-through all of the query parameters - the valid ones are listed at + * + * @link https://developers.sparkpost.com/api/#/reference/message-events/events-documentation/search-for-message-events + * + * @param array $queryParams The query parameters. Note that a query parameter containing an array + * is collapsed into a comma-separated list. + * + * @return array The result of the query. + */ + public function search(array $queryParams) + { + // check for DateTime objects & replace them with the formatted string equivalent + foreach (['from', 'to'] as $dateTimeParam) { + if (isset($queryParams[$dateTimeParam]) && $queryParams[$dateTimeParam] instanceof \DateTime) { + // the message events API doesn't allow the seconds or GMT offset, so strip them + $queryParams[$dateTimeParam] = substr($queryParams[$dateTimeParam]->format(\DateTime::ATOM), 0, 16); + } + } - return $this->get(null, $queryParams); - } + return $this->get(null, $queryParams); + } - /** - * List descriptions of the event fields that could be included in a response from the MessageEvent::search() method. - * - * @return array The event field descriptions. - */ - public function documentation() { - return $this->get("events/documentation"); - } + /** + * List descriptions of the event fields that could be included in a response from the MessageEvent::search() method. + * + * @return array The event field descriptions. + */ + public function documentation() + { + return $this->get('events/documentation'); + } - /** - * List examples of the event data that will be included in a response from the MessageEvent::search() method. - * - * @param array $events (optional) Event types for which to get a sample payload. If not provided, samples - * for all events will be returned. - * - * @return array Sample events. - */ - public function samples(Array $events = []) { - return $this->get("events/samples", ["events"=>$events]); - } -} \ No newline at end of file + /** + * List examples of the event data that will be included in a response from the MessageEvent::search() method. + * + * @param array $events (optional) Event types for which to get a sample payload. If not provided, samples + * for all events will be returned. + * + * @return array Sample events. + */ + public function samples(array $events = []) + { + return $this->get('events/samples', ['events' => $events]); + } +} diff --git a/lib/SparkPost/SparkPost.php b/lib/SparkPost/SparkPost.php index ffc84f0..92ad867 100644 --- a/lib/SparkPost/SparkPost.php +++ b/lib/SparkPost/SparkPost.php @@ -1,136 +1,150 @@ 'api.sparkpost.com', - 'protocol'=>'https', - 'port'=>443, - 'strictSSL'=>true, - 'key'=>'', - 'version'=>'v1' - ]; - - /** - * Sets up httpAdapter and config - * - * Sets up instances of sub libraries. - * - * @param \Ivory\HttpAdapter\HttpAdapterInterface $httpAdapter - An adapter for making http requests - * @param String | array $settingsConfig - Hashmap that contains config values - * for the SDK to connect to SparkPost. If its a string we assume that - * its just they API Key. - */ - 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); - $this->messageEvents = new MessageEvents($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 - * @param string $endpoint - * @return APIResource - the unwrapped resource - */ - public function setupUnwrapped ($endpoint) { - $this->{$endpoint} = new APIResource($this); - $this->{$endpoint}->endpoint = $endpoint; - - return $this->{$endpoint}; - } - - /** - * Merges passed in headers with default headers for http requests - */ - public function getHttpHeaders() { - $defaultOptions = [ - 'Authorization' => $this->config['key'], - 'Content-Type' => 'application/json', +class SparkPost +{ + public $transmission; + public $messageEvents; + + /** + * Library version, used for setting User-Agent. + */ + private $version = '1.1.0'; + + /** + * Connection config for making requests. + */ + private $config; + + /** + * @var \Ivory\HttpAdapter\HttpAdapterInterface to make requests through. + */ + public $httpAdapter; + + /** + * 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', ]; - return $defaultOptions; - } - - /** - * Helper function for getting the configuration for http requests - * @param array $config - * @return Configuration - */ - private function getHttpConfig($config) { - // 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/' . $this->version); - return $httpConfig; - } - - - /** - * Validates and sets up the httpAdapter - * @param $httpAdapter \Ivory\HttpAdapter\HttpAdapterInterface to make requests through. - * @throws \Exception - */ - public function setHttpAdapter(HttpAdapterInterface $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 String | array $settingsConfig - Hashmap that contains config values - * for the SDK to connect to SparkPost. If its a string we assume that - * its just they API Key. - * @throws \Exception - */ - public function setConfig($settingsConfig) { - // if the config map is a string we should assume that its an api key - if (is_string($settingsConfig)) { - $settingsConfig = ['key'=>$settingsConfig]; + /** + * Sets up httpAdapter and config. + * + * Sets up instances of sub libraries. + * + * @param \Ivory\HttpAdapter\HttpAdapterInterface $httpAdapter - An adapter for making http requests + * @param string | array $settingsConfig - Hashmap that contains config values + * for the SDK to connect to SparkPost. If its a string we assume that + * its just they API Key. + */ + 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); + $this->messageEvents = new MessageEvents($this); } - // Validate API key because its required - if (!isset($settingsConfig['key']) || !preg_match('/\S/', $settingsConfig['key'])){ - throw new \Exception('You must provide an API key'); + /** + * Creates an unwrapped api interface for endpoints that aren't yet supported. + * The new resource is attached to this object as well as returned. + * + * @param string $endpoint + * + * @return APIResource - the unwrapped resource + */ + public function setupUnwrapped($endpoint) + { + $this->{$endpoint} = new APIResource($this); + $this->{$endpoint}->endpoint = $endpoint; + + return $this->{$endpoint}; } - $this->config = self::$apiDefaults; + /** + * Merges passed in headers with default headers for http requests. + */ + public function getHttpHeaders() + { + $defaultOptions = [ + 'Authorization' => $this->config['key'], + 'Content-Type' => 'application/json', + ]; + + return $defaultOptions; + } - // set config, overriding defaults - foreach ($settingsConfig as $configOption => $configValue) { - if(key_exists($configOption, $this->config)) { - $this->config[$configOption] = $configValue; - } + /** + * Helper function for getting the configuration for http requests. + * + * @param array $config + * + * @return Configuration + */ + private function getHttpConfig($config) + { + // 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/'.$this->version); + + return $httpConfig; } - } -} -?> + /** + * Validates and sets up the httpAdapter. + * + * @param $httpAdapter \Ivory\HttpAdapter\HttpAdapterInterface to make requests through. + * + * @throws \Exception + */ + public function setHttpAdapter(HttpAdapterInterface $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 string | array $settingsConfig - Hashmap that contains config values + * for the SDK to connect to SparkPost. If its a string we assume that + * its just they API Key. + * + * @throws \Exception + */ + public function setConfig($settingsConfig) + { + // if the config map is a string we should assume that its an api key + if (is_string($settingsConfig)) { + $settingsConfig = ['key' => $settingsConfig]; + } + + // Validate API key because its required + if (!isset($settingsConfig['key']) || !preg_match('/\S/', $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; + } + } + } +} diff --git a/lib/SparkPost/Transmission.php b/lib/SparkPost/Transmission.php index ae5d071..ff63722 100644 --- a/lib/SparkPost/Transmission.php +++ b/lib/SparkPost/Transmission.php @@ -1,128 +1,136 @@ 'content.attachments', - 'campaign'=>'campaign_id', - 'customHeaders'=>'content.headers', - 'description'=>'description', - 'from'=>'content.from', - 'html'=>'content.html', - 'inlineCss'=>'options.inline_css', - 'inlineImages'=>'content.inline_images', - 'metadata'=>'metadata', - 'recipientList'=>'recipients.list_id', - 'recipients'=>'recipients', - 'replyTo'=>'content.reply_to', - 'returnPath'=>'return_path', - 'rfc822'=>'content.email_rfc822', - 'sandbox'=>'options.sandbox', - 'startTime'=>'options.start_time', - 'subject'=>'content.subject', - 'substitutionData'=>'substitution_data', - 'template'=>'content.template_id', - 'text'=>'content.text', - 'trackClicks'=>'options.click_tracking', - 'trackOpens'=>'options.open_tracking', - 'transactional'=>'options.transactional', - 'useDraftTemplate'=>'use_draft_template' - ]; + /** + * Mapping for values passed into the send method to the values needed for the Transmission API. + * + * @var array + */ + protected static $parameterMappings = [ + 'attachments' => 'content.attachments', + 'campaign' => 'campaign_id', + 'customHeaders' => 'content.headers', + 'description' => 'description', + 'from' => 'content.from', + 'html' => 'content.html', + 'inlineCss' => 'options.inline_css', + 'inlineImages' => 'content.inline_images', + 'metadata' => 'metadata', + 'recipientList' => 'recipients.list_id', + 'recipients' => 'recipients', + 'replyTo' => 'content.reply_to', + 'returnPath' => 'return_path', + 'rfc822' => 'content.email_rfc822', + 'sandbox' => 'options.sandbox', + 'startTime' => 'options.start_time', + 'subject' => 'content.subject', + 'substitutionData' => 'substitution_data', + 'template' => 'content.template_id', + 'text' => 'content.text', + 'trackClicks' => 'options.click_tracking', + 'trackOpens' => 'options.open_tracking', + 'transactional' => 'options.transactional', + 'useDraftTemplate' => 'use_draft_template', + ]; - /** - * 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 - ]; + /** + * 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, + ]; - /** - * 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: - * 'attachments': array, - * 'campaign': string, - * 'customHeaders': array, - * 'description': string, - * 'from': string, - * 'html': string, - * 'inlineCss': boolean, - * 'inlineImages': array, - * 'metadata': array, - * 'recipientList': string, - * 'recipients': array, - * 'replyTo': string, - * 'rfc822': string, - * 'sandbox': boolean, - * 'startTime': string | \DateTime, - * 'subject': string, - * 'substitutionData': array, - * 'template': string, - * 'text': string, - * 'trackClicks': boolean, - * 'trackOpens': boolean, - * 'transactional': boolean, - * 'useDraftTemplate': boolean - * - * @param array $transmissionConfig - * @return array API repsonse represented as key-value pairs - */ - public function send( $transmissionConfig ) { - if(isset($transmissionConfig["startTime"]) && $transmissionConfig["startTime"] instanceof \DateTime) - { - $transmissionConfig["startTime"] = $transmissionConfig["startTime"]->format(\DateTime::ATOM); - } + /** + * 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: + * 'attachments': array, + * 'campaign': string, + * 'customHeaders': array, + * 'description': string, + * 'from': string, + * 'html': string, + * 'inlineCss': boolean, + * 'inlineImages': array, + * 'metadata': array, + * 'recipientList': string, + * 'recipients': array, + * 'replyTo': string, + * 'rfc822': string, + * 'sandbox': boolean, + * 'startTime': string | \DateTime, + * 'subject': string, + * 'substitutionData': array, + * 'template': string, + * 'text': string, + * 'trackClicks': boolean, + * 'trackOpens': boolean, + * 'transactional': boolean, + * 'useDraftTemplate': boolean + * + * @param array $transmissionConfig + * + * @return array API repsonse represented as key-value pairs + */ + public function send($transmissionConfig) + { + if (isset($transmissionConfig['startTime']) && $transmissionConfig['startTime'] instanceof \DateTime) { + $transmissionConfig['startTime'] = $transmissionConfig['startTime']->format(\DateTime::ATOM); + } - return $this->create( $transmissionConfig ); - } + return $this->create($transmissionConfig); + } - /** - * Method for retrieving information about all transmissions - * Wrapper method for a cleaner interface - * - * @param null|string $campaignID - * @param null|string $templateID - * @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; + /** + * Method for retrieving information about all transmissions + * Wrapper method for a cleaner interface. + * + * @param null|string $campaignID + * @param null|string $templateID + * + * @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 ); - } + return $this->get(null, $options); + } - /** - * 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); - } + /** + * 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); + } } - -?> diff --git a/test/unit/APIResourceExceptionTest.php b/test/unit/APIResourceExceptionTest.php index 5bb4758..8ae80de 100644 --- a/test/unit/APIResourceExceptionTest.php +++ b/test/unit/APIResourceExceptionTest.php @@ -1,36 +1,43 @@ message = 'Test message'; - $this->code = 400; - $this->description = 'Test description'; - $this->exception = new APIResponseException(NULL, 0, $this->message, $this->code, $this->description); - } +class APIResourceExceptionTest extends \PHPUnit_Framework_TestCase +{ + private $message; + private $code; + private $description; + private $exception; - public function testAPIMessage() { - $this->assertEquals($this->message, $this->exception->getAPIMessage()); - } + /** + * (non-PHPdoc). + * + * @before + * + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() + { + $this->message = 'Test message'; + $this->code = 400; + $this->description = 'Test description'; + $this->exception = new APIResponseException(null, 0, $this->message, $this->code, $this->description); + } - public function testAPICode() { - $this->assertEquals($this->code, $this->exception->getAPICode()); - } + public function testAPIMessage() + { + $this->assertEquals($this->message, $this->exception->getAPIMessage()); + } - public function testAPIDescription() { - $this->assertEquals($this->description, $this->exception->getAPIDescription()); - } + public function testAPICode() + { + $this->assertEquals($this->code, $this->exception->getAPICode()); + } + public function testAPIDescription() + { + $this->assertEquals($this->description, $this->exception->getAPIDescription()); + } } diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php index 8552815..67c37ab 100644 --- a/test/unit/APIResourceTest.php +++ b/test/unit/APIResourceTest.php @@ -1,184 +1,196 @@ 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() +use Mockery; + +class APIResourceTest extends \PHPUnit_Framework_TestCase +{ + 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('getStatusCode')->andReturn(200); - $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('getStatusCode')->andReturn(200); - $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('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); - - $this->assertEquals($testBody, $this->resource->get('test')); - } - - public function testGetCommaSeparated() { - $testBody = ['results'=>['my'=>'test']]; - $requestArray = [ - "param1" => "param1val", - "param2" => ["param2val1", "param2val2"] - ]; - $expectedGetParams = "param1=param1val¶m2=" . urlencode("param2val1,param2val2"); - - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with(matchesPattern("/.*\/test\?{$expectedGetParams}/"), 'GET', Mockery::type('array'), null)-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); - - $this->assertEquals($testBody, $this->resource->get('test', $requestArray)); - } - - public function testDelete() { - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with('/.*\/test/', 'DELETE', Mockery::type('array'), null)-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(''); - - $this->assertEquals(null, $this->resource->delete('test')); - } - - public function testAdapter404Exception() { - try { - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(404); - - $this->resource->get('test'); + public function testConstructorSetsUpSparkPostObject() + { + $this->sparkPostMock->newProp = 'new value'; + $this->assertEquals($this->sparkPostMock, self::$utils->getProperty($this->resource, 'sparkpost')); } - catch(\Exception $e) { - $this->assertRegExp('/.*resource does not exist.*/', $e->getMessage()); + + 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('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->create($testInput)); } - } - - public function testAdapter403Exception() { - $testBody = [ 'errors' => [ - [ - 'message' => 'Forbidden.' - ] - ]]; - try { - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(403); - $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody)); - - $this->resource->get('test'); + + 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('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->update('test', $testInput)); } - catch(\Exception $e) { - $this->assertRegExp('/Request forbidden/', $e->getMessage()); + + 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('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->get('test')); } - } - - public function testAdapter4XXException() { - try { - $testBody = ['errors'=>['my'=>'test']]; - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(400); - $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody)); - - $this->resource->get('test'); + + public function testGetCommaSeparated() + { + $testBody = ['results' => ['my' => 'test']]; + $requestArray = [ + 'param1' => 'param1val', + 'param2' => ['param2val1', 'param2val2'], + ]; + $expectedGetParams = 'param1=param1val¶m2='.urlencode('param2val1,param2val2'); + + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with(matchesPattern("/.*\/test\?{$expectedGetParams}/"), 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->get('test', $requestArray)); } - catch(\Exception $e) { - $this->assertRegExp('/Received bad response.*/', $e->getMessage()); + + public function testDelete() + { + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'DELETE', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(''); + + $this->assertEquals(null, $this->resource->delete('test')); } - } - public function testAdapter5XXException() { - try { - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - andThrow(new \Exception('Something went wrong.')); + public function testAdapter404Exception() + { + try { + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(404); + + $this->resource->get('test'); + } catch (\Exception $e) { + $this->assertRegExp('/.*resource does not exist.*/', $e->getMessage()); + } + } - $this->resource->get('test'); + public function testAdapter403Exception() + { + $testBody = ['errors' => [ + [ + 'message' => 'Forbidden.', + ], + ]]; + try { + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(403); + $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody)); + + $this->resource->get('test'); + } catch (\Exception $e) { + $this->assertRegExp('/Request forbidden/', $e->getMessage()); + } } - catch(\Exception $e) { - $this->assertRegExp('/Unable to contact.*API.*/', $e->getMessage()); + + public function testAdapter4XXException() + { + try { + $testBody = ['errors' => ['my' => 'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(400); + $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody)); + + $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/MessageEventTest.php b/test/unit/MessageEventTest.php index 48657e6..3d92412 100644 --- a/test/unit/MessageEventTest.php +++ b/test/unit/MessageEventTest.php @@ -2,70 +2,73 @@ namespace SparkPost; -use \Mockery; - +use Mockery; class MessageEventTest extends \PHPUnit_Framework_TestCase { - private $sparkPostMock; - private $sut; + private $sparkPostMock; + private $sut; - /** - * (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->sut = new MessageEvents($this->sparkPostMock); - } + /** + * (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->sut = new MessageEvents($this->sparkPostMock); + } - public function testDateTimeConversion() - { - $testBody = ['results' => ['my' => 'test']]; - $testFrom = new \DateTime("1978-08-27 04:05:02"); - $testFromStr = urlencode("1978-08-27T04:05"); - $testTo = new \DateTime("2016-04-04 19:00"); - $testToStr = urlencode("2016-04-04T19:00"); + public function testDateTimeConversion() + { + $testBody = ['results' => ['my' => 'test']]; + $testFrom = new \DateTime('1978-08-27 04:05:02'); + $testFromStr = urlencode('1978-08-27T04:05'); + $testTo = new \DateTime('2016-04-04 19:00'); + $testToStr = urlencode('2016-04-04T19:00'); - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with("/message-events/?from={$testFromStr}&to={$testToStr}", 'GET', Mockery::type('array'), null)-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with("/message-events/?from={$testFromStr}&to={$testToStr}", 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); - $this->assertEquals($testBody, $this->sut->search(["from" => $testFrom, "to" => $testTo])); - } + $this->assertEquals($testBody, $this->sut->search(['from' => $testFrom, 'to' => $testTo])); + } - public function testDocumentation() { - $testBody = ['results' => ['my' => 'test']]; - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with("/message-events/events/documentation", 'GET', Mockery::type('array'), null)-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + public function testDocumentation() + { + $testBody = ['results' => ['my' => 'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/message-events/events/documentation', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); - $this->assertEquals($testBody, $this->sut->documentation()); - } + $this->assertEquals($testBody, $this->sut->documentation()); + } - public function testSamples() { - $testBody = ['results' => ['my' => 'test']]; - $responseMock = Mockery::mock(); - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with("/message-events/events/samples?events=".urlencode("delivery,bounce"), 'GET', Mockery::type('array'), null)-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + public function testSamples() + { + $testBody = ['results' => ['my' => 'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/message-events/events/samples?events='.urlencode('delivery,bounce'), 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); - $this->assertEquals($testBody, $this->sut->samples(["delivery", "bounce"])); - } -} \ No newline at end of file + $this->assertEquals($testBody, $this->sut->samples(['delivery', 'bounce'])); + } +} diff --git a/test/unit/SendGridCompatibiility/EmailTest.php b/test/unit/SendGridCompatibiility/EmailTest.php index 2b86d7a..2846e9e 100644 --- a/test/unit/SendGridCompatibiility/EmailTest.php +++ b/test/unit/SendGridCompatibiility/EmailTest.php @@ -1,161 +1,178 @@ 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']); - } +use SparkPost\SendGridCompatibility\Email; - /** - * @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 = '

This is some 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()); - } +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 = '

This is some 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()); + } } - -?> diff --git a/test/unit/SparkPostTest.php b/test/unit/SparkPostTest.php index ed10b55..26563c3 100644 --- a/test/unit/SparkPostTest.php +++ b/test/unit/SparkPostTest.php @@ -1,4 +1,5 @@ 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); - } +class SparkPostTest extends \PHPUnit_Framework_TestCase +{ + private static $utils; + private $adapterMock; + /** @var SparkPost */ + private $resource; - public function tearDown(){ - Mockery::close(); - } + /** + * (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'); + }); - /** - * @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()); - } + $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 testSetConfigStringKey() { - $this->resource->setConfig('a key'); - $config = self::$utils->getProperty($this->resource, 'config'); - $this->assertEquals('a key', $config['key']); - } + public function tearDown() + { + Mockery::close(); + } - /** - * @expectedException Exception - * @expectedExceptionMessageRegExp /API key/ - */ - public function testSetBadConfig() { - $this->resource->setConfig(['not'=>'a key']); - } + /** + * @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()); + } + public function testSetConfigStringKey() + { + $this->resource->setConfig('a key'); + $config = self::$utils->getProperty($this->resource, 'config'); + $this->assertEquals('a key', $config['key']); + } - public function testGetHeaders() { - $results = $this->resource->getHttpHeaders(); - $this->assertEquals('a key', $results['Authorization']); - $this->assertEquals('application/json', $results['Content-Type']); - } + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /API key/ + */ + public function testSetBadConfig() + { + $this->resource->setConfig(['not' => 'a key']); + } - public function testSetUnwrapped() { - $results = $this->resource->setupUnwrapped('ASweetEndpoint'); - $this->assertEquals($this->resource->ASweetEndpoint, $results); - $this->assertInstanceOf('SparkPost\APIResource', $results); - $this->assertEquals('ASweetEndpoint', $results->endpoint); - } + 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); + } } -?> diff --git a/test/unit/TestUtils/ClassUtils.php b/test/unit/TestUtils/ClassUtils.php index 26d264c..b25ca56 100644 --- a/test/unit/TestUtils/ClassUtils.php +++ b/test/unit/TestUtils/ClassUtils.php @@ -1,56 +1,64 @@ class = new \ReflectionClass($fqClassName); + } - private $class; + /** + * 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); - public function __construct($fqClassName) { - $this->class = new \ReflectionClass($fqClassName); - } + return $method; + } - /** - * 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); - /** - * 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); - } + 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 ba29b3b..d606c53 100644 --- a/test/unit/TransmissionTest.php +++ b/test/unit/TransmissionTest.php @@ -1,106 +1,114 @@ 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('getStatusCode')->andReturn(200); - - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); - - $this->assertEquals($responseBody, $this->resource->send($body)); - } - - public function testSendDateTimeConversion() - { - $testStartTime = new \DateTime("2016-08-27 13:01:02", new \DateTimeZone("UTC")); - - $responseMock = Mockery::mock(); - $responseBody = ['results'=>'yay']; - $this->sparkPostMock->httpAdapter->shouldReceive('send')-> - once()-> - with('/.*\/transmissions/', 'POST', Mockery::type('array'), matchesPattern('/"start_time":"2016-08-27T13:01:02\+00:00"/'))-> - andReturn($responseMock); - $responseMock->shouldReceive('getStatusCode')->andReturn(200); - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); - - $this->assertEquals($responseBody, $this->resource->send(['startTime'=>$testStartTime])); - } - - 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('getStatusCode')->andReturn(200); - - $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('getStatusCode')->andReturn(200); - - $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('getStatusCode')->andReturn(200); - - $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); - - $this->assertEquals($responseBody, $this->resource->find('test')); - } - +use Mockery; + +class TransmissionTest extends \PHPUnit_Framework_TestCase +{ + 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('getStatusCode')->andReturn(200); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->send($body)); + } + + public function testSendDateTimeConversion() + { + $testStartTime = new \DateTime('2016-08-27 13:01:02', new \DateTimeZone('UTC')); + + $responseMock = Mockery::mock(); + $responseBody = ['results' => 'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions/', 'POST', Mockery::type('array'), matchesPattern('/"start_time":"2016-08-27T13:01:02\+00:00"/'))-> + andReturn($responseMock); + $responseMock->shouldReceive('getStatusCode')->andReturn(200); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->send(['startTime' => $testStartTime])); + } + + 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('getStatusCode')->andReturn(200); + + $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('getStatusCode')->andReturn(200); + + $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('getStatusCode')->andReturn(200); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->find('test')); + } } -?> diff --git a/test/unit/bootstrap.php b/test/unit/bootstrap.php index 0b851be..5a41f1c 100644 --- a/test/unit/bootstrap.php +++ b/test/unit/bootstrap.php @@ -1,3 +1,3 @@ + +require_once dirname(__FILE__).'/../../vendor/autoload.php';