* Updated composer.json to guzzle v5

* Don't allow HHVM to fail
* Updated RestClient to Guzzle5
* Removed php5.3 from travis.
* Bugfix and removed debug code
This commit is contained in:
Tobias Nyholm 2015-04-18 21:20:26 +02:00 committed by Jesse Spears
parent edae22eba4
commit 3bb69d8cbe
5 changed files with 182 additions and 171 deletions

View File

@ -1,16 +1,17 @@
language: php language: php
php: php:
- 5.3
- 5.4 - 5.4
- 5.5 - 5.5
- 5.6 - 5.6
- 7.0
- hhvm - hhvm
matrix: before_install:
allow_failures: - travis_retry composer self-update
- php: hhvm
before_script: install:
- echo 'Installing composer dependencies now!' - travis_retry composer install
- composer install
script:
- phpunit

View File

@ -2,10 +2,11 @@
"name": "mailgun/mailgun-php", "name": "mailgun/mailgun-php",
"description": "The Mailgun SDK provides methods for all API functions.", "description": "The Mailgun SDK provides methods for all API functions.",
"require": { "require": {
"guzzle/guzzle": "<4.0,>=3.8" "guzzlehttp/guzzle": "~5.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "3.7.*" "php": ">=5.4.0",
"phpunit/phpunit": "~4.6"
}, },
"autoload": { "autoload": {
"psr-0": { "psr-0": {

View File

@ -2,11 +2,12 @@
namespace Mailgun\Connection; namespace Mailgun\Connection;
use Guzzle\Http\Client as Guzzle; use GuzzleHttp\Client as Guzzle;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Post\PostBodyInterface;
use GuzzleHttp\Post\PostFile;
use GuzzleHttp\Query;
use Mailgun\Connection\Exceptions\GenericHTTPError; use Mailgun\Connection\Exceptions\GenericHTTPError;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Http\QueryAggregator\PhpAggregator;
use Mailgun\Connection\Exceptions\InvalidCredentials; use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingRequiredParameters; use Mailgun\Connection\Exceptions\MissingRequiredParameters;
use Mailgun\Connection\Exceptions\MissingEndpoint; use Mailgun\Connection\Exceptions\MissingEndpoint;
@ -16,8 +17,8 @@ use Mailgun\Constants\ExceptionMessages;
/** /**
* This class is a wrapper for the Guzzle (HTTP Client Library). * This class is a wrapper for the Guzzle (HTTP Client Library).
*/ */
class RestClient { class RestClient
{
/** /**
* @var string * @var string
*/ */
@ -28,186 +29,167 @@ class RestClient {
*/ */
protected $mgClient; protected $mgClient;
/**
* @var bool
*/
protected $hasFiles = False;
/** /**
* @param string $apiKey * @param string $apiKey
* @param string $apiEndpoint * @param string $apiEndpoint
* @param string $apiVersion * @param string $apiVersion
* @param bool $ssl * @param bool $ssl
*/ */
public function __construct($apiKey, $apiEndpoint, $apiVersion, $ssl){ public function __construct($apiKey, $apiEndpoint, $apiVersion, $ssl)
{
$this->apiKey = $apiKey; $this->apiKey = $apiKey;
$this->mgClient = new Guzzle($this->generateEndpoint($apiEndpoint, $apiVersion, $ssl)); $this->mgClient = new Guzzle([
$this->mgClient->setDefaultOption('curl.options', array('CURLOPT_FORBID_REUSE' => true)); 'base_url'=>$this->generateEndpoint($apiEndpoint, $apiVersion, $ssl),
$this->mgClient->setDefaultOption('auth', array (Api::API_USER, $this->apiKey)); 'defaults'=>[
$this->mgClient->setDefaultOption('exceptions', false); 'auth' => array(Api::API_USER, $this->apiKey),
$this->mgClient->setUserAgent(Api::SDK_USER_AGENT . '/' . Api::SDK_VERSION); 'exceptions' => false,
'config' => ['curl' => [ CURLOPT_FORBID_REUSE => true ]],
'headers' => [
'User-Agent' => Api::SDK_USER_AGENT.'/'.Api::SDK_VERSION,
],
],
]);
} }
/** /**
* @param string $endpointUrl * @param string $endpointUrl
* @param array $postData * @param array $postData
* @param array $files * @param array $files
*
* @return \stdClass * @return \stdClass
*
* @throws GenericHTTPError * @throws GenericHTTPError
* @throws InvalidCredentials * @throws InvalidCredentials
* @throws MissingEndpoint * @throws MissingEndpoint
* @throws MissingRequiredParameters * @throws MissingRequiredParameters
*/ */
public function post($endpointUrl, $postData = array(), $files = array()){ public function post($endpointUrl, $postData = array(), $files = array())
$request = $this->mgClient->post($endpointUrl, array(), $postData); {
$request = $this->mgClient->createRequest('POST', $endpointUrl, ['body' => $postData]);
/** @var \GuzzleHttp\Post\PostBodyInterface $postBody */
$postBody = $request->getBody();
$postBody->setAggregator(Query::duplicateAggregator());
if(isset($files["message"])){ $fields = ['message', 'attachment', 'inline'];
$this->hasFiles = True; foreach ($fields as $fieldName) {
foreach($files as $message){ if (isset($files[$fieldName])) {
$request->addPostFile("message", $message); if (is_array($files[$fieldName])) {
foreach ($files[$fieldName] as $file) {
$this->addFile($postBody, $fieldName, $file);
} }
} } else {
$this->addFile($postBody, $fieldName, $files[$fieldName]);
if(isset($files["attachment"])){
$this->hasFiles = True;
foreach($files["attachment"] as $attachment){
// Backward compatibility code
if (is_array($attachment)){
$request->addPostFile("attachment",
$attachment['filePath'], null,
$attachment['remoteName']);
}
else{
$request->addPostFile("attachment", $attachment);
} }
} }
} }
if(isset($files["inline"])){ $response = $this->mgClient->send($request);
$this->hasFiles = True;
foreach($files["inline"] as $inline){
// Backward compatibility code
if (is_array($inline)){
$request->addPostFile("inline",
$inline['filePath'], null,
$inline['remoteName']);
}
else{
$request->addPostFile("inline", $inline);
}
}
}
/*
This block of code is to accommodate for a bug in Guzzle.
See https://github.com/guzzle/guzzle/issues/545.
It can be removed when Guzzle resolves the issue.
*/
if($this->hasFiles){
$request->getPostFields()->setAggregator(new PhpAggregator());
}
else{
$request->getPostFields()->setAggregator(new DuplicateAggregator());
}
$response = $request->send();
return $this->responseHandler($response); return $this->responseHandler($response);
} }
/** /**
* @param string $endpointUrl * @param string $endpointUrl
* @param array $queryString * @param array $queryString
*
* @return \stdClass * @return \stdClass
*
* @throws GenericHTTPError * @throws GenericHTTPError
* @throws InvalidCredentials * @throws InvalidCredentials
* @throws MissingEndpoint * @throws MissingEndpoint
* @throws MissingRequiredParameters * @throws MissingRequiredParameters
*/ */
public function get($endpointUrl, $queryString = array()){ public function get($endpointUrl, $queryString = array())
$request = $this->mgClient->get($endpointUrl); {
if(isset($queryString)){ $response = $this->mgClient->get($endpointUrl, ['query' => $queryString]);
foreach($queryString as $key=>$value){
$request->getQuery()->set($key, $value);
}
}
$response = $request->send();
return $this->responseHandler($response); return $this->responseHandler($response);
} }
/** /**
* @param string $endpointUrl * @param string $endpointUrl
*
* @return \stdClass * @return \stdClass
*
* @throws GenericHTTPError * @throws GenericHTTPError
* @throws InvalidCredentials * @throws InvalidCredentials
* @throws MissingEndpoint * @throws MissingEndpoint
* @throws MissingRequiredParameters * @throws MissingRequiredParameters
*/ */
public function delete($endpointUrl){ public function delete($endpointUrl)
$request = $this->mgClient->delete($endpointUrl); {
$response = $request->send(); $response = $this->mgClient->delete($endpointUrl);
return $this->responseHandler($response); return $this->responseHandler($response);
} }
/** /**
* @param string $endpointUrl * @param string $endpointUrl
* @param array $putData * @param array $putData
*
* @return \stdClass * @return \stdClass
*
* @throws GenericHTTPError * @throws GenericHTTPError
* @throws InvalidCredentials * @throws InvalidCredentials
* @throws MissingEndpoint * @throws MissingEndpoint
* @throws MissingRequiredParameters * @throws MissingRequiredParameters
*/ */
public function put($endpointUrl, $putData){ public function put($endpointUrl, $putData)
$request = $this->mgClient->put($endpointUrl, array(), $putData); {
$request->getPostFields()->setAggregator(new DuplicateAggregator()); $request = $this->mgClient->createRequest('PUT', $endpointUrl, ['body' => $putData]);
$response = $request->send(); /** @var \GuzzleHttp\Post\PostBodyInterface $postBody */
$postBody = $request->getBody();
$postBody->setAggregator(Query::duplicateAggregator());
$response = $this->mgClient->send($request);
return $this->responseHandler($response); return $this->responseHandler($response);
} }
/** /**
* @param \Guzzle\Http\Message\Response $responseObj * @param ResponseInterface $responseObj
*
* @return \stdClass * @return \stdClass
*
* @throws GenericHTTPError * @throws GenericHTTPError
* @throws InvalidCredentials * @throws InvalidCredentials
* @throws MissingEndpoint * @throws MissingEndpoint
* @throws MissingRequiredParameters * @throws MissingRequiredParameters
*/ */
public function responseHandler($responseObj){ public function responseHandler($responseObj)
{
$httpResponseCode = $responseObj->getStatusCode(); $httpResponseCode = $responseObj->getStatusCode();
if($httpResponseCode === 200){ if ($httpResponseCode === 200) {
$data = (string) $responseObj->getBody(); $data = (string) $responseObj->getBody();
$jsonResponseData = json_decode($data, false); $jsonResponseData = json_decode($data, false);
$result = new \stdClass(); $result = new \stdClass();
// return response data as json if possible, raw if not // return response data as json if possible, raw if not
$result->http_response_body = $data && $jsonResponseData === null ? $data : $jsonResponseData; $result->http_response_body = $data && $jsonResponseData === null ? $data : $jsonResponseData;
} } elseif ($httpResponseCode == 400) {
elseif($httpResponseCode == 400){ throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS.$this->getResponseExceptionMessage($responseObj));
throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS . $this->getResponseExceptionMessage($responseObj)); } elseif ($httpResponseCode == 401) {
}
elseif($httpResponseCode == 401){
throw new InvalidCredentials(ExceptionMessages::EXCEPTION_INVALID_CREDENTIALS); throw new InvalidCredentials(ExceptionMessages::EXCEPTION_INVALID_CREDENTIALS);
} } elseif ($httpResponseCode == 404) {
elseif($httpResponseCode == 404){ throw new MissingEndpoint(ExceptionMessages::EXCEPTION_MISSING_ENDPOINT.$this->getResponseExceptionMessage($responseObj));
throw new MissingEndpoint(ExceptionMessages::EXCEPTION_MISSING_ENDPOINT . $this->getResponseExceptionMessage($responseObj)); } else {
}
else{
throw new GenericHTTPError(ExceptionMessages::EXCEPTION_GENERIC_HTTP_ERROR, $httpResponseCode, $responseObj->getBody()); throw new GenericHTTPError(ExceptionMessages::EXCEPTION_GENERIC_HTTP_ERROR, $httpResponseCode, $responseObj->getBody());
} }
$result->http_response_code = $httpResponseCode; $result->http_response_code = $httpResponseCode;
return $result; return $result;
} }
/** /**
* @param \Guzzle\Http\Message\Response $responseObj * @param \Guzzle\Http\Message\Response $responseObj
*
* @return string * @return string
*/ */
protected function getResponseExceptionMessage(\Guzzle\Http\Message\Response $responseObj){ protected function getResponseExceptionMessage(\Guzzle\Http\Message\Response $responseObj)
$body = (string)$responseObj->getBody(); {
$body = (string) $responseObj->getBody();
$response = json_decode($body); $response = json_decode($body);
if (json_last_error() == JSON_ERROR_NONE && isset($response->message)) { if (json_last_error() == JSON_ERROR_NONE && isset($response->message)) {
return " " . $response->message; return " ".$response->message;
} }
} }
@ -215,14 +197,39 @@ class RestClient {
* @param string $apiEndpoint * @param string $apiEndpoint
* @param string $apiVersion * @param string $apiVersion
* @param bool $ssl * @param bool $ssl
*
* @return string * @return string
*/ */
private function generateEndpoint($apiEndpoint, $apiVersion, $ssl){ private function generateEndpoint($apiEndpoint, $apiVersion, $ssl)
if(!$ssl){ {
return "http://" . $apiEndpoint . "/" . $apiVersion . "/"; if (!$ssl) {
return "http://".$apiEndpoint."/".$apiVersion."/";
} else {
return "https://".$apiEndpoint."/".$apiVersion."/";
} }
else{
return "https://" . $apiEndpoint . "/" . $apiVersion . "/";
} }
/**
* Add a file to the postBody.
*
* @param PostBodyInterface $postBody
* @param string $fieldName
* @param string|array $filePath
*/
private function addFile(PostBodyInterface $postBody, $fieldName, $filePath)
{
$filename = null;
// Backward compatibility code
if (is_array($filePath)) {
$filename = $filePath['remoteName'];
$filePath = $filePath['filePath'];
}
// Remove leading @ symbol
if (strpos($filePath, '@') === 0) {
$filePath = substr($filePath, 1);
}
$postBody->addFile(new PostFile($fieldName, fopen($filePath, 'r'), $filename));
} }
} }

View File

@ -2,8 +2,6 @@
namespace Mailgun\Tests; namespace Mailgun\Tests;
use Guzzle\Tests\GuzzleTestCase; abstract class MailgunTestCase extends \PHPUnit_Framework_TestCase
abstract class MailgunTestCase extends GuzzleTestCase
{ {
} }

View File

@ -1,7 +1,11 @@
<?php <?php
namespace Mailgun\Tests\Mock\Connection; namespace Mailgun\Tests\Mock\Connection;
use Mailgun\Connection\Exceptions\GenericHTTPError;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingEndpoint;
use Mailgun\Connection\RestClient; use Mailgun\Connection\RestClient;
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
class TestBroker extends RestClient class TestBroker extends RestClient
{ {
@ -17,25 +21,25 @@ class TestBroker extends RestClient
public function post($endpointUrl, $postData = array(), $files = array()) public function post($endpointUrl, $postData = array(), $files = array())
{ {
return $this->responseHandler($endpointUrl, $httpResponseCode = 200); return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
} }
public function get($endpointUrl, $queryString = array()) public function get($endpointUrl, $queryString = array())
{ {
return $this->responseHandler($endpointUrl, $httpResponseCode = 200); return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
} }
public function delete($endpointUrl) public function delete($endpointUrl)
{ {
return $this->responseHandler($endpointUrl, $httpResponseCode = 200); return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
} }
public function put($endpointUrl, $queryString) public function put($endpointUrl, $queryString)
{ {
return $this->responseHandler($endpointUrl, $httpResponseCode = 200); return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
} }
public function responseHandler($endpointUrl, $httpResponseCode = 200) public function testResponseHandler($endpointUrl, $httpResponseCode = 200)
{ {
if ($httpResponseCode === 200) { if ($httpResponseCode === 200) {
$result = new \stdClass(); $result = new \stdClass();
@ -44,13 +48,13 @@ class TestBroker extends RestClient
foreach ($jsonResponseData as $key => $value) { foreach ($jsonResponseData as $key => $value) {
$result->http_response_body->$key = $value; $result->http_response_body->$key = $value;
} }
} elseif ($httpStatusCode == 400) { } elseif ($httpResponseCode == 400) {
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS); throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
} elseif ($httpStatusCode == 401) { } elseif ($httpResponseCode == 401) {
throw new InvalidCredentials(EXCEPTION_INVALID_CREDENTIALS); throw new InvalidCredentials(EXCEPTION_INVALID_CREDENTIALS);
} elseif ($httpStatusCode == 401) { } elseif ($httpResponseCode == 401) {
throw new GenericHTTPError(EXCEPTION_INVALID_CREDENTIALS); throw new GenericHTTPError(EXCEPTION_INVALID_CREDENTIALS);
} elseif ($httpStatusCode == 404) { } elseif ($httpResponseCode == 404) {
throw new MissingEndpoint(EXCEPTION_MISSING_ENDPOINT); throw new MissingEndpoint(EXCEPTION_MISSING_ENDPOINT);
} else { } else {
throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR); throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR);