Code cleanup!

This commit is contained in:
Travis Swientek 2013-07-25 15:42:06 -07:00
parent 24ddfa0e54
commit 4e43786949
9 changed files with 211 additions and 294 deletions

View File

@ -2,46 +2,52 @@
namespace Mailgun\Connection; namespace Mailgun\Connection;
require dirname(__DIR__) . '/globals.php'; require dirname(__DIR__) . '/Globals.php';
use Guzzle\Http\Client as Guzzle; use Guzzle\Http\Client as Guzzle;
use Mailgun\MailgunClient; use Mailgun\MailgunClient;
use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\GenericHTTPError; use Mailgun\Connection\Exceptions\GenericHTTPError;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
class HttpBroker{ class HttpBroker{
private $apiKey; private $apiKey;
protected $workingDomain; protected $workingDomain;
protected $debug; protected $debugMode;
protected $mgClient;
public function __construct($apiKey, $workingDomain, $debugMode = false){
protected $apiEndpoint = API_ENDPOINT;
protected $apiVersion = API_VERSION;
protected $apiUser = API_USER;
protected $sdkVersion = SDK_VERSION;
protected $sdkUserAgent = SDK_USER_AGENT;
public function __construct($apiKey, $domain, $debug = false){
$this->apiKey = $apiKey; $this->apiKey = $apiKey;
$this->workingDomain = $domain; $this->workingDomain = $workingDomain;
$this->debug = $debug; $this->debugMode = $debugMode;
if($this->debug){
$this->client = new Guzzle('https://api.ninomail.com/' . $this->apiVersion . '/', array('ssl.certificate_authority' => false)); /*
* !!WARNING, REMOVE DEBUG CODE BEFORE GOING GA!!
*/
if($this->debugMode){
$this->mgClient = new Guzzle('https://api.ninomail.com/' . API_VERSION . '/', array('ssl.certificate_authority' => false));
} }
else{ else{
$this->client = new Guzzle('https://' . $this->apiEndpoint . '/' . $this->apiVersion . '/'); $this->mgClient = new Guzzle('https://' . API_ENDPOINT . '/' . API_VERSION . '/');
} }
$this->client->setDefaultOption('curl.options', array('CURLOPT_FORBID_REUSE' => true));
$this->client->setDefaultOption('auth', array ($this->apiUser, $this->apiKey)); /*
$this->client->setDefaultOption('exceptions', true); * !!WARNING, REMOVE DEBUG CODE BEFORE GOING GA!!
$this->client->setUserAgent($this->sdkUserAgent . '/' . $this->sdkVersion); */
$this->mgClient->setDefaultOption('curl.options', array('CURLOPT_FORBID_REUSE' => true));
$this->mgClient->setDefaultOption('auth', array (API_USER, $this->apiKey));
$this->mgClient->setDefaultOption('exceptions', true);
$this->mgClient->setUserAgent(SDK_USER_AGENT . '/' . SDK_VERSION);
} }
public function postRequest($endpointUrl, $postData = array(), $files = array()){ public function postRequest($endpointUrl, $postData = array(), $files = array()){
$request = $this->client->post($endpointUrl, array(), $postData); $request = $this->mgClient->post($endpointUrl, array(), $postData);
if(isset($files["attachment"])){ if(isset($files["attachment"])){
foreach($files["attachment"] as $attachment){ foreach($files["attachment"] as $attachment){
@ -52,88 +58,58 @@ class HttpBroker{
foreach($files["inline"] as $attachment){ foreach($files["inline"] as $attachment){
$request->addPostFile("inline", $attachment); $request->addPostFile("inline", $attachment);
} }
} }
$response = $request->send(); $response = $request->send();
$httpResponeCode = $response->getStatusCode(); return $this->responseHandler($response);
if($httpResponeCode === 200){
$jsonResponseData = $response->json();
foreach ($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
elseif($httpStatusCode == 401){
throw new InvalidCredentials("Your credentials are incorrect.");
}
else{
throw new GenericHTTPError("A generic HTTP Error has occurred! Check your network connection and try again.");
return false;
}
$result->http_response_code = $httpResponeCode;
return $result;
} }
public function getRequest($endpointUrl, $queryString = array()){ public function getRequest($endpointUrl, $queryString = array()){
$request = $this->client->get($endpointUrl, $queryString); $request = $this->mgClient->get($endpointUrl, $queryString);
$response = $request->send(); $response = $request->send();
$httpResponeCode = $response->getStatusCode(); return $this->responseHandler($response);
if($httpResponeCode === 200){
$jsonResponseData = $response->json();
foreach ($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
elseif($httpStatusCode == 401){
throw new InvalidCredentials("Your credentials are incorrect.");
}
else{
throw new GenericHTTPError("A generic HTTP Error has occurred! Check your network connection and try again.");
return false;
}
$result->http_response_code = $httpResponeCode;
return $result;
} }
public function deleteRequest($endpointUrl){ public function deleteRequest($endpointUrl){
$request = $this->client->delete($endpointUrl); $request = $this->mgClient->delete($endpointUrl);
$response = $request->send(); $response = $request->send();
$httpResponeCode = $response->getStatusCode(); return $this->responseHandler($response);
if($httpResponeCode === 200){
$jsonResponseData = $response->json();
foreach ($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
elseif($httpStatusCode == 401){
throw new InvalidCredentials("Your credentials are incorrect.");
}
else{
throw new GenericHTTPError("A generic HTTP Error has occurred! Check your network connection and try again.");
return false;
}
$result->http_response_code = $httpResponeCode;
return $result;
} }
public function putRequest($endpointUrl, $queryString){ public function putRequest($endpointUrl, $queryString){
$request = $this->client->put($endpointUrl, $queryString); $request = $this->mgClient->put($endpointUrl, $queryString);
$response = $request->send(); $response = $request->send();
$httpResponeCode = $response->getStatusCode(); return $this->responseHandler($response);
}
public function responseHandler($responseObj){
$httpResponeCode = $responseObj->getStatusCode();
if($httpResponeCode === 200){ if($httpResponeCode === 200){
$jsonResponseData = $response->json(); $jsonResponseData = $responseObj->json();
foreach ($jsonResponseData as $key => $value){ foreach ($jsonResponseData as $key => $value){
$result->$key = $value; $result->http_response_body->$key = $value;
} }
} }
elseif($httpStatusCode == 400){
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
elseif($httpStatusCode == 401){ elseif($httpStatusCode == 401){
throw new InvalidCredentials("Your credentials are incorrect."); throw new InvalidCredentials(EXCEPTION_INVALID_CREDENTIALS);
}
elseif($httpStatusCode == 401){
throw new GenericHTTPError(EXCEPTION_INVALID_CREDENTIALS);
}
elseif($httpStatusCode == 404){
throw new MissingEndpoint(EXCEPTION_MISSING_ENDPOINT);
} }
else{ else{
throw new GenericHTTPError("A generic HTTP Error has occurred! Check your network connection and try again."); throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR);
return false; return false;
} }
$result->http_response_code = $httpResponeCode; $result->http_response_code = $httpResponeCode;
return $result; return $result;
} }
public function returnWorkingDomain(){ public function returnWorkingDomain(){
return $this->workingDomain; return $this->workingDomain;
} }

View File

@ -17,8 +17,8 @@ class MailgunClient{
* classes created from here. * classes created from here.
*/ */
public function __construct($apiKey, $domain, $debug = false){ public function __construct($apiKey, $workingDomain, $debugMode = false){
$this->httpBroker = new HttpBroker($apiKey, $domain, $debug); $this->httpBroker = new HttpBroker($apiKey, $workingDomain, $debugMode);
} }
/* /*
@ -29,18 +29,23 @@ class MailgunClient{
public function Messages(){ public function Messages(){
return new Messages($this->httpBroker); return new Messages($this->httpBroker);
} }
public function Unsubscribes(){ public function Unsubscribes(){
return new Unsubscribes($this->httpBroker); return new Unsubscribes($this->httpBroker);
} }
public function Complaints(){ public function Complaints(){
return new Complaints($this->httpBroker); return new Complaints($this->httpBroker);
} }
public function Bounces(){ public function Bounces(){
return new Bounces($this->httpBroker); return new Bounces($this->httpBroker);
} }
public function Stats(){ public function Stats(){
return new Stats($this->httpBroker); return new Stats($this->httpBroker);
} }
public function Logs(){ public function Logs(){
return new Logs($this->httpBroker); return new Logs($this->httpBroker);
} }

View File

@ -1,12 +1,9 @@
<?PHP <?PHP
//BatchMessage.php - Extends the Message class and provides continuous recipient addition.
namespace Mailgun\Messages; namespace Mailgun\Messages;
use Mailgun\Exceptions\NoDomainsConfigured; use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Exceptions\HTTPError; use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
class BatchMessage extends MessageBuilder{ class BatchMessage extends MessageBuilder{
@ -25,7 +22,7 @@ class BatchMessage extends MessageBuilder{
if($this->toRecipientCount == 1000){ if($this->toRecipientCount == 1000){
//If autoSend is off, do things here. //If autoSend is off, do things here.
if($this->autoSend == false){ if($this->autoSend == false){
throw new HTTPError("Too many recipients for API"); throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the to field.");
} }
else{ else{
$this->sendMessage(); $this->sendMessage();
@ -38,13 +35,13 @@ class BatchMessage extends MessageBuilder{
} }
} }
$addr = $name . " <" . $address . ">"; $compiledAddress = $name . " <" . $address . ">";
if(isset($this->message["to"])){ if(isset($this->message["to"])){
array_push($this->message["to"], $addr); array_push($this->message["to"], $compiledAddress);
} }
else{ else{
$this->message["to"] = array($addr); $this->message["to"] = array($compiledAddress);
} }
$attributes["id"] = $this->toRecipientCount; $attributes["id"] = $this->toRecipientCount;
$this->batchRecipientAttributes["$address"] = $attributes; $this->batchRecipientAttributes["$address"] = $attributes;
@ -57,20 +54,26 @@ class BatchMessage extends MessageBuilder{
$message = $this->message; $message = $this->message;
$files = $this->files; $files = $this->files;
} }
if(array_key_exists("from", $message) && if(!array_key_exists("from", $message)){
array_key_exists("to", $message) && throw new MissingRequiredMIMEParameters("You are missing the from parameter for your message.");
array_key_exists("subject", $message) &&
(array_key_exists("text", $message) || array_key_exists("html", $message))){
$this->message["recipient-variables"] = json_encode($this->batchRecipientAttributes);
$response = $this->httpBroker->postRequest($this->endpointUrl, $message, $files);
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
unset($this->message["to"]);
return $response;
}
else{
throw new MissingRequiredMIMEParameters("You are missing the minimum parameters to send a message.");
} }
} elseif(!array_key_exists("to", $message)){
throw new MissingRequiredMIMEParameters("You are missing a recipient for your message.");
}
elseif(!array_key_exists("subject", $message)){
throw new MissingRequiredMIMEParameters("You are missing the subject of the message.");
}
elseif((!array_key_exists("text", $message) && !array_key_exists("html", $message))){
throw new MissingRequiredMIMEParameters("You are missing the body of the message.");
}
else{
$this->message["recipient-variables"] = json_encode($this->batchRecipientAttributes);
$response = $this->httpBroker->postRequest($this->endpointUrl, $message, $files);
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
unset($this->message["to"]);
return $response;
}
}
} }
?> ?>

View File

@ -1,37 +1,26 @@
<?PHP <?PHP
/*
* Message.php - Message builder for creating a message object. Pass the message object to the client to send the message.
*/
namespace Mailgun\Messages; namespace Mailgun\Messages;
use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Messages\Expcetions\InvalidParameter; use Mailgun\Messages\Expcetions\InvalidParameter;
use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Messages\Expcetions\InvalidParameterType; use Mailgun\Messages\Expcetions\InvalidParameterType;
class MessageBuilder extends Messages{ class MessageBuilder extends Messages{
protected $message; protected $message = array();
protected $files; protected $files = array();
protected $sanitized; protected $sanitized;
protected $toRecipientCount; protected $toRecipientCount = 0;
protected $ccRecipientCount; protected $ccRecipientCount = 0;
protected $bccRecipientCount; protected $bccRecipientCount = 0;
protected $attachmentCount; protected $attachmentCount = 0;
protected $campaignIdCount; protected $campaignIdCount = 0;
protected $customOptionCount; protected $customOptionCount = 0;
protected $httpBroker; protected $httpBroker;
public function __construct($httpBroker){ public function __construct($httpBroker){
parent::__construct($httpBroker); parent::__construct($httpBroker);
$this->message = array();
$this->files = array();
$this->toRecipientCount = 0;
$this->ccRecipientCount = 0;
$this->bccRecipientCount = 0;
$this->attachmentCount = 0;
$this->campaignIdCount = 0;
$this->customOptionCount = 0;
$this->httpBroker = $httpBroker; $this->httpBroker = $httpBroker;
} }
@ -46,16 +35,16 @@ class MessageBuilder extends Messages{
} }
} }
if(isset($name)){ if(isset($name)){
$addr = $name . " <" . $address . ">"; $compiledAddress = $name . " <" . $address . ">";
} }
else{ else{
$addr = $address; $compiledAddress = $address;
} }
if(isset($this->message["to"])){ if(isset($this->message["to"])){
array_push($this->message["to"], $addr); array_push($this->message["to"], $compiledAddress);
} }
else{ else{
$this->message["to"] = array($addr); $this->message["to"] = array($compiledAddress);
} }
$this->toRecipientCount++; $this->toRecipientCount++;
return true; return true;
@ -76,16 +65,16 @@ class MessageBuilder extends Messages{
} }
} }
if(isset($name)){ if(isset($name)){
$addr = $name . " <" . $address . ">"; $compiledAddress = $name . " <" . $address . ">";
} }
else{ else{
$addr = $address; $compiledAddress = $address;
} }
if(isset($this->message["cc"])){ if(isset($this->message["cc"])){
array_push($this->message["cc"], $addr); array_push($this->message["cc"], $compiledAddress);
} }
else{ else{
$this->message["cc"] = array($addr); $this->message["cc"] = array($compiledAddress);
} }
$this->ccRecipientCount++; $this->ccRecipientCount++;
return true; return true;
@ -94,6 +83,7 @@ class MessageBuilder extends Messages{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the cc field."); throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the cc field.");
} }
} }
public function addBccRecipient($address, $attributes){ public function addBccRecipient($address, $attributes){
if($this->bccRecipientCount < 1000){ if($this->bccRecipientCount < 1000){
if(is_array($attributes)){ if(is_array($attributes)){
@ -105,16 +95,16 @@ class MessageBuilder extends Messages{
} }
} }
if(isset($name)){ if(isset($name)){
$addr = $name . " <" . $address . ">"; $compiledAddress = $name . " <" . $address . ">";
} }
else{ else{
$addr = $address; $compiledAddress = $address;
} }
if(isset($this->message["bcc"])){ if(isset($this->message["bcc"])){
array_push($this->message["bcc"], $addr); array_push($this->message["bcc"], $compiledAddress);
} }
else{ else{
$this->message["bcc"] = array($addr); $this->message["bcc"] = array($compiledAddress);
} }
$this->bccRecipientCount++; $this->bccRecipientCount++;
return true; return true;
@ -123,6 +113,7 @@ class MessageBuilder extends Messages{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the bcc field."); throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the bcc field.");
} }
} }
public function setFromAddress($address, $attributes){ public function setFromAddress($address, $attributes){
if(isset($attributes)){ if(isset($attributes)){
if(is_array($attributes)){ if(is_array($attributes)){
@ -138,14 +129,15 @@ class MessageBuilder extends Messages{
} }
} }
if(isset($name)){ if(isset($name)){
$addr = $name . " <" . $address . ">"; $compiledAddress = $name . " <" . $address . ">";
} }
else{ else{
$addr = $address; $compiledAddress = $address;
} }
$this->message['from'] = $addr; $this->message['from'] = $compiledAddress;
return true; return true;
} }
public function setSubject($data = NULL){ public function setSubject($data = NULL){
if($data == NULL || $data == ""){ if($data == NULL || $data == ""){
$data = " "; $data = " ";
@ -153,6 +145,7 @@ class MessageBuilder extends Messages{
$this->message['subject'] = $data; $this->message['subject'] = $data;
return true; return true;
} }
public function addCustomHeader($headerName, $data){ public function addCustomHeader($headerName, $data){
if(!preg_match("/^h:/i", $headerName)){ if(!preg_match("/^h:/i", $headerName)){
$headerName = "h:" . $headerName; $headerName = "h:" . $headerName;
@ -160,6 +153,7 @@ class MessageBuilder extends Messages{
$this->message[$headerName] = array($data); $this->message[$headerName] = array($data);
return true; return true;
} }
public function setTextBody($data){ public function setTextBody($data){
if($data == NULL || $data == ""){ if($data == NULL || $data == ""){
$data = " "; $data = " ";
@ -167,6 +161,7 @@ class MessageBuilder extends Messages{
$this->message['text'] = $data; $this->message['text'] = $data;
return true; return true;
} }
public function setHtmlBody($data){ public function setHtmlBody($data){
if($data == NULL || $data == ""){ if($data == NULL || $data == ""){
$data = " "; $data = " ";
@ -174,6 +169,7 @@ class MessageBuilder extends Messages{
$this->message['html'] = $data; $this->message['html'] = $data;
return true; return true;
} }
public function addAttachment($data){ public function addAttachment($data){
if(preg_match("/^@/", $data)){ if(preg_match("/^@/", $data)){
if(isset($this->files["attachment"])){ if(isset($this->files["attachment"])){
@ -188,6 +184,7 @@ class MessageBuilder extends Messages{
throw new InvalidParameter("Attachments must be passed with an \"@\" preceding the file path. Web resources not supported."); throw new InvalidParameter("Attachments must be passed with an \"@\" preceding the file path. Web resources not supported.");
} }
} }
public function addInlineImage($data){ public function addInlineImage($data){
if(preg_match("/^@/", $data)){ if(preg_match("/^@/", $data)){
if(isset($this->files['inline'])){ if(isset($this->files['inline'])){
@ -203,6 +200,7 @@ class MessageBuilder extends Messages{
throw new InvalidParameter("Inline images must be passed with an \"@\" preceding the file path. Web resources not supported."); throw new InvalidParameter("Inline images must be passed with an \"@\" preceding the file path. Web resources not supported.");
} }
} }
public function setTestMode($data){ public function setTestMode($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){ if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes"; $data = "yes";
@ -213,6 +211,7 @@ class MessageBuilder extends Messages{
$this->message['o:testmode'] = $data; $this->message['o:testmode'] = $data;
return true; return true;
} }
public function addCampaignId($data){ public function addCampaignId($data){
if($this->campaignIdCount < 3){ if($this->campaignIdCount < 3){
if(isset($this->message['o:campaign'])){ if(isset($this->message['o:campaign'])){
@ -228,6 +227,7 @@ class MessageBuilder extends Messages{
throw new TooManyParameters("You've exceeded the maximum (3) campaigns for a single message."); throw new TooManyParameters("You've exceeded the maximum (3) campaigns for a single message.");
} }
} }
public function setDkim($data){ public function setDkim($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){ if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes"; $data = "yes";
@ -238,6 +238,7 @@ class MessageBuilder extends Messages{
$this->message["o:dkim"] = $data; $this->message["o:dkim"] = $data;
return true; return true;
} }
public function setOpenTracking($data){ public function setOpenTracking($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){ if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes"; $data = "yes";
@ -247,7 +248,8 @@ class MessageBuilder extends Messages{
} }
$this->message['o:tracking-opens'] = $data; $this->message['o:tracking-opens'] = $data;
return true; return true;
} }
public function setClickTracking($data){ public function setClickTracking($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){ if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes"; $data = "yes";
@ -258,6 +260,7 @@ class MessageBuilder extends Messages{
$this->message['o:tracking-clicks'] = $data; $this->message['o:tracking-clicks'] = $data;
return true; return true;
} }
public function setDeliveryTime($timeDate, $timeZone = NULL){ public function setDeliveryTime($timeDate, $timeZone = NULL){
if(isset($timeZone)){ if(isset($timeZone)){
$timeZoneObj = new \DateTimeZone("$timeZone"); $timeZoneObj = new \DateTimeZone("$timeZone");
@ -271,6 +274,7 @@ class MessageBuilder extends Messages{
$this->message['o:deliverytime'] = $formattedTimeDate; $this->message['o:deliverytime'] = $formattedTimeDate;
return true; return true;
} }
public function addCustomData($customName, $data){ public function addCustomData($customName, $data){
if(is_array($data)){ if(is_array($data)){
$jsonArray = json_encode($data); $jsonArray = json_encode($data);
@ -282,6 +286,7 @@ class MessageBuilder extends Messages{
} }
} }
public function addCustomOption($optionName, $data){ public function addCustomOption($optionName, $data){
if(!preg_match("/^o:/i", $optionName)){ if(!preg_match("/^o:/i", $optionName)){
$optionName = "o:" . $optionName; $optionName = "o:" . $optionName;
@ -295,9 +300,11 @@ class MessageBuilder extends Messages{
return true; return true;
} }
} }
public function getMessage(){ public function getMessage(){
return $this->message; return $this->message;
} }
public function getFiles(){ public function getFiles(){
return $this->files; return $this->files;
} }

View File

@ -1,16 +1,11 @@
<?php <?php
/*
* Message.php - Message builder for creating a message object. Pass the message object to the client to send the message.
*/
namespace Mailgun\Messages; namespace Mailgun\Messages;
use Mailgun\Messages\MessageBuilder;
use Mailgun\Messages\BatchMessage; use Mailgun\Messages\BatchMessage;
use Mailgun\Messages\MessageBuilder;
use Mailgun\Messages\Exceptions\TooManyParameters; use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Messages\Expcetions\InvalidParameter;
use Mailgun\Messages\Expcetions\InvalidParameterType;
class Messages{ class Messages{
@ -23,20 +18,27 @@ class Messages{
$this->workingDomain = $this->httpBroker->returnWorkingDomain(); $this->workingDomain = $this->httpBroker->returnWorkingDomain();
$this->endpointUrl = $this->workingDomain . "/messages"; $this->endpointUrl = $this->workingDomain . "/messages";
} }
public function sendMessage($message = array(), $files = array()){ public function sendMessage($message = array(), $files = array()){
if(count($message) < 1){ if(count($message) < 1){
$message = $this->message; $message = $this->message;
$files = $this->files; $files = $this->files;
} }
if(array_key_exists("from", $message) && if(!array_key_exists("from", $message)){
array_key_exists("to", $message) && throw new MissingRequiredMIMEParameters("You are missing the from parameter for your message.");
array_key_exists("subject", $message) && }
(array_key_exists("text", $message) || array_key_exists("html", $message))){ elseif(!array_key_exists("to", $message)){
$response = $this->httpBroker->postRequest($this->endpointUrl, $message, $files); throw new MissingRequiredMIMEParameters("You are missing a recipient for your message.");
return $response; }
} elseif(!array_key_exists("subject", $message)){
throw new MissingRequiredMIMEParameters("You are missing the subject of the message.");
}
elseif((!array_key_exists("text", $message) && !array_key_exists("html", $message))){
throw new MissingRequiredMIMEParameters("You are missing the body of the message.");
}
else{ else{
throw new MissingRequiredMIMEParameters("You are missing the minimum parameters to send a message."); $response = $this->httpBroker->postRequest($this->endpointUrl, $message, $files);
return $response;
} }
} }
@ -48,6 +50,7 @@ class Messages{
public function MessageBuilder(){ public function MessageBuilder(){
return new MessageBuilder($this->httpBroker); return new MessageBuilder($this->httpBroker);
} }
public function BatchMessage($autoSend = true){ public function BatchMessage($autoSend = true){
return new BatchMessage($this->httpBroker, $autoSend); return new BatchMessage($this->httpBroker, $autoSend);
} }

View File

@ -8,4 +8,11 @@ const SDK_VERSION = "0.1";
const SDK_USER_AGENT = "mailgun-sdk-php"; const SDK_USER_AGENT = "mailgun-sdk-php";
const DEFAULT_TIME_ZONE = "UTC"; const DEFAULT_TIME_ZONE = "UTC";
//Exception Messages
const EXCEPTION_INVALID_CREDENTIALS = "Your credentials are incorrect.";
const EXCEPTION_GENERIC_HTTP_ERROR = "An HTTP Error has occurred! Check your network connection and try again.";
const EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS = "The parameters passed to the API were invalid. This might be a bug! Notify support@mailgun.com.";
const EXCEPTION_MISSING_ENDPOINT = "The endpoint you've tried to access does not exist. This might be a bug! Notify support@mailgun.com.";
?> ?>

View File

@ -22,184 +22,106 @@ class TestBroker extends HttpBroker{
public function postRequest($endpointUrl, $postData = array(), $files = array()){ public function postRequest($endpointUrl, $postData = array(), $files = array()){
if(preg_match("/\/messages$/", $endpointUrl)){ if(preg_match("/\/messages$/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Queued. Thank you.","id": "<20111114174239.25659.5817@samples.mailgun.org>"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/unsubscribes$/", $endpointUrl)){ elseif(preg_match("/\/unsubscribes$/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Address has been added to the unsubscribes table","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/complaints$/", $endpointUrl)){ elseif(preg_match("/\/complaints$/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
//$jsonResponseData = json_encode('{"message": "Address has been added to the unsubscribes table","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/bounces$/", $endpointUrl)){ elseif(preg_match("/\/bounces$/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
//$jsonResponseData = json_encode('{"message": "Address has been added to the unsubscribes table","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
else{ else{
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
} }
return $result; return $result;
} }
public function getRequest($endpointUrl, $queryString = array()){ public function getRequest($endpointUrl, $queryString = array()){
if($endpointUrl == "domains"){ if($endpointUrl == "domains"){
$httpResponseCode = 200; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_decode('{"total_count": 1,"items": [{"created_at": "Wed, 10 Jul 2013 19:26:52 GMT","smtp_login": "postmaster@samples.mailgun.org","name": "samples.mailgun.org","smtp_password": "4rtqo4p6rrx9"}]}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){ elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Unsubscribe event has been removed","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/unsubscribes/", $endpointUrl)){ elseif(preg_match("/\/unsubscribes/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/complaints/", $endpointUrl)){ elseif(preg_match("/\/complaints/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/bounces/", $endpointUrl)){ elseif(preg_match("/\/bounces/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/stats/", $endpointUrl)){ elseif(preg_match("/\/stats/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/log/", $endpointUrl)){ elseif(preg_match("/\/log/", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
if($httpResponseCode === 200){ }
foreach($jsonResponseData as $key => $value){ else{
$result->$key = $value; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
}
$result->http_response_code = $httpResponseCode;
} }
return $result; return $result;
} }
public function deleteRequest($endpointUrl){ public function deleteRequest($endpointUrl){
if($endpointUrl == "domains"){ if($endpointUrl == "domains"){
$httpResponseCode = 200; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_decode('asdfasdfasdf');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){ elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Unsubscribe event has been removed","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/complaints\//", $endpointUrl)){ elseif(preg_match("/\/complaints\//", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Unsubscribe event has been removed","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/bounces\//", $endpointUrl)){ elseif(preg_match("/\/bounces\//", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Unsubscribe event has been removed","address": "ev@mailgun.net"}');
if($httpResponseCode === 200){
foreach($jsonResponseData as $key => $value){
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
elseif(preg_match("/\/tags\//", $endpointUrl)){ elseif(preg_match("/\/tags\//", $endpointUrl)){
$httpResponseCode = "200"; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_encode('{"message": "Unsubscribe event has been removed","address": "ev@mailgun.net"}'); }
if($httpResponseCode === 200){ else{
foreach($jsonResponseData as $key => $value){ return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
return $result; return $result;
} }
public function putRequest($endpointUrl, $queryString){ public function putRequest($endpointUrl, $queryString){
if($endpointUrl == "domains"){ if($endpointUrl == "domains"){
$httpResponseCode = 200; return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$jsonResponseData = json_decode('asdfasdfasdf'); }
if($httpResponseCode === 200){ else{
foreach($jsonResponseData as $key => $value){ return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
$result->$key = $value;
}
}
$result->http_response_code = $httpResponseCode;
} }
return $result; return $result;
} }
public function responseHandler($endpointUrl, $httpResponseCode = 200){
if($httpResponseCode === 200){
$jsonResponseData = json_decode('{"message": "Some JSON Response Data"}');
foreach($jsonResponseData as $key => $value){
$result->http_response_body->$key = $value;
}
}
elseif($httpStatusCode == 400){
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
elseif($httpStatusCode == 401){
throw new InvalidCredentials(EXCEPTION_INVALID_CREDENTIALS);
}
elseif($httpStatusCode == 401){
throw new GenericHTTPError(EXCEPTION_INVALID_CREDENTIALS);
}
elseif($httpStatusCode == 404){
throw new MissingEndpoint(EXCEPTION_MISSING_ENDPOINT);
}
else{
throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR);
return false;
}
$result->http_response_code = $httpResponseCode;
return $result;
}
} }

View File

@ -4,12 +4,6 @@ namespace Mailgun\Tests;
use Guzzle\Tests\GuzzleTestCase; use Guzzle\Tests\GuzzleTestCase;
abstract class MailgunTestCase extends GuzzleTestCase{}
abstract class MailgunTestCase extends GuzzleTestCase
{
}
?> ?>