Skip to content

Commit

Permalink
Added debug option
Browse files Browse the repository at this point in the history
Added debug option
  • Loading branch information
avigoldman committed Jan 6, 2017
2 parents c54abe8 + 1abdc8b commit f4cb526
Show file tree
Hide file tree
Showing 14 changed files with 271 additions and 126 deletions.
8 changes: 7 additions & 1 deletion README.md
Expand Up @@ -100,7 +100,11 @@ $sparky = new SparkPost($httpClient, ['key'=>'YOUR_API_KEY']);
* Type: `Boolean`
* Default: `true`
* `async` defines if the `request` function sends an asynchronous or synchronous request. If your client does not support async requests set this to `false`

* `options.debug`
* Required: No
* Type: `Boolean`
* Default: `false`
* If `debug` is true, then then all `SparkPostResponse` and `SparkPostException` instances will return any array of the request values through the function `getRequest`

## Methods
### request(method, uri [, payload [, headers]])
Expand Down Expand Up @@ -299,6 +303,8 @@ An exception will be thrown in two cases: there is a problem with the request or
* Returns the exception message
* **getBody()**
* If there is a response body it returns it as an `Array`. Otherwise it returns `null`.
* **getRequest()**
* Returns an array with the request values `method`, `url`, `headers`, `body` when `debug` is `true`


### Contributing
Expand Down
42 changes: 42 additions & 0 deletions examples/debug/index.php
@@ -0,0 +1,42 @@
<?php

namespace Examples\Templates;

require dirname(__FILE__).'/../bootstrap.php';

use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

$httpClient = new GuzzleAdapter(new Client());

/*
* configure options in example-options.json
*/
$sparky = new SparkPost($httpClient, [
"key" => "YOUR_API_KEY",
// This will expose your API KEY - do not use this in production.
"debug" => true
]);

$promise = $sparky->request('GET', 'templates');

try {
$response = $promise->wait();

var_dump($response);

echo "Request:\n";
print_r($response->getRequest());

echo "Response:\n";
echo $response->getStatusCode()."\n";
print_r($response->getBody())."\n";
} catch (\Exception $e) {
echo "Request:\n";
print_r($e->getRequest());

echo "Exception:\n";
echo $e->getCode()."\n";
echo $e->getMessage()."\n";
}
2 changes: 1 addition & 1 deletion examples/message-events/get_message_events.php
Expand Up @@ -16,7 +16,7 @@
$sparky = new SparkPost($httpClient, $options);

$promise = $sparky->request('GET', 'message-events', [
'campaign_ids' => 'CAMPAIGN_ID'
'campaign_ids' => 'CAMPAIGN_ID',
]);

try {
Expand Down
12 changes: 6 additions & 6 deletions examples/templates/create_template.php
Expand Up @@ -16,12 +16,12 @@
$sparky = new SparkPost($httpClient, $options);

$promise = $sparky->request('POST', 'templates', [
"name" => "PHP example template",
"content" => [
"from" => "from@YOUR_DOMAIN",
"subject" => "Your Subject",
"html" => "<b>Write your message here.</b>"
]
'name' => 'PHP example template',
'content' => [
'from' => 'from@YOUR_DOMAIN',
'subject' => 'Your Subject',
'html' => '<b>Write your message here.</b>',
],
]);

try {
Expand Down
4 changes: 2 additions & 2 deletions examples/templates/preview_template.php
Expand Up @@ -17,8 +17,8 @@

$promise = $sparky->request('POST', 'templates/TEMPLATE_ID/preview?draft=true', [
'substitution_data' => [
'some_key' => 'some_value'
]
'some_key' => 'some_value',
],
]);

try {
Expand Down
4 changes: 2 additions & 2 deletions examples/templates/update_template.php
Expand Up @@ -17,8 +17,8 @@

$promise = $sparky->request('PUT', 'templates/TEMPLATE_ID', [
'options' => [
'open_tracking' => true
]
'open_tracking' => true,
],
]);

try {
Expand Down
4 changes: 2 additions & 2 deletions lib/SparkPost/Resource.php
Expand Up @@ -3,8 +3,8 @@
namespace SparkPost;

/**
* Class Resource
* @package SparkPost
* Class Resource.
*
* @deprecated Soft reservations placed on name Resource (as of PHP7)
*/
class Resource extends ResourceBase
Expand Down
3 changes: 1 addition & 2 deletions lib/SparkPost/ResourceBase.php
Expand Up @@ -3,8 +3,7 @@
namespace SparkPost;

/**
* Class ResourceBase
* @package SparkPost
* Class ResourceBase.
*/
class ResourceBase
{
Expand Down
72 changes: 59 additions & 13 deletions lib/SparkPost/SparkPost.php
Expand Up @@ -11,12 +11,12 @@
class SparkPost
{
/**
* @var string Library version, used for setting User-Agent.
* @var string Library version, used for setting User-Agent
*/
private $version = '2.0.3';

/**
* @var HttpClient|HttpAsyncClient used to make requests.
* @var HttpClient|HttpAsyncClient used to make requests
*/
private $httpClient;

Expand All @@ -26,7 +26,7 @@ class SparkPost
private $messageFactory;

/**
* @var array Options for requests.
* @var array Options for requests
*/
private $options;

Expand All @@ -40,10 +40,11 @@ class SparkPost
'key' => '',
'version' => 'v1',
'async' => true,
'debug' => false,
];

/**
* @var Transmission Instance of Transmission class.
* @var Transmission Instance of Transmission class
*/
public $transmissions;

Expand Down Expand Up @@ -93,11 +94,13 @@ public function request($method = 'GET', $uri = '', $payload = [], $headers = []
*/
public function syncRequest($method = 'GET', $uri = '', $payload = [], $headers = [])
{
$request = $this->buildRequest($method, $uri, $payload, $headers);
$requestValues = $this->buildRequestValues($method, $uri, $payload, $headers);
$request = call_user_func_array(array($this, 'buildRequestInstance'), $requestValues);

try {
return new SparkPostResponse($this->httpClient->sendRequest($request));
return new SparkPostResponse($this->httpClient->sendRequest($request), $this->ifDebug($requestValues));
} catch (\Exception $exception) {
throw new SparkPostException($exception);
throw new SparkPostException($exception, $this->ifDebug($requestValues));
}
}

Expand All @@ -114,25 +117,26 @@ public function syncRequest($method = 'GET', $uri = '', $payload = [], $headers
public function asyncRequest($method = 'GET', $uri = '', $payload = [], $headers = [])
{
if ($this->httpClient instanceof HttpAsyncClient) {
$request = $this->buildRequest($method, $uri, $payload, $headers);
$requestValues = $this->buildRequestValues($method, $uri, $payload, $headers);
$request = call_user_func_array(array($this, 'buildRequestInstance'), $requestValues);

return new SparkPostPromise($this->httpClient->sendAsyncRequest($request));
return new SparkPostPromise($this->httpClient->sendAsyncRequest($request), $this->ifDebug($requestValues));
} else {
throw new \Exception('Your http client does not support asynchronous requests. Please use a different client or use synchronous requests.');
}
}

/**
* Builds request from given params.
* Builds request values from given params.
*
* @param string $method
* @param string $uri
* @param array $payload
* @param array $headers
*
* @return RequestInterface
* @return array $requestValues
*/
public function buildRequest($method, $uri, $payload, $headers)
public function buildRequestValues($method, $uri, $payload, $headers)
{
$method = trim(strtoupper($method));

Expand All @@ -153,7 +157,37 @@ public function buildRequest($method, $uri, $payload, $headers)
];
$body = strtr(json_encode($body), $jsonReplace);

return $this->getMessageFactory()->createRequest($method, $url, $headers, $body);
return [
'method' => $method,
'url' => $url,
'headers' => $headers,
'body' => $body,
];
}

/**
* Build RequestInterface from given params.
*
* @param array $requestValues
*
* @return RequestInterface
*/
public function buildRequestInstance($method, $uri, $headers, $body)
{
return $this->getMessageFactory()->createRequest($method, $uri, $headers, $body);
}

/**
* Build RequestInterface from given params.
*
* @param array $requestValues
*
* @return RequestInterface
*/
public function buildRequest($method, $uri, $payload, $headers)
{
$requestValues = $this->buildRequestValues($method, $uri, $payload, $headers);
return call_user_func_array(array($this, 'buildRequestInstance'), $requestValues);
}

/**
Expand Down Expand Up @@ -245,6 +279,18 @@ public function setOptions($options)
}
}

/**
* Returns the given value if debugging, an empty instance otherwise.
*
* @param any $param
*
* @return any $param
*/
private function ifDebug($param)
{
return $this->options['debug'] ? $param : null;
}

/**
* Sets up any endpoints to custom classes e.g. $this->transmissions.
*/
Expand Down
19 changes: 18 additions & 1 deletion lib/SparkPost/SparkPostException.php
Expand Up @@ -11,13 +11,20 @@ class SparkPostException extends \Exception
*/
private $body = null;

/**
* Array with the request values sent.
*/
private $request;

/**
* Sets up the custom exception and copies over original exception values.
*
* @param Exception $exception - the exception to be wrapped
*/
public function __construct(\Exception $exception)
public function __construct(\Exception $exception, $request = null)
{
$this->request = $request;

$message = $exception->getMessage();
$code = $exception->getCode();
if ($exception instanceof HttpException) {
Expand All @@ -29,6 +36,16 @@ public function __construct(\Exception $exception)
parent::__construct($message, $code, $exception->getPrevious());
}

/**
* Returns the request values sent.
*
* @return array $request
*/
public function getRequest()
{
return $this->request;
}

/**
* Returns the body.
*
Expand Down
22 changes: 15 additions & 7 deletions lib/SparkPost/SparkPostPromise.php
Expand Up @@ -11,14 +11,20 @@ class SparkPostPromise implements HttpPromise
*/
private $promise;

/**
* Array with the request values sent.
*/
private $request;

/**
* set the promise to be wrapped.
*
* @param HttpPromise $promise
*/
public function __construct(HttpPromise $promise)
public function __construct(HttpPromise $promise, $request = null)
{
$this->promise = $promise;
$this->request = $request;
}

/**
Expand All @@ -29,13 +35,15 @@ public function __construct(HttpPromise $promise)
*/
public function then(callable $onFulfilled = null, callable $onRejected = null)
{
return $this->promise->then(function ($response) use ($onFulfilled) {
$request = $this->request;

return $this->promise->then(function ($response) use ($onFulfilled, $request) {
if (isset($onFulfilled)) {
$onFulfilled(new SparkPostResponse($response));
$onFulfilled(new SparkPostResponse($response, $request));
}
}, function ($exception) use ($onRejected) {
}, function ($exception) use ($onRejected, $request) {
if (isset($onRejected)) {
$onRejected(new SparkPostException($exception));
$onRejected(new SparkPostException($exception, $request));
}
});
}
Expand Down Expand Up @@ -64,9 +72,9 @@ public function wait($unwrap = true)
try {
$response = $this->promise->wait($unwrap);

return $response ? new SparkPostResponse($response) : $response;
return $response ? new SparkPostResponse($response, $this->request) : $response;
} catch (\Exception $exception) {
throw new SparkPostException($exception);
throw new SparkPostException($exception, $this->request);
}
}
}

0 comments on commit f4cb526

Please sign in to comment.