summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authornornholdj <nornholdj@gmail.com>2014-10-31 15:10:06 -0400
committernornholdj <nornholdj@gmail.com>2014-10-31 15:10:06 -0400
commit68a7e8ec33f205a71107d924e0d244f5edac97a6 (patch)
tree7e47e9d41a8a3304e32eb0da6219c523f3e9c126
parentde407ac8bf029e85278eaeb683e6f86c6a11c097 (diff)
downloadphp-sparkpost-68a7e8ec33f205a71107d924e0d244f5edac97a6.zip
php-sparkpost-68a7e8ec33f205a71107d924e0d244f5edac97a6.tar.gz
php-sparkpost-68a7e8ec33f205a71107d924e0d244f5edac97a6.tar.bz2
MA-946 #time 3h 30m Revamped Transmission object to be stateless,
updated tests and examples.
-rw-r--r--composer.json3
-rw-r--r--examples/transmission/configuration_based.php37
-rw-r--r--examples/transmission/get_all_transmissions.php11
-rw-r--r--examples/transmission/get_transmission.php13
-rw-r--r--examples/transmission/mime_parts.php29
-rw-r--r--examples/transmission/rfc822.php33
-rw-r--r--examples/transmission/send_transmission_all_fields.php68
-rw-r--r--examples/transmission/send_transmission_all_fields_method_based.php45
-rw-r--r--examples/transmission/stored_recipients_inline_content.php30
-rw-r--r--examples/transmission/stored_template_send.php35
-rw-r--r--lib/MessageSystems/SparkPost.php (renamed from lib/MessageSystems/Configuration.php)2
-rw-r--r--lib/MessageSystems/Transmission.php549
-rw-r--r--lib/SparkPost.php30
-rw-r--r--test/unit/SparkPostTest.php (renamed from test/unit/ConfigurationTest.php)16
-rw-r--r--test/unit/TransmissionTest.php197
15 files changed, 236 insertions, 862 deletions
diff --git a/composer.json b/composer.json
index a2f5c40..5bfd63a 100644
--- a/composer.json
+++ b/composer.json
@@ -19,8 +19,7 @@
},
"autoload": {
"psr-4": {
- "MessageSystems\\": "lib/MessageSystems/",
- "SparkPost\\": "lib/"
+ "MessageSystems\\": "lib/MessageSystems/"
}
}
}
diff --git a/examples/transmission/configuration_based.php b/examples/transmission/configuration_based.php
index 374f446..366434f 100644
--- a/examples/transmission/configuration_based.php
+++ b/examples/transmission/configuration_based.php
@@ -2,29 +2,30 @@
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
- use SparkPost\SparkPost;
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
$key = 'YOURAPIKEY';
- $sdk = new SparkPost(['key'=>$key]);
-
- $transmission = $sdk->Transmission([
- "return_path"=>"return@example.com",
- "from"=>"From Envelope <from@example.com>",
- "html"=>"<p>Hello World!</p>",
- "text"=>"Hello World!",
- "subject"=>"Example Email",
- "recipients"=>[
- [
- "address"=>[
- "email"=>"john.doe@sample.com"
- ]
- ]
- ]
- ]);
+ SparkPost::setConfig(['key'=>$key]);
try {
- $results = $transmission->send();
+ $results = Transmission::send([
+ "returnPath"=>"return@example.com",
+ "from"=>"From Envelope <from@example.com>",
+ "html"=>"<p>Hello World!</p>",
+ "text"=>"Hello World!",
+ "subject"=>"Example Email",
+ "recipients"=>[
+ [
+ "address"=>[
+ "email"=>"jordan.nornhold@rackspace.messagesystems.com"
+ ]
+ ]
+ ]
+ ]);
echo 'Congrats you can use your SDK!';
+
+ var_dump(Transmission::$structure);
} catch (\Exception $exception) {
echo $exception->getMessage();
}
diff --git a/examples/transmission/get_all_transmissions.php b/examples/transmission/get_all_transmissions.php
index 9ffc2fd..1425e65 100644
--- a/examples/transmission/get_all_transmissions.php
+++ b/examples/transmission/get_all_transmissions.php
@@ -2,15 +2,14 @@
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
- use SparkPost\SparkPost;
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
- $key = 'YOURAPIKEY';
- $sdk = new SparkPost(['key'=>$key]);
-
- $transmission = $sdk->Transmission();
+ $key = 'YOURAPIKEY';
+ SparkPost::setConfig(['key'=>$key]);
try {
- $results = $transmission->all();
+ $results = Transmission::all();
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/get_transmission.php b/examples/transmission/get_transmission.php
index 86e9f0f..55cfe79 100644
--- a/examples/transmission/get_transmission.php
+++ b/examples/transmission/get_transmission.php
@@ -1,15 +1,14 @@
<?php
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
-
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
-
-$transmission = $sdk->Transmission();
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
+
+ $key = 'YOURAPIKEY';
+ SparkPost::setConfig(['key'=>$key]);
try {
- $results = $transmission->find('11860038888980495');
+ $results = Transmission::find('Your Transmission Id');
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/mime_parts.php b/examples/transmission/mime_parts.php
deleted file mode 100644
index 2b68b46..0000000
--- a/examples/transmission/mime_parts.php
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-namespace Examples\Transmisson;
-require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
-
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
-
-$transmission = $sdk->Transmission();
-
-$transmission->setReturnPath('return@example.com')
- ->setFrom('From Envelope <from@example.com>')
- ->addRecipient([
- 'address'=> [
- 'email'=> 'john.doe@sample.com'
- ]
- ])
- ->setSubject('Example Email')
- ->setHTMLContent('<p>Hello World!</p>')
- ->setTextContent('Hello World!');
-
-
-try {
- $results = $transmission->send();
- echo 'Congrats you can use your SDK!';
-} catch (\Exception $exception) {
- echo $exception->getMessage();
-}
-?> \ No newline at end of file
diff --git a/examples/transmission/rfc822.php b/examples/transmission/rfc822.php
index 58c62cc..e2b7353 100644
--- a/examples/transmission/rfc822.php
+++ b/examples/transmission/rfc822.php
@@ -1,26 +1,23 @@
<?php
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
-
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
-
-
-
-$transmission = $sdk->Transmission();
-
-$transmission->setReturnPath('return@example.com')
- ->addRecipient([
- 'address'=>[
- 'email'=>'john.doe@sample.com'
- ]
- ])
- ->setRfc822Content("Content-Type: text/plain\nFrom: From Envelope <from@example.com>\nSubject: Example Email\n\nHello World");
-
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
+
+ $key = 'YOURAPIKEY';
+ SparkPost::setConfig(['key'=>$key]);
try {
- $results = $transmission->send();
+ $results = Transmission::send([
+ 'recipients'=>[
+ [
+ 'address'=>[
+ 'email'=>'john.doe@sample.com'
+ ]
+ ]
+ ],
+ 'rfc822Part'=>"Content-Type: text/plain\nFrom: From Envelope <from@example.com>\nSubject: Example Email\n\nHello World"
+ ]);
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/send_transmission_all_fields.php b/examples/transmission/send_transmission_all_fields.php
index 5aec6b8..6064e67 100644
--- a/examples/transmission/send_transmission_all_fields.php
+++ b/examples/transmission/send_transmission_all_fields.php
@@ -1,45 +1,41 @@
<?php
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
+use MessageSystems\SparkPost;
+use MessageSystems\Transmission;
$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
+SparkPost::setConfig(['key'=>$key]);
-
-
-$transmission = $sdk->Transmission([
- "campaign"=>"my-campaign",
- "metadata"=>[
- "sample_campaign"=>true,
- "type"=>"these are custom fields"
- ],
- "substitutionData"=>[
- "name"=>"Test Name"
- ],
- "description"=>"my description",
- "return_path"=>"return@example.com",
- "replyTo"=>"reply@test.com",
- "headers"=>[
- "X-Custom-Header"=>"Sample Custom Header"
- ],
- "openTracking"=>false,
- "clickTracking"=>false,
- "from"=>"From Envelope <from@example.com>",
- "html"=>"<p>Hello World! Your name is: {{name}}</p>",
- "text"=>"Hello World!",
- "subject"=>"Example Email: {{name}}",
- "recipients"=>[
- [
- "address"=>[
- "email"=>"john.doe@sample.com"
- ]
- ]
- ]
-]);
-
-try {
- $results = $transmission->send();
+try{
+ $results = Transmission::send([
+ "campaign"=>"my-campaign",
+ "metadata"=>[
+ "sample_campaign"=>true,
+ "type"=>"these are custom fields"
+ ],
+ "substitutionData"=>[
+ "name"=>"Test Name"
+ ],
+ "description"=>"my description",
+ "replyTo"=>"reply@test.com",
+ "headers"=>[
+ "X-Custom-Header"=>"Sample Custom Header"
+ ],
+ "openTracking"=>false,
+ "clickTracking"=>false,
+ "from"=>"From Envelope <from@example.com>",
+ "html"=>"<p>Hello World! Your name is: {{name}}</p>",
+ "text"=>"Hello World!",
+ "subject"=>"Example Email: {{name}}",
+ "recipients"=>[
+ [
+ "address"=>[
+ "email"=>"john.doe@sample.com"
+ ]
+ ]
+ ]
+ ]);
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/send_transmission_all_fields_method_based.php b/examples/transmission/send_transmission_all_fields_method_based.php
deleted file mode 100644
index 0f3314b..0000000
--- a/examples/transmission/send_transmission_all_fields_method_based.php
+++ /dev/null
@@ -1,45 +0,0 @@
-<?php
-namespace Examples\Transmisson;
-require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
-
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
-
-
-
-$transmission = $sdk->Transmission();
-
-$transmission->setCampaign('my campaign')
- ->setMetadata([
- "sample_campaign"=>"true",
- "type"=>"test type meta data"
- ])
- ->setSubstitutionData([
- "name"=>"Test Name"
- ])
- ->setDescription('My Description')
- ->setReturnPath('return@example.com')
- ->setReplyTo('reply@test.com')
- ->setContentHeaders([
- "X-Custom-Header"=>"Sample Custom Header"
- ])
- ->disableOpenTracking()
- ->disableClickTracking()
- ->setFrom('From Envelope <from@example.com>')
- ->addRecipient([
- "address"=> [
- "email"=>"john.doe@sample.com"
- ]
- ])
- ->setSubject('Example Email: {{name}}')
- ->setHTMLContent('<p>Hello World! Your name is: {{name}}</p>')
- ->setTextContent('Hello World!');
-
-
-try {
- $results = $transmission->send();
- echo 'Congrats you can use your SDK!';
-} catch (\Exception $exception) {
- echo $exception->getMessage();
-} \ No newline at end of file
diff --git a/examples/transmission/stored_recipients_inline_content.php b/examples/transmission/stored_recipients_inline_content.php
index 8dccdda..a545122 100644
--- a/examples/transmission/stored_recipients_inline_content.php
+++ b/examples/transmission/stored_recipients_inline_content.php
@@ -1,25 +1,25 @@
<?php
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
+
+ $key = 'YOURAPIKEY';
+ SparkPost::setConfig(['key'=>$key]);
+
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
+try {
+ $results = Transmission::send([
+ "campaign"=>"my-campaign",
+ "from"=>"From Envelope <from@example.com>",
+ "html"=>"<p>Hello World! Your name is: {{name}}</p>",
+ "text"=>"Hello World!",
+ "subject"=>"Example Email: {{name}}",
+ "recipientList"=>'Example List'
+ ]);
-$transmission = $sdk->Transmission();
-
-$transmission->setCampaign('my campaign')
- ->setReturnPath('return@example.com')
- ->setFrom('From Envelope <from@example.com>')
- ->useRecipientList('Example List')
- ->setSubject('Example Email')
- ->setHTMLContent('<p>Hello World!</p>')
- ->setTextContent('Hello World!');
-
-try {
- $results = $transmission->send();
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/examples/transmission/stored_template_send.php b/examples/transmission/stored_template_send.php
index 7a0e784..4d58c70 100644
--- a/examples/transmission/stored_template_send.php
+++ b/examples/transmission/stored_template_send.php
@@ -1,27 +1,24 @@
<?php
namespace Examples\Transmisson;
require_once (dirname(__FILE__).'/../bootstrap.php');
-use SparkPost\SparkPost;
-
-
-$key = 'YOURAPIKEY';
-$sdk = new SparkPost(['key'=>$key]);
-
-
-
-$transmission = $sdk->Transmission();
-
-$transmission->setReturnPath('return@example.com')
- ->setFrom('From Envelope <from@example.com>')
- ->addRecipient([
- "address"=>[
- "email"=>"john.doe@sample.com"
- ]
- ])
- ->useStoredTemplate('my-template');
+ use MessageSystems\SparkPost;
+ use MessageSystems\Transmission;
+
+ $key = 'YOURAPIKEY';
+ SparkPost::setConfig(['key'=>$key]);
try {
- $results = $transmission->send();
+ $results = Transmission::send([
+ "from"=>"From Envelope <from@example.com>",
+ "recipients"=>[
+ [
+ "address"=>[
+ "email"=>"john.doe@sample.com"
+ ]
+ ]
+ ],
+ "template"=>"my-template"
+ ]);
echo 'Congrats you can use your SDK!';
} catch (\Exception $exception) {
echo $exception->getMessage();
diff --git a/lib/MessageSystems/Configuration.php b/lib/MessageSystems/SparkPost.php
index d44cab3..dfb4295 100644
--- a/lib/MessageSystems/Configuration.php
+++ b/lib/MessageSystems/SparkPost.php
@@ -1,7 +1,7 @@
<?php
namespace MessageSystems;
-class Configuration {
+class SparkPost {
private static $config;
private static $defaults = [
diff --git a/lib/MessageSystems/Transmission.php b/lib/MessageSystems/Transmission.php
index 2b4b9cc..af8b722 100644
--- a/lib/MessageSystems/Transmission.php
+++ b/lib/MessageSystems/Transmission.php
@@ -7,117 +7,67 @@ use GuzzleHttp\Exception\RequestException;
* @desc SDK interface for managing transmissions
*/
class Transmission {
- private $model;
- private $config;
- private $request;
+ private static $request;
+
+ private static $parameterMappings = [
+ 'campaign'=>'campaign_id',
+ 'metadata'=>'metadata',
+ 'substitutionData'=>'substitution_data',
+ 'description'=>'description',
+ 'returnPath'=>'return_path',
+ 'replyTo'=>'content.reply_to',
+ 'subject'=>'content.subject',
+ 'from'=>'content.from',
+ 'html'=>'content.html',
+ 'text'=>'content.text',
+ 'rfc822Part'=>'content.email_rfc822',
+ 'headers'=>'content.headers',
+ 'recipients'=>'recipients',
+ 'recipientList'=>'recipients.list_id',
+ 'template'=>'content.template_id',
+ 'openTracking'=>'options.open_tracking',
+ 'clickTracking'=>'options.click_tracking',
+ 'useDraftTemplate'=>'use_draft_template'
+ ];
- private $parameterMappings = [
- 'campaign'=>'setCampaign',
- 'metadata'=>'setMetadata',
- 'substitutionData'=>'setSubstitutionData',
- 'description'=>'setDescription',
- 'returnPath'=>'setReturnPath',
- 'replyTo'=>'setReplyTo',
- 'subject'=>'setSubject',
- 'from'=>'setFrom',
- 'html'=>'setHTMLContent',
- 'text'=>'setTextContent',
- 'rfc822Part'=>'setRfc822Content',
- 'headers'=>'setContentHeaders',
- 'recipients'=>'addRecipients',
- 'recipientList'=>'useRecipientList',
- 'template'=>'useStoredTemplate',
- 'openTracking'=>1,
- 'clickTracking'=>1,
- 'useDraftTemplate'=>1
+ private static $structure = [
+ 'return_path'=>"default@sparkpostmail.com",
+ 'content'=>[
+ 'html'=>null,
+ 'text'=>null,
+ 'email_rfc822'=>null
+ ],
+ 'options'=>[
+ 'open_tracking'=>null,
+ 'click_tracking'=>null
+ ]
];
/**
- * @desc Sets up an object for managaging Transmissions
- *
- * Please note that key values that can be specified are:
- * - campaign
- * - metadata
- * - substitutionData
- * - description
- * - returnPath
- * - replyTo
- * - subject
- * - from
- * - html
- * - text
- * - rfc822Part
- * - headers
- * - recipients
- * - recipientList
- * - template
- * - openTracking
- * - clickTracking
- * - useDraftTemplate
- *
- * @param array $params (optional) key-value pairs representing the Transmission's settings
+ * @desc Ensure that this class cannot be instansiated
*/
- public function __construct($params = null) {
- $this->config = Configuration::getConfig();
-
- $this->config['baseUrl'] = '/api/' . $this->config['version'] . '/transmissions';
-
- $this->request = new Client();
- $this->model = [
- 'campaign_id'=>null,
- 'metadata'=>null,
- 'substitution_data'=>null,
- 'description'=>null,
- 'return_path'=>null,
- 'content' => [
- 'reply_to'=>null,
- 'subject'=>null,
- 'from'=>null,
- 'html'=>null,
- 'text'=>null,
- 'email_rfc822'=>null,
- 'headers'=>null,
- 'template_id'=>null,
- 'use_draft_template'=>false,
- ],
- 'options'=>[
- 'open_tracking'=>true,
- 'click_tracking'=>true
- ],
- 'recipients'=>null
- ];
-
- //if params were supplied, set their values on the model
- if(!is_null($params)) {
- foreach($params as $key=>$value) {
- $this->setMappedValue($key, $value);
- }
+ private function __construct() {}
+
+ private static function getHttpClient() {
+ if(!isset(self::$request)) {
+ self::$request = new Client();
}
+ return self::$request;
}
+
/**
* @desc Private Method helper to reference parameter mappings and set the right value for the right parameter
*/
- private function setMappedValue ($mapKey, $value) {
+ private static function setMappedValue (&$model, $mapKey, $value) {
//get mapping
- if(array_key_exists($mapKey, $this->parameterMappings)) {
- // if its an option, set the value directly
- if(in_array($mapKey, ['openTracking', 'clickTracking', 'useDraftTemplate'])) {
- switch ($mapKey) {
- case 'openTracking':
- $this->model['options']['open_tracking'] = $value;
- break;
- case 'clickTracking':
- $this->model['options']['click_tracking'] = $value;
- break;
- case 'useDraftTemplate':
- $this->model['content']['use_draft_template'] = $value;
- break;
- }
- } else { //otherwise call the method to set the value
- $method = $this->parameterMappings[$mapKey];
- $this->$method($value);
+ if(array_key_exists($mapKey, self::$parameterMappings)) {
+ $temp = &$model;
+ $path = explode('.', self::$parameterMappings[$mapKey]);
+ foreach( $path as $key ) {
+ $temp = &$temp[$key];
}
+ $temp = $value;
} //ignore anything we don't have a mapping for
}
@@ -126,8 +76,9 @@ class Transmission {
*
* @return string base url for the transmissions API
*/
- private function getBaseUrl() {
- return $this->config['protocol'] . '://' . $this->config['host'] . ($this->config['port'] ? ':' . $this->config['port'] : '') . $this->config['baseUrl'];
+ private static function getBaseUrl($config) {
+ $baseUrl = '/api/' . $config['version'] . '/transmissions';
+ return $config['protocol'] . '://' . $config['host'] . ($config['port'] ? ':' . $config['port'] : '') . $baseUrl;
}
/**
@@ -139,12 +90,22 @@ class Transmission {
*
* @return array API repsonse represented as key-value pairs
*/
- public function send() {
+ public static function send($transmissionConfig) {
+ $hostConfig = SparkPost::getConfig();
+ $request = self::getHttpClient();
+
+ //create model from $transmissionConfig
+ $model = self::$structure;
+ foreach($transmissionConfig as $key=>$value) {
+ self::setMappedValue($model, $key, $value);
+ }
+
+ //send the request
try {
- $response = $this->request->post($this->getBaseUrl(), [
- 'json'=>$this->model,
- "headers"=>['authorization' => $this->config['key']],
- "verify"=>$this->config['strictSSL']
+ $response = $request->post(self::getBaseUrl($hostConfig), [
+ 'json'=>$model,
+ "headers"=>['authorization' => $hostConfig['key']],
+ "verify"=>$hostConfig['strictSSL']
]);
return $response->json();
} catch (RequestException $exception) {
@@ -153,6 +114,7 @@ class Transmission {
} catch (\Exception $exception) {
throw new \Exception('Unable to contact Transmissions API: '. $exception->getMessage());
}
+
}
/**
@@ -166,18 +128,21 @@ class Transmission {
* @param string $transmissionID (optional) string Transmission ID of specific Transmission to retrieve
* @return array Result set of transmissions found
*/
- private function fetch ($transmissionID = null) {
+ private static function fetch ($transmissionID = null) {
//figure out the url
- $url = $this->getBaseUrl();
+ $hostConfig = SparkPost::getConfig();
+ $url = self::getBaseUrl($hostConfig);
if (!is_null($transmissionID)){
$url .= '/'.$transmissionID;
}
+ $request = self::getHttpClient();
+
//make request
- try {
- $response = $this->request->get($url, [
- "headers"=>['authorization' => $this->config['key']],
- "verify"=>$this->config['strictSSL']
+ try {
+ $response = $request->get($url, [
+ "headers"=>['authorization' => $hostConfig['key']],
+ "verify"=>$hostConfig['strictSSL']
]);
return $response->json();
} catch (RequestException $exception) {
@@ -198,8 +163,8 @@ class Transmission {
*
* @return array result Set of transmissions
*/
- public function all() {
- return $this->fetch();
+ public static function all() {
+ return self::fetch();
}
/**
@@ -209,362 +174,8 @@ class Transmission {
* @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->fetch($transmissionID);
- }
-
- /**
- * @desc Method for adding metadata to a Transmission
- *
- * Metadata for a Transmission are key-value pairs that will be made available
- * in the webhooks payloads as identifiers for events that are associated with a particular Transmission
- *
- * Please note that metadata can be applied at the recipient level, and any recipient level metadata takes
- * precedence over Transmission level metadata
- *
- * @param array $meta Key-value pairs to be applied to the Transmission level metadata
- * @return \MessageSystems\Transmission Object
- */
- public function setMetadata ($meta) {
- $this->model['metadata'] = $meta;
- return $this;
- }
-
- /**
- * @desc Method for adding substitution data to a Transmission
- *
- * Substitution data are key-value pairs that are provided
- * to the subsititution engine. The substitution engine scans
- * parts of the content for substitution syntax '{{ }}' and
- * substitutes the values of a given key where the syntax was found
- *
- * Please note that recipient level substitution data takes precedence
- * over any Transmission level substitution data
- *
- * @param array $subs Key-value pairs of substitution data to be applied at the Transmission level
- * @return \MessageSystems\Transmission Object
- */
- public function setSubstitutiondata ($subs) {
- $this->model['substitution_data'] = $subs;
- return $this;
- }
-
- /**
- * @desc Method for adding a campaign to a Transmission
- *
- * Campaigns are logical groupings of related Transmissions
- *
- * For example, I may have multiple mailings related to my Labor Day Sale,
- * and would apply the campaign 'LaborDay2k14' to all Transmissions associated with
- * said sale.
- *
- * It is also worth noting that Transmissions flagged with a given campaign will be available
- * for filtering in both webhooks, as well as the Reporting UI/Metrics API
- *
- * @param string $campaignID Campaign Name, with a max length of 64 bytes
- * @return \MessageSystems\Transmission Object
- */
- public function setCampaign ($campaignID) {
- $this->model['campaign_id'] = $campaignID;
- return $this;
- }
-
- /**
- * @desc Method for adding a description to a Transmission
- *
- * Descriptions are arbitrary strings used further describe what a specific
- * Transmission was/is for the user's benefit.
- *
- * Please note that the only place currently that description is exposed is via
- * the Transmissions API, and the fetch method of this SDK
- *
- * @param string $description Description of a Transmission with a max length of 1024 bytes
- * @return \MessageSystems\Transmission Object
- */
- public function setDescription ($description) {
- $this->model['description'] = $description;
- return $this;
- }
-
- /**
- * @desc Method for adding a Return Path to a Transmission
- *
- * A return path is an email address supplied to a Transmission where any
- * bounces generated 'in the wild' will be sent back to this address. Return
- * Path is used at the server level.
- *
- * Please note that this field can be specified in recipients if using
- * VERP (Variable Envelope Return Path), which will give each recipient
- * a unique envelope MAIL FROM
- *
- * @param string $returnPath Return Path to be applied to a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function setReturnPath ($returnPath) {
- $this->model['return_path'] = $returnPath;
- return $this;
- }
-
- /**
- * @desc Method for adding a Reply To to a Transmission
- *
- * A Reply To is very similar to Return Path, but instead of
- * being used by servers, Reply To is used by humans. When a human
- * in their mail client clicks the reply button, the To field of that email
- * will be populated with the email address provided in the Reply To field
- *
- * @param string $replyTo Reply To to be applied to a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function setReplyTo ($replyTo) {
- $this->model['content']['reply_to'] = $replyTo;
- return $this;
- }
-
- /**
- * @desc Method for adding a Subject to a Transmission
- *
- * Sets the subject line of content for a given Transmission
- *
- * @param string $subject Subject to be applied to a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function setSubject ($subject) {
- $this->model['content']['subject'] = $subject;
- return $this;
- }
-
- /**
- * @desc Method for adding a From to a Transmission
- *
- * Sets the from header of content for a given Transmission.
- * Please note that there are three ways to provide the from header
- *
- * 1. From is a string, like 'person@example.com'
- * 2. From is an object with a key email, like '{email: 'person@example.com'}'
- * 3. From is an object with a email and name key, like '{name: 'Jane Doe', email: 'person@example.com'}'
- *
- * Using the third form of From will result is a 'pretty' From headers, like From: Jane Doe <person@example.com>
- *
- * @param mixed $fromField array/string From header to be applied to a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function setFrom ($fromField) {
- $this->model['content']['from'] = $fromField;
- return $this;
- }
-
- /**
- * @desc Method for adding HTML content to a Transmission
- *
- * Used for generating a Transmission using inline HTML content
- * Please note that you cannot specify HTML content if you've also
- * provided a stored template (useStoredTemplate)
- *
- * You cannot specify HTML content if you've also provided RFC-822
- * encoded content
- *
- * @param string $html HTML Content to be used when the Transmission is sent
- * @return \MessageSystems\Transmission Object
- */
- public function setHTMLContent ($html) {
- $this->model['content']['html'] = $html;
- return $this;
- }
-
- /**
- * @desc Method for adding Plain Text content to a Transmission
- *
- * Use for generating a Transmission using line Plain Text content
- * Please note that you cannot specify Plain Text content if you've also
- * provided a stored template (useStoredTemplate)
- *
- * You cannot specify Plain Text content if you've also provided RFC-822
- * encoded content
- *
- * @param string $plaintext Plain Text Content to be used when the Transmission is sent
- * @return \MessageSystems\Transmission Object
- */
- public function setTextContent ($plaintext) {
- $this->model['content']['text'] = $plaintext;
- return $this;
- }
-
- /**
- * @desc Method for adding RFC 822 encoded content to a Transmission
- *
- * Used for generating a Transmission using inline encoded content
- * Please note that you cannot specify RFC-822 content if you've also
- * provided a stored template (useStoredTemplate)
- *
- * You cannot specify RFC-822 content if you've already provided HTML
- * or Plain Text content
- *
- * @param string $rfc RFC-822 encoded content to be used when the Transmission is sent
- * @return \MessageSystems\Transmission Object
- */
- public function setRfc822Content ($rfc) {
- $this->model['content']['email_rfc822'] = $rfc;
- return $this;
- }
-
- /**
- * @desc Method for adding custom headers to the content of a Transmission
- *
- * Can contain any key-value pairs _except_
- * - Subject
- * - From
- * - To
- * - Reply-To
- *
- * @param array $headers Key-value pairs of headers to add to the content of a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function setContentHeaders (array $headers) {
- $this->model['content']['headers'] = $headers;
- return $this;
- }
-
- /**
- * @desc Method for adding a single recipient to a Transmission
- *
- * Used for supplying inline recipients for a Transmission. Emails will be generated
- * for each recipient in the list.
- *
- * The only required field in the recipient definition is address, all others are optional
- * If using multiple recipients, iteratively call this method, or use addRecipients
- *
- * If you call useRecipientList after using this method, recipient value will be overridden
- *
- * @param array $recipient An associative array of recipient data to send a Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function addRecipient (array $recipient) {
- if(!is_array($this->model['recipients'])) {
- $this->model['recipients'] = [];
- }
- array_push($this->model['recipients'], $recipient);
- return $this;
- }
-
- /**
- * @desc Method for adding multiple recipients at once to a Transmission
- *
- * Used for supplying inline recipients for a Transmission. Emails will be generated
- * for each recipient in the list.
- *
- * The only required field in the recipient definition is address, all others are optional
- *
- * If you call useRecipientList after using this method, recipients value will be overridden
- *
- * @param array $recipients An array of associative arrays containing recipient data
- * @return \MessageSystems\Transmission Object
- */
- public function addRecipients (array $recipients) {
- if(!is_array($this->model['recipients'])) {
- $this->model['recipients'] = [];
- }
- $this->model['recipients'] = array_merge($this->model['recipients'], $recipients);
- return $this;
- }
-
- /**
- * @desc Method for specifying a stored recipient list
- *
- * Used for supplying a Transmission with recipients from a stored recipient list
- * Please note that you cannot use a stored recipient list _and_ inline recipients (addRecipient)
- * If you use addRecipient or addRecipients after using this method, recipientList value
- * will be overridden
- *
- * @param string $recipientList Name of the recipient list to be used during Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function useRecipientList ($recipientList) {
- // Resetting the data type as it could've been an array of inline recipients
- $this->model['recipients'] = [];
- $this->model['recipients']['list_id'] = $recipientList;
- return $this;
- }
-
- /**
- * @desc Method for specifying a stored template
- *
- * Used for supplying a Transmission with content from a stored template
- * Please note that you cannot use a stored template if you've also added inline
- * HTML, Plain Text, or RFC-822 encoded content
- *
- * @param string $templateID Name of template to be used during Transmission
- * @return \MessageSystems\Transmission Object
- */
- public function useStoredTemplate ($templateID) {
- $this->model['content']['template_id'] = $templateID;
- return $this;
- }
-
- /**
- * @desc Method for enabling click tracking for a given transmission
- * By default, click tracking is enabled for a transmission
- *
- * @return \MessageSystems\Transmission Object
- */
- public function enableClickTracking () {
- $this->model['options']['click_tracking'] = true;
- return $this;
- }
-
- /**
- * @desc Method for disabling click tracking for a given transmission
- * By default, click tracking is enabled for a transmission
- *
- * @return \MessageSystems\Transmission Object
- */
- public function disableClickTracking () {
- $this->model['options']['click_tracking'] = false;
- return $this;
- }
-
- /**
- * @desc Method for enabling open tracking for a given transmission
- * By default, open tracking is enabled for a transmission
- *
- * @return \MessageSystems\Transmission Object
- */
- public function enableOpenTracking () {
- $this->model['options']['open_tracking'] = true;
- return $this;
- }
-
- /**
- * @desc Method for disabling open tracking for a given transmission
- * By default, open tracking is enabled for a transmission
- *
- * @return \MessageSystems\Transmission Object
- */
- public function disableOpenTracking () {
- $this->model['options']['open_tracking'] = false;
- return $this;
- }
-
- /**
- * @desc Method for allowing the sending of a draft version of a template with a transmission
- * By default, you cannot send a draft version of a stored template
- *
- * @return \MessageSystems\Transmission Object
- */
- public function useDraftTemplate () {
- $this->model['content']['use_draft_template'] = true;
- return $this;
- }
-
- /**
- * @desc Method for disallowing the sending of a draft version of a template with a transmission
- * By default, you cannot send a draft version of a stored template
- *
- * @return \MessageSystems\Transmission Object
- */
- public function usePublishedTemplate () {
- $this->model['content']['use_draft_template'] = false;
- return $this;
+ public static function find($transmissionID) {
+ return self::fetch($transmissionID);
}
}
diff --git a/lib/SparkPost.php b/lib/SparkPost.php
deleted file mode 100644
index 539b0db..0000000
--- a/lib/SparkPost.php
+++ /dev/null
@@ -1,30 +0,0 @@
-<?php
-namespace SparkPost;
-
-use MessageSystems\Transmission;
-use MessageSystems\Configuration;
-
-class SparkPost {
-
- public $transmission;
-
- /**
- * @desc Sets up the config for the sdk suite
- * @param array $globalOpts
- */
- public function __construct(array $globalOpts) {
- Configuration::setConfig($globalOpts);
- }
-
- /**
- * @desc Creates a new Transmission object and returns it.
- * @param array $options Transmission constructor options
- * @see \MessageSystems\Transmission
- * @return \MessageSystems\Transmission
- */
- public function Transmission(array $options = null) {
- $this->transmission = new Transmission($options);
- return $this->transmission;
- }
-}
-?> \ No newline at end of file
diff --git a/test/unit/ConfigurationTest.php b/test/unit/SparkPostTest.php
index 52c60be..218cb6e 100644
--- a/test/unit/ConfigurationTest.php
+++ b/test/unit/SparkPostTest.php
@@ -1,15 +1,15 @@
<?php
namespace SparkPost\Test;
-use MessageSystems\Configuration;
+use MessageSystems\SparkPost;
-class ConfigurationTest extends \PHPUnit_Framework_TestCase {
+class SparkPostTest extends \PHPUnit_Framework_TestCase {
/**
* @desc Ensures that the configuration class is not instantiable.
*/
public function testConstructorCannotBeCalled() {
- $class = new \ReflectionClass('\MessageSystems\Configuration');
+ $class = new \ReflectionClass('\MessageSystems\SparkPost');
$this->assertFalse($class->isInstantiable());
}
@@ -20,7 +20,7 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase {
* @expectedExceptionMessage No configuration has been provided
*/
public function testGetConfigEmptyException() {
- Configuration::getConfig();
+ SparkPost::getConfig();
}
/**
@@ -29,7 +29,7 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase {
* @expectedExceptionMessage You must provide an API key
*/
public function testSetConfigAPIKeyNotSetException() {
- Configuration::setConfig(['something'=>'other than an API Key']);
+ SparkPost::setConfig(['something'=>'other than an API Key']);
}
/**
@@ -38,16 +38,16 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase {
* @expectedExceptionMessage You must provide an API key
*/
public function testSetConfigAPIKeyEmptyException() {
- Configuration::setConfig(['key'=>'']);
+ SparkPost::setConfig(['key'=>'']);
}
/**
* @desc Tests overridable values are set while invalid values are ignored
*/
public function testSetConfigMultipleValuesAndGetConfig() {
- Configuration::setConfig(['key'=>'lala', 'version'=>'v8', 'port'=>1024, 'someOtherValue'=>'fakeValue']);
+ SparkPost::setConfig(['key'=>'lala', 'version'=>'v8', 'port'=>1024, 'someOtherValue'=>'fakeValue']);
- $testConfig = Configuration::getConfig();
+ $testConfig = SparkPost::getConfig();
$this->assertEquals('lala', $testConfig['key']);
$this->assertEquals('v8', $testConfig['version']);
$this->assertEquals(1024, $testConfig['port']);
diff --git a/test/unit/TransmissionTest.php b/test/unit/TransmissionTest.php
index 3d2f6d3..8da2645 100644
--- a/test/unit/TransmissionTest.php
+++ b/test/unit/TransmissionTest.php
@@ -2,7 +2,7 @@
namespace SparkPost\Test;
use MessageSystems\Transmission;
-use MessageSystems\Configuration;
+use MessageSystems\SparkPost;
use GuzzleHttp\Subscriber\Mock;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Stream\Stream;
@@ -14,7 +14,6 @@ use GuzzleHttp\Stream\Stream;
*/
class TransmissionTest extends \PHPUnit_Framework_TestCase {
- private $transmission = null;
private $client = null;
private static function getMethod($name) {
@@ -24,58 +23,22 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase {
return $method;
}
- private static function getProperty($obj, $name) {
- $class = new \ReflectionClass('\MessageSystems\Transmission');
- $property = $class->getProperty($name);
- $property->setAccessible(true);
- return $property->getValue($obj);
- }
-
- /**
- * Dynamically dereferences an array for a path list provided by the $dereferenceArray
- * @param array $array Nested array to be dereferenced
- * @param array $dereferenceArray list of key values to dereference
- * @return mixed
- */
- private static function dereference($array, $dereferenceArray) {
- $value = $array;
- foreach($dereferenceArray as $derefValue) {
- $value = $value[$derefValue];
- }
- return $value;
- }
-
/**
* (non-PHPdoc)
* @before
* @see PHPUnit_Framework_TestCase::setUp()
*/
public function setUp() {
- Configuration::setConfig(['key'=>'blah']);
- $this->transmission = new Transmission();
- $this->client = self::getProperty($this->transmission, 'request'); //so we can bootstrap api responses
+ SparkPost::setConfig(['key'=>'blah']);
+ $this->client = self::getMethod('getHttpClient')->invoke(null); //so we can bootstrap api responses
}
/**
- * @desc Constructor will not set invalid keys
+ * @desc Ensures that the configuration class is not instantiable.
*/
- public function testConstructorWillNotSetInvalidKeys() {
- $transmission = new Transmission(['blah'=>'blah']);
- $this->assertArrayNotHasKey('blah', $this->getProperty($transmission, 'model'));
- }
-
- /**
- *
- */
- public function testConstructorWillSetValidKeys() {
- $transmission = new Transmission(['description'=>'this is a test', 'text'=>'test txt', 'openTracking'=>false, 'clickTracking'=>false, 'useDraftTemplate'=>false, 'recipientList'=>'my recip list']);
- $this->assertArrayHasKey('description', $this->getProperty($transmission, 'model'));
- $this->assertEquals('this is a test', $this->getProperty($transmission, 'model')['description']);
- $this->assertEquals('test txt', $this->getProperty($transmission, 'model')['content']['text']);
- $this->assertEquals(false, $this->getProperty($transmission, 'model')['options']['open_tracking']);
- $this->assertEquals(false, $this->getProperty($transmission, 'model')['options']['click_tracking']);
- $this->assertEquals(false, $this->getProperty($transmission, 'model')['content']['use_draft_template']);
- $this->assertEquals('my recip list', $this->getProperty($transmission, 'model')['recipients']['list_id']);
+ public function testConstructorCannotBeCalled() {
+ $class = new \ReflectionClass('\MessageSystems\Transmission');
+ $this->assertFalse($class->isInstantiable());
}
/**
@@ -84,7 +47,8 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase {
public function testAllWithGoodResponse() {
$mock = new Mock([new Response(200, [], Stream::factory('{"results":[{"test":"This is a test"}, {"test":"two"}]}'))]);
$this->client->getEmitter()->attach($mock);
- $this->assertEquals(["results"=>[['test'=>'This is a test'], ['test'=>'two']]], $this->transmission->all());
+ $this->assertEquals(["results"=>[['test'=>'This is a test'], ['test'=>'two']]], Transmission::all());
+ $this->client->getEmitter()->detach($mock);
}
/**
@@ -93,40 +57,40 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase {
public function testFindWithGoodResponse() {
$mock = new Mock([new Response(200, [], Stream::factory('{"results":[{"test":"This is a test"}]}'))]);
$this->client->getEmitter()->attach($mock);
- $this->assertEquals(["results"=>[['test'=>'This is a test']]], $this->transmission->find('someId'));
+ $this->assertEquals(["results"=>[['test'=>'This is a test']]], Transmission::find('someId'));
+ $this->client->getEmitter()->detach($mock);
}
/**
- * @expectedException Exception
- * @expectedExceptionMessage The specified Transmission ID does not exist
+ *
*/
public function testFindWith404Response() {
$mock = new Mock([new Response(404, [])]);
$this->client->getEmitter()->attach($mock);
- $this->transmission->find('someId');
+ try {
+ Transmission::find('someId');
+ } catch (\Exception $e) {
+ $this->assertEquals('The specified Transmission ID does not exist', $e->getMessage());
+ } finally {
+ $this->client->getEmitter()->detach($mock);
+ }
}
/**
- * @expectedException Exception
- * @expectedExceptionMessage Received bad response from Transmission API: 400
+ *
*/
public function testFindWithOtherBadResponse() {
$mock = new Mock([new Response(400, [])]);
$this->client->getEmitter()->attach($mock);
- $this->transmission->find('someId');
+ try {
+ Transmission::find('someId');
+ } catch (\Exception $e) {
+ $this->assertEquals('Received bad response from Transmission API: 400', $e->getMessage());
+ } finally {
+ $this->client->getEmitter()->detach($mock);
+ }
}
-// /**
-// * @expectedException Exception
-// * @expectedExceptionMessageRegExp /Unable to contact Transmissions API:.* /
-// */
-// public function testFindForUnableToContactServer() {
-// $mock = new Mock([new Response(500)]);
-// $this->client->getEmitter()->attach($mock);
-// $this->transmission->find('someId');
-// }
-
-
/**
*
*/
@@ -134,109 +98,24 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase {
$body = ["result"=>["transmission_id"=> "11668787484950529"], "status"=>["message"=> "ok","code"=> "1000"]];
$mock = new Mock([new Response(200, [], Stream::factory(json_encode($body)))]);
$this->client->getEmitter()->attach($mock);
- $this->assertEquals($body, $this->transmission->send());
+ $this->assertEquals($body, Transmission::send(['text'=>'awesome email']));
+ $this->client->getEmitter()->detach($mock);
}
/**
- * @expectedException Exception
- * @expectedExceptionMessage This is a fake error
+ *
*/
- public function testFindForRequestException() {
+ public function testSendForRequestException() {
$body = ['errors'=>['This is a fake error']];
$mock = new Mock([new Response(400, [], Stream::factory(json_encode($body)))]);
$this->client->getEmitter()->attach($mock);
- $this->transmission->send();
- }
-
-// /**
-// * @expectedException Exception
-// * @expectedExceptionMessageRegExp /Unable to contact Traissions API: \w+/
-// */
-// public function testSendForUnableToContactServer() {
-// $mock = new Mock([new Response(500, [])]);
-// $this->client->getEmitter()->attach($mock);
-// $this->transmission->send();
-// }
-
-
- public function setProvider() {
- return [
- ['setMetadata', ['metadata']],
- ['setSubstitutionData', ['substitution_data']],
- ['setCampaign', ['campaign_id']],
- ['setDescription', ['description']],
- ['setReturnPath', ['return_path']],
- ['setReplyTo', ['content', 'reply_to']],
- ['setSubject', ['content', 'subject']],
- ['setFrom', ['content', 'from']],
- ['setHTMLContent', ['content', 'html']],
- ['setTextContent', ['content', 'text']],
- ['setRfc822Content', ['content', 'email_rfc822']],
-
- ['useRecipientList', ['recipients', 'list_id']],
- ['useStoredTemplate', ['content', 'template_id']]
- ];
- }
-
- /**
- * @dataProvider setProvider
- */
- public function testSimpleSetFunctions($setterFunction, $dereference) {
- $testValue = 'test';
- $returnValue = $this->transmission->$setterFunction($testValue);
- $this->assertInstanceOf('MessageSystems\Transmission', $returnValue);
- $this->assertSame($this->transmission, $returnValue);
- $this->assertEquals($testValue, self::dereference(self::getProperty($this->transmission, 'model'), $dereference));
- }
-
- public function complexSetFunctionsProvider() {
- return [
- ['addRecipient', ['recipients'], ['address'=>'testRecipient@example.com'], [['address'=>'testRecipient@example.com']]],
- ['addRecipients', ['recipients'], [
- ['address'=>'testRecipient1@example.com'],
- ['address'=>'testRecipient2@example.com'],
- ['address'=>'testRecipient3@example.com']
- ],
- [
- ['address'=>'testRecipient1@example.com'],
- ['address'=>'testRecipient2@example.com'],
- ['address'=>'testRecipient3@example.com']
- ]],
- ['setContentHeaders', ['content', 'headers'], ['x-head'=>'somevalue'], ['x-head'=>'somevalue']],
- ];
- }
-
- /**
- * @dataProvider complexSetFunctionsProvider
- */
- public function testComplexSetFunctions($setterFunction, $dereference, $setValue, $expected) {
- $returnValue = $this->transmission->$setterFunction($setValue);
- $this->assertInstanceOf('MessageSystems\Transmission', $returnValue);
- $this->assertSame($this->transmission, $returnValue);
- $this->assertEquals($expected, self::dereference(self::getProperty($this->transmission, 'model'), $dereference));
- }
-
-
-
- public function optionsProvider() {
- return [
- ['enableClickTracking', ['options', 'click_tracking'], true],
- ['disableClickTracking', ['options', 'click_tracking'], false],
- ['enableOpenTracking', ['options', 'open_tracking'], true],
- ['disableOpenTracking', ['options', 'open_tracking'], false],
- ['useDraftTemplate', ['content', 'use_draft_template'], true],
- ['usePublishedTemplate', ['content', 'use_draft_template'], false]
- ];
- }
-
- /**
- * @dataProvider optionsProvider
- */
- public function testOptionsFunctions($setterFunction, $dereference, $expected) {
- $returnValue = $this->transmission->$setterFunction();
- $this->assertInstanceOf('MessageSystems\Transmission', $returnValue);
- $this->assertSame($this->transmission, $returnValue);
- $this->assertEquals($expected, self::dereference(self::getProperty($this->transmission, 'model'), $dereference));
+ try {
+ Transmission::send(['text'=>'awesome email']);
+ } catch (\Exception $e) {
+ $this->assertEquals('["This is a fake error"]', $e->getMessage());
+ } finally {
+ $this->client->getEmitter()->detach($mock);
+ }
}
}