End of day commit

This commit is contained in:
Travis Swientek 2013-07-23 17:34:50 -07:00
parent e5ae7e47d3
commit 5befeb0f66
21 changed files with 767 additions and 148 deletions

View File

@ -1,19 +1,24 @@
{
"name": "mailgun/mailgun-php-client",
"name": "mailgun/mailgun-sdk-php",
"description": "The Mailgun SDK provides methods for all API functions.",
"require": {
"guzzle/guzzle": "3.7.1",
"guzzle/guzzle": "3.7.1"
},
"require-dev": {
"phpunit/phpunit": "3.7.*"
},
"authors": [
{
"name": "Travis Swientek",
"email": "travis@tswientek.com"
}
],
"autoload": {
"psr-0": {
"Mailgun\\Tests": "tests/",
"Mailgun": "src/"
}
}
},
"license": "MIT",
"authors": [
{
"name": "Travis Swientek",
"email": "travis@mailgunhq.com"
}
],
"minimum-stability": "stable"
}

115
composer.lock generated
View File

@ -3,7 +3,7 @@
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
],
"hash": "7301f9087143937ee9fa2db35177d0ca",
"hash": "bc22ca77dbf86d18c024967b95de2a97",
"packages": [
{
"name": "guzzle/guzzle",
@ -97,6 +97,62 @@
],
"time": "2013-07-05 20:17:54"
},
{
"name": "symfony/event-dispatcher",
"version": "v2.3.2",
"target-dir": "Symfony/Component/EventDispatcher",
"source": {
"type": "git",
"url": "https://github.com/symfony/EventDispatcher.git",
"reference": "v2.3.2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/v2.3.2",
"reference": "v2.3.2",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"symfony/dependency-injection": "~2.0"
},
"suggest": {
"symfony/dependency-injection": "",
"symfony/http-kernel": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.3-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\EventDispatcher\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
}
],
"description": "Symfony EventDispatcher Component",
"homepage": "http://symfony.com",
"time": "2013-05-13 14:36:40"
}
],
"packages-dev": [
{
"name": "phpunit/php-code-coverage",
"version": "1.2.12",
@ -459,60 +515,6 @@
],
"time": "2013-01-13 10:24:48"
},
{
"name": "symfony/event-dispatcher",
"version": "v2.3.2",
"target-dir": "Symfony/Component/EventDispatcher",
"source": {
"type": "git",
"url": "https://github.com/symfony/EventDispatcher.git",
"reference": "v2.3.2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/v2.3.2",
"reference": "v2.3.2",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"symfony/dependency-injection": "~2.0"
},
"suggest": {
"symfony/dependency-injection": "",
"symfony/http-kernel": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.3-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\EventDispatcher\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
}
],
"description": "Symfony EventDispatcher Component",
"homepage": "http://symfony.com",
"time": "2013-05-13 14:36:40"
},
{
"name": "symfony/yaml",
"version": "v2.3.2",
@ -560,9 +562,6 @@
"homepage": "http://symfony.com",
"time": "2013-07-11 19:36:36"
}
],
"packages-dev": [
],
"aliases": [

View File

@ -12,7 +12,6 @@
<testsuites>
<testsuite>
<directory>./tests/Mailgun/Tests</directory>
<exclude>./tests/Mailgun/Tests/Connection/ConnectionTest.php</exclude>
</testsuite>
</testsuites>

View File

@ -0,0 +1,128 @@
<?PHP
namespace Mailgun\Connection;
require dirname(__DIR__) . '/globals.php';
use Guzzle\Http\Client as Guzzle;
use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\GenericHTTPError;
class Client{
protected $apiKey;
protected $domain;
protected $client;
protected $debug;
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->domain = $domain;
$this->debug = $debug;
if($this->debug){
$this->client = new Guzzle('https://api.ninomail.com/' . $this->apiVersion . '/', array('ssl.certificate_authority' => false));
$this->client->setDefaultOption('auth', array ($this->apiUser, $this->apiKey));
$this->client->setDefaultOption('exceptions', false);
$this->client->setUserAgent($this->sdkUserAgent . '/' . $this->sdkVersion);
$this->validateCredentials();
}
else{
$this->client = new Guzzle('https://' . $this->apiEndpoint . '/' . $this->apiVersion . '/');
$this->client->setDefaultOption('auth', array ($this->apiUser, $this->apiKey));
$this->client->setDefaultOption('exceptions', false);
$this->client->setUserAgent($this->sdkUserAgent . '/' . $this->sdkVersion);
$this->validateCredentials();
}
}
public function validateCredentials(){
$url = "domains";
$data = null;
$request = $this->client->get($url, array(), $data);
$response = $request->send();
if($response->getStatusCode() == 200){
$jsonResp = $response->json();
foreach ($jsonResp as $key => $value){
$object->$key = $value;
}
if($object->total_count > 0){
return true;
}
else{
throw new NoDomainsConfigured("You don't have any domains on your account.");
return false;
}
}
elseif($response->getStatusCode() == 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;
}
}
public function sendMessage($message){
if(array_key_exists("from", $message) &&
array_key_exists("to", $message) &&
array_key_exists("subject", $message) &&
(array_key_exists("text", $message) || array_key_exists("html", $message))){
$domain = $this->domain;
if($this->debug){
$request = $this->client->post("$domain/messages", array(), $message);
if(isset($message["attachment"])){
foreach($message["attachment"] as $attachments){
$request->addPostFile("attachment", $attachments);
}
unset($message["attachment"]);
}
if(isset($message["inline"])){
foreach($message["inline"] as $inlineAttachments){
$request->addPostFile("inline", $inlineAttachments);
}
}
$response = $request->send();
}
else{
$request = $this->client->post("$domain/messages", array(), $message);
if(isset($message["attachment"])){
foreach($message["attachment"] as $attachments){
$request->addPostFile("attachment", $attachments);
}
unset($message["attachment"]);
}
if(isset($message["inline"])){
foreach($message["inline"] as $inlineAttachments){
$request->addPostFile("inline", $inlineAttachments);
}
}
$response = $request->send();
}
return $response;
}
throw new MissingRequiredMIMEParameters("You are missing the minimum parameters to send a message.");
}
public function postUnsubscribe($data){
$domain = $this->domain;
$request = $this->client->post("$domain/unsubscribes", array(), $data);
return $request->send();
}
public function deleteUnsubscribe($address){
$domain = $this->domain;
$request = $client->delete("$domain/unsubscribes/$address");
return $request->send();
}
}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Connection\Exceptions;
class GenericHTTPError extends \Exception{}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Connection\Exceptions;
class InvalidCredentials extends \Exception{}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Connection\Exceptions;
class MissingRequiredMIMEParameters extends \Exception{}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Connection\Exceptions;
class NoDomainsConfigured extends \Exception{}
?>

View File

@ -0,0 +1,89 @@
<?PHP
//BatchMessage.php - Extends the Message class and provides continuous recipient addition.
namespace Mailgun\Messages;
use Guzzle\Http\Client as Guzzler;
use Mailgun\Exceptions\NoDomainsConfigured;
use Mailgun\Exceptions\HTTPError;
class BatchMessage extends Message{
private $batchRecipientAttributes;
private $client;
private $autoSend;
public function __construct($client, $debug = false){
parent::__construct($this->client);
$this->batchRecipientAttributes = array();
$this->client = $client;
$this->debug = $debug;
}
public function addBatchRecipient($address, $attributes){
//Check for maximum recipient count
if($this->toRecipientCount == 1000){
//If autoSend is off, do things here.
if($this->debug == true){
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
unset($this->message['to']);
}
else{
//Send current set and reset recipient parameters
$this->sendBatchMessage();
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
unset($this->message['to']);
}
}
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
$addr = $name . " <" . $address . ">";
if(isset($this->message["to"])){
array_push($this->message["to"], $addr);
}
else{
$this->message["to"] = array($addr);
}
$attributes["id"] = $this->toRecipientCount;
$this->batchRecipientAttributes["$address"] = $attributes;
$this->toRecipientCount++;
return true;
}
public function endBatchMessage(){
if($this->debug == true){
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
$this->message = array();
return true;
}
$this->sendBatchMessage();
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
$this->message = array();
return true;
}
private function sendBatchMessage(){
if(array_key_exists("from", $this->message)){
if($this->toRecipientCount > 0){
if(array_key_exists("subject", $this->message)){
if(array_key_exists("text", $this->message) || array_key_exists("html", $this->message)){
$this->message["recipient-variables"] = json_encode($this->batchRecipientAttributes);
return $this->client->sendMessage($this->message);
}
}
}
}
}
}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Messages\Exceptions;
class InvalidParameter extends \Exception{}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Messages\Exceptions;
class InvalidParameterType extends \Exception{}
?>

View File

@ -0,0 +1,6 @@
<?php
namespace Mailgun\Messages\Exceptions;
class TooManyParameters extends \Exception{}
?>

View File

@ -0,0 +1,299 @@
<?PHP
/*
* Message.php - Message builder for creating a message object. Pass the message object to the client to send the message.
*/
namespace Mailgun\Messages;
use Guzzle\Http\Client as Guzzler;
use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Messages\Expcetions\InvalidParameter;
use Mailgun\Messages\Expcetions\InvalidParameterType;
class Message{
protected $message;
protected $sanitized;
protected $toRecipientCount;
protected $ccRecipientCount;
protected $bccRecipientCount;
protected $attachmentCount;
protected $campaignIdCount;
protected $customOptionCount;
public function __construct(){
$this->message = array();
$this->toRecipientCount = 0;
$this->ccRecipientCount = 0;
$this->bccRecipientCount = 0;
$this->attachmentCount = 0;
$this->campaignIdCount = 0;
$this->customOptionCount = 0;
}
public function addToRecipient($address, $attributes){
if($this->toRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
if(isset($name)){
$addr = $name . " <" . $address . ">";
}
else{
$addr = $address;
}
if(isset($this->message["to"])){
array_push($this->message["to"], $addr);
}
else{
$this->message["to"] = array($addr);
}
$this->toRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the to field.");
}
}
public function addCcRecipient($address, $attributes){
if($this->ccRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
if(isset($name)){
$addr = $name . " <" . $address . ">";
}
else{
$addr = $address;
}
if(isset($this->message["cc"])){
array_push($this->message["cc"], $addr);
}
else{
$this->message["cc"] = array($addr);
}
$this->ccRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the cc field.");
}
}
public function addBccRecipient($address, $attributes){
if($this->bccRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
if(isset($name)){
$addr = $name . " <" . $address . ">";
}
else{
$addr = $address;
}
if(isset($this->message["bcc"])){
array_push($this->message["bcc"], $addr);
}
else{
$this->message["bcc"] = array($addr);
}
$this->bccRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the bcc field.");
}
}
public function setFromAddress($address, $attributes){
if(isset($attributes)){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
else{
throw new InvalidParameterType("The parameter you've passed in position 2 must be an array.");
}
}
if(isset($name)){
$addr = $name . " <" . $address . ">";
}
else{
$addr = $address;
}
$this->message['from'] = $addr;
return true;
}
public function setSubject($data = NULL){
if($data == NULL || $data == ""){
$data = " ";
}
$this->message['subject'] = $data;
return true;
}
public function addCustomHeader($headerName, $data){
if(!preg_match("/^h:/i", $headerName)){
$headerName = "h:" . $headerName;
}
$this->message[$headerName] = array($data);
return true;
}
public function setTextBody($data){
if($data == NULL || $data == ""){
$data = " ";
}
$this->message['text'] = $data;
return true;
}
public function setHtmlBody($data){
if($data == NULL || $data == ""){
$data = " ";
}
$this->message['html'] = $data;
return true;
}
public function addAttachment($data){
if(preg_match("/^@/", $data)){
if(isset($this->message["attachment"])){
array_push($this->message["attachment"], $data);
}
else{
$this->message["attachment"] = array($data);
}
return true;
}
else{
throw new InvalidParameter("Attachments must be passed with an \"@\" preceding the file path. Web resources not supported.");
}
}
public function addInlineImage($data){
if(preg_match("/^@/", $data)){
if(isset($this->message['inline'])){
array_push($this->message['inline'] , $data);
return true;
}
else{
$this->message['inline'] = array($data);
return true;
}
}
else{
throw new InvalidParameter("Inline images must be passed with an \"@\" preceding the file path. Web resources not supported.");
}
}
public function setTestMode($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes";
}
else{
$data = "no";
}
$this->message['o:testmode'] = $data;
return true;
}
public function addCampaignId($data){
if($this->campaignIdCount < 3){
if(isset($this->message['o:campaign'])){
array_push($this->message['o:campaign'] , $data);
}
else{
$this->message['o:campaign'] = array($data);
}
$this->campaignIdCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum (3) campaigns for a single message.");
}
}
public function setDkim($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes";
}
else{
$data = "no";
}
$this->message["o:dkim"] = $data;
return true;
}
public function setOpenTracking($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes";
}
else{
$data = "no";
}
$this->message['o:tracking-opens'] = $data;
return true;
}
public function setClickTracking($data){
if(filter_var($data, FILTER_VALIDATE_BOOLEAN)){
$data = "yes";
}
else{
$data = "no";
}
$this->message['o:tracking-clicks'] = $data;
return true;
}
public function setDeliveryTime($timeDate, $timeZone = NULL){
if(isset($timeZone)){
$timeZoneObj = new \DateTimeZone("$timeZone");
}
else{
$timeZoneObj = new \DateTimeZone(\DEFAULT_TIME_ZONE);
}
$dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
$formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
$this->message['o:deliverytime'] = $formattedTimeDate;
return true;
}
public function addCustomData($customName, $data){
if(is_array($data)){
$jsonArray = json_encode($data);
$this->message['v:'.$customName] = $jsonArray;
}
else{
throw new InvalidParameter("Custom Data values must be passed as an array.");
return false;
}
}
public function addCustomOption($optionName, $data){
if(!preg_match("/^o:/i", $optionName)){
$optionName = "o:" . $optionName;
}
if(isset($this->message['options'][$optionName])){
array_push($this->message['options'][$optionName], $data);
return true;
}
else{
$this->message['options'][$optionName] = array($data);
return true;
}
}
public function getMessage(){
return $this->message;
}
}
?>

View File

@ -0,0 +1,36 @@
<?PHP
/*
* Unsubscribe.php - Processing unsubscribes.
*/
namespace Mailgun\Unsubscribes;
class Unsubscribe{
private $client;
public function __construct($client){
$this->client = $client;
}
public function addUnsubscribe($address, $tag = NULL){
if(isset($tag)){
$data = array("address" => $address, "tag" => $tag);
}
else{
$data = array("address" => $address, "tag" => "*");
}
$response = $this->client->postUnsubscribe($data);
return $response;
}
public function deleteUnsubscribe($address){
$response = $this->client->deleteUnsubscribe($address);
return $response;
}
public function getUnsubscribe($address){
}
}

View File

@ -3,14 +3,16 @@
require 'vendor/autoload.php';
use Mailgun\Common\Client;
use Mailgun\Common\Message;
use Mailgun\Connection\Client;
use Mailgun\Messages\Message;
use Mailgun\Exceptions\NoDomainsConfigured;
use Mailgun\Exceptions\HTTPError;
use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\GenericHTTPError;
$client = new Client("key-ca6d168e492611df8307001d60d24a9c-0b27e", "aawdawdad.ninomail.com", true);
$client = new Client("key-ca6d168e492611df83070asdf01d60d24a9c-0b27e", "aawdawdad.ninomail.com", true);
$message = new Message();
$message->addCustomData("My-Super-Awesome-Data", array("What" => "Mailgun Rocks!"));

View File

@ -0,0 +1,10 @@
HTTP/1.1 200 OK
Date: Tue, 23 Jul 2013 23:48:32 GMT
Connection: keep-alive
Server: nginx/1.4.1
Content-Type: application/json
{
"message": "Queued. Thank you.",
"id": "<20130723234832.14853.95179@trstx.com>"
}

View File

@ -0,0 +1,48 @@
<?PHP
namespace Mailgun\Tests\Connection;
use Mailgun\Connection\Client;
use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\GenericHTTPError;
class ClientTest extends \Mailgun\Tests\MailgunTestCase{
private $client;
public function setUp(){
$this->client = new Client(\DEFAULT_MG_API_KEY, \DEFAULT_MG_DOMAIN, false);
$path = "../../Mock/messages";
$this->setMockResponse($this->client, $path);
}
public function testNewClientConnection(){
$result = $this->client->validateCredentials();
$this->assertTrue($result);
}
public function testSendSimpleTestMessage(){
$result = $this->client->sendMessage(array("from" => "Excited User <me@samples.mailgun.org>", "to" => "travis@tswientek.com", "subject" => "Hello", "text" => "PHP Unit Test Success!", "o:testmode" => true));
$status = $result->getStatusCode();
$this->assertEquals("200", $status);
}
/**
* @expectedException Mailgun\Connection\Exceptions\InvalidCredentials
*/
public function testBadCredentialsException(){
$throwAway = new Client("key-this-is-not-valid", \DEFAULT_MG_DOMAIN, false);
}
/**
* @expectedException Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters
*/
public function testRequiredMIMEParametersException(){
$this->client->sendMessage(array("from" => "Excited User <me@samples.mailgun.org>", "subject" => "Hello", "text" => "PHP Unit Test Success!", "o:testmode" => true));
}
}
?>

View File

@ -2,7 +2,9 @@
namespace Mailgun\Tests;
abstract class MailgunTestCase extends \PHPUnit_Framework_TestCase
use Guzzle\Tests\GuzzleTestCase;
abstract class MailgunTestCase extends GuzzleTestCase
{
//Will include more stuff here... Just extending PHPUnit for now.
}

View File

@ -1,8 +1,8 @@
<?PHP
namespace Mailgun\Tests\BatchMessage;
use Mailgun\Common\Client;
use Mailgun\Common\BatchMessage;
use Mailgun\Connection\Client;
use Mailgun\Messages\BatchMessage;
class BatchMessageTest extends \Mailgun\Tests\MailgunTestCase{

View File

@ -1,7 +1,7 @@
<?PHP
namespace Mailgun\Tests\Message;
use Mailgun\Common\Message;
use Mailgun\Messages\Message;
class MessageTest extends \Mailgun\Tests\MailgunTestCase{
public function setUp(){
@ -173,74 +173,4 @@ class MessageTest extends \Mailgun\Tests\MailgunTestCase{
}
}
?>
?>

View File

@ -0,0 +1,30 @@
<?PHP
namespace Mailgun\Tests\Unsubscribes;
use Mailgun\Connection\Client;
use Mailgun\Unsubscribes\Unsubscribe;
class UnsubscribeTest extends \Mailgun\Tests\MailgunTestCase{
private $client;
public function setUp(){
$this->client = new Client(\DEFAULT_MG_API_KEY, \DEFAULT_MG_DOMAIN, false);
}
public function testAddUnsubscribe(){
$unsub = new Unsubscribe($this->client);
$response = $unsub->addUnsubscribe("test@samples.mailgun.org");
$httpCode = $response->getStatusCode();
$this->assertEquals(200, $httpCode);
}
public function testDeleteUnsubscribe(){
$unsub = new Unsubscribe($this->client);
$response = $unsub->deleteUnsubscribe("test@samples.mailgun.org");
$httpCode = $response->getStatusCode();
$this->assertEquals(200, $httpCode);
}
}