Adding PHP7 type annotations (#523)

* Adding PHP7 type annotations

* cs

* Moved HttpClientConfigurator and RequestBuilder to Mailgun\HttpClient namespace

* fixing tests

* Rebased and fixed tests

* minors

* cs

* Bugfixes

* Typo
This commit is contained in:
Tobias Nyholm 2019-01-09 20:18:58 +01:00 committed by GitHub
parent 4a903b2ec0
commit b725ab728e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 289 additions and 667 deletions

View File

@ -10,7 +10,7 @@
"webmozart/assert": "^1.2"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"phpunit/phpunit": "^7.5",
"php-http/guzzle6-adapter": "^1.0",
"nyholm/psr7": "^1.0",
"nyholm/nsa": "^1.1"

View File

@ -3,11 +3,9 @@
colors="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader">
convertWarningsToExceptions="true">
<testsuites>
<testsuite name="Mailgun test suite">

View File

@ -11,6 +11,7 @@ namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Model\Attachment\Attachment as Model;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
@ -18,11 +19,9 @@ use Mailgun\Model\Attachment\Attachment as Model;
class Attachment extends HttpApi
{
/**
* @param string $url
*
* @return Model
* @return Model|ResponseInterface
*/
public function show($url)
public function show(string $url)
{
Assert::stringNotEmpty($url);
Assert::regex($url, '@https://.*mailgun\.(net|org)/v.+@');

View File

@ -38,11 +38,8 @@ class Domain extends HttpApi
*
* @return IndexResponse
*/
public function index($limit = 100, $skip = 0)
public function index(int $limit = 100, int $skip = 0)
{
Assert::integer($limit);
Assert::integer($skip);
$params = [
'limit' => $limit,
'skip' => $skip,
@ -60,7 +57,7 @@ class Domain extends HttpApi
*
* @return ShowResponse|array|ResponseInterface
*/
public function show($domain)
public function show(string $domain)
{
Assert::stringNotEmpty($domain);
@ -83,7 +80,7 @@ class Domain extends HttpApi
*
* @return CreateResponse|array|ResponseInterface
*/
public function create($domain, $smtpPass = null, $spamAction = null, $wildcard = null)
public function create(string $domain, string $smtpPass = null, string $spamAction = null, bool $wildcard = null)
{
Assert::stringNotEmpty($domain);
@ -112,7 +109,7 @@ class Domain extends HttpApi
*
* @return DeleteResponse|array|ResponseInterface
*/
public function delete($domain)
public function delete(string $domain)
{
Assert::stringNotEmpty($domain);
@ -130,12 +127,9 @@ class Domain extends HttpApi
*
* @return CredentialResponse
*/
public function credentials($domain, $limit = 100, $skip = 0)
public function credentials(string $domain, int $limit = 100, int $skip = 0)
{
Assert::stringNotEmpty($domain);
Assert::integer($limit);
Assert::integer($skip);
$params = [
'limit' => $limit,
'skip' => $skip,
@ -155,7 +149,7 @@ class Domain extends HttpApi
*
* @return CreateCredentialResponse|array|ResponseInterface
*/
public function createCredential($domain, $login, $password)
public function createCredential(string $domain, string $login, string $password)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($login);
@ -181,7 +175,7 @@ class Domain extends HttpApi
*
* @return UpdateCredentialResponse|array|ResponseInterface
*/
public function updateCredential($domain, $login, $pass)
public function updateCredential(string $domain, string $login, string $pass)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($login);
@ -205,7 +199,7 @@ class Domain extends HttpApi
*
* @return DeleteCredentialResponse|array|ResponseInterface
*/
public function deleteCredential($domain, $login)
public function deleteCredential(string $domain, string $login)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($login);
@ -228,7 +222,7 @@ class Domain extends HttpApi
*
* @return ConnectionResponse|ResponseInterface
*/
public function connection($domain)
public function connection(string $domain)
{
Assert::stringNotEmpty($domain);
@ -247,12 +241,9 @@ class Domain extends HttpApi
*
* @return UpdateConnectionResponse|array|ResponseInterface
*/
public function updateConnection($domain, $requireTLS, $noVerify)
public function updateConnection(string $domain, ?bool $requireTLS, ?bool $noVerify)
{
Assert::stringNotEmpty($domain);
Assert::nullOrBoolean($requireTLS);
Assert::nullOrBoolean($noVerify);
$params = [];
if (null !== $requireTLS) {
@ -275,7 +266,7 @@ class Domain extends HttpApi
*
* @return VerifyResponse|array|ResponseInterface
*/
public function verify($domain)
public function verify(string $domain)
{
Assert::stringNotEmpty($domain);

View File

@ -27,7 +27,7 @@ class Event extends HttpApi
*
* @return EventResponse
*/
public function get($domain, array $params = [])
public function get(string $domain, array $params = [])
{
Assert::stringNotEmpty($domain);

View File

@ -16,7 +16,7 @@ use Mailgun\Hydrator\Hydrator;
use Mailgun\Hydrator\NoopHydrator;
use Mailgun\Exception\HttpClientException;
use Mailgun\Exception\HttpServerException;
use Mailgun\RequestBuilder;
use Mailgun\HttpClient\RequestBuilder;
use Psr\Http\Message\ResponseInterface;
/**
@ -41,11 +41,6 @@ abstract class HttpApi
*/
protected $requestBuilder;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
@ -63,7 +58,7 @@ abstract class HttpApi
*
* @throws \Exception
*/
protected function hydrateResponse(ResponseInterface $response, $class)
protected function hydrateResponse(ResponseInterface $response, string $class)
{
if (!$this->hydrator) {
return $response;
@ -79,8 +74,6 @@ abstract class HttpApi
/**
* Throw the correct exception for this error.
*
* @param ResponseInterface $response
*
* @throws \Exception
*/
protected function handleErrors(ResponseInterface $response)
@ -110,10 +103,8 @@ abstract class HttpApi
* @param string $path Request path
* @param array $parameters GET parameters
* @param array $requestHeaders Request Headers
*
* @return ResponseInterface
*/
protected function httpGet($path, array $parameters = [], array $requestHeaders = [])
protected function httpGet(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface
{
if (count($parameters) > 0) {
$path .= '?'.http_build_query($parameters);
@ -136,10 +127,8 @@ abstract class HttpApi
* @param string $path Request path
* @param array $parameters POST parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPost($path, array $parameters = [], array $requestHeaders = [])
protected function httpPost(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface
{
return $this->httpPostRaw($path, $this->createRequestBody($parameters), $requestHeaders);
}
@ -150,10 +139,8 @@ abstract class HttpApi
* @param string $path Request path
* @param array|string $body Request body
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPostRaw($path, $body, array $requestHeaders = [])
protected function httpPostRaw(string $path, $body, array $requestHeaders = []): ResponseInterface
{
try {
$response = $this->httpClient->sendRequest(
@ -172,10 +159,8 @@ abstract class HttpApi
* @param string $path Request path
* @param array $parameters PUT parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPut($path, array $parameters = [], array $requestHeaders = [])
protected function httpPut(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface
{
try {
$response = $this->httpClient->sendRequest(
@ -194,10 +179,8 @@ abstract class HttpApi
* @param string $path Request path
* @param array $parameters DELETE parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpDelete($path, array $parameters = [], array $requestHeaders = [])
protected function httpDelete(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface
{
try {
$response = $this->httpClient->sendRequest(
@ -217,7 +200,7 @@ abstract class HttpApi
*
* @return array
*/
protected function createRequestBody(array $parameters)
private function createRequestBody(array $parameters): array
{
$resources = [];
foreach ($parameters as $key => $values) {

View File

@ -25,11 +25,10 @@ class Ip extends HttpApi
/**
* Returns a list of IPs.
*
* @param bool $dedicated
*
* @return IndexResponse|ResponseInterface
*/
public function index($dedicated = false)
public function index(bool $dedicated = false)
{
Assert::boolean($dedicated);
@ -45,11 +44,10 @@ class Ip extends HttpApi
/**
* Returns a list of IPs assigned to a domain.
*
* @param string $domain
*
* @return IndexResponse|ResponseInterface
*/
public function domainIndex($domain)
public function domainIndex(string $domain)
{
Assert::stringNotEmpty($domain);
@ -61,11 +59,10 @@ class Ip extends HttpApi
/**
* Returns a single ip.
*
* @param string $ip
*
* @return ShowResponse|ResponseInterface
*/
public function show($ip)
public function show(string $ip)
{
Assert::ip($ip);
@ -77,12 +74,10 @@ class Ip extends HttpApi
/**
* Assign a dedicated IP to the domain specified.
*
* @param string $domain
* @param string $ip
*
* @return UpdateResponse|ResponseInterface
*/
public function assign($domain, $ip)
public function assign(string $domain, string $ip)
{
Assert::stringNotEmpty($domain);
Assert::ip($ip);
@ -99,12 +94,11 @@ class Ip extends HttpApi
/**
* Unassign an IP from the domain specified.
*
* @param string $domain
* @param string $ip
*
* @return UpdateResponse|ResponseInterface
*/
public function unassign($domain, $ip)
public function unassign(string $domain, string $ip)
{
Assert::stringNotEmpty($domain);
Assert::ip($ip);

View File

@ -19,10 +19,7 @@ use Mailgun\Model\MailingList\UpdateResponse;
class MailingList extends HttpApi
{
/**
* @return Member
*/
public function member()
public function member(): Member
{
return new Member($this->httpClient, $this->requestBuilder, $this->hydrator);
}
@ -36,7 +33,7 @@ class MailingList extends HttpApi
*
* @throws \Exception
*/
public function pages($limit = 100)
public function pages(int $limit = 100)
{
Assert::integer($limit);
Assert::greaterThan($limit, 0);
@ -62,7 +59,7 @@ class MailingList extends HttpApi
*
* @throws \Exception
*/
public function create($address, $name = null, $description = null, $accessLevel = 'readonly')
public function create(string $address, string $name = null, string $description = null, string $accessLevel = 'readonly')
{
Assert::stringNotEmpty($address);
Assert::nullOrStringNotEmpty($name);
@ -90,7 +87,7 @@ class MailingList extends HttpApi
*
* @throws \Exception
*/
public function show($address)
public function show(string $address)
{
Assert::stringNotEmpty($address);
@ -109,7 +106,7 @@ class MailingList extends HttpApi
*
* @throws \Exception
*/
public function update($address, $parameters = [])
public function update(string $address, array $parameters = [])
{
Assert::stringNotEmpty($address);
Assert::isArray($parameters);
@ -143,7 +140,7 @@ class MailingList extends HttpApi
*
* @throws \Exception
*/
public function delete($address)
public function delete(string $address)
{
Assert::stringNotEmpty($address);

View File

@ -26,24 +26,27 @@ class Member extends HttpApi
*
* @param string $address Address of the mailing list
* @param int $limit Maximum number of records to return (optional: 100 by default)
* @param string|null $subscribed `yes` to lists subscribed, `no` for unsubscribed. list all if null
* @param string|null $subscribed `true` to lists subscribed, `false` for unsubscribed. list all if null
*
* @return IndexResponse
*
* @throws \Exception
*/
public function index($address, $limit = 100, $subscribed = null)
public function index(string $address, int $limit = 100, bool $subscribed = null)
{
Assert::stringNotEmpty($address);
Assert::integer($limit);
Assert::greaterThan($limit, 0);
Assert::oneOf($subscribed, [null, 'yes', 'no']);
$params = [
'limit' => $limit,
'subscribed' => $subscribed,
];
if (true === $subscribed) {
$params['subscribed'] = 'yes';
} elseif (false === $subscribed) {
$params['subscribed'] = 'no';
}
$response = $this->httpGet(sprintf('/v3/lists/%s/members/pages', $address), $params);
return $this->hydrateResponse($response, IndexResponse::class);
@ -59,7 +62,7 @@ class Member extends HttpApi
*
* @throws \Exception
*/
public function show($list, $address)
public function show(string $list, string $address)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
@ -76,27 +79,25 @@ class Member extends HttpApi
* @param string $address Address for the member
* @param string $name Name for the member (optional)
* @param array $vars Array of field => value pairs to store additional data
* @param string $subscribed `yes` to add as subscribed (default), `no` as unsubscribed
* @param string $upsert `yes` to update member if present, `no` to raise error in case of a duplicate member (default)
* @param bool $subscribed `true` to add as subscribed (default), `false` as unsubscribed
* @param bool $upsert `true` to update member if present, `false` to raise error in case of a duplicate member (default)
*
* @return CreateResponse
*
* @throws \Exception
*/
public function create($list, $address, $name = null, array $vars = [], $subscribed = 'yes', $upsert = 'no')
public function create(string $list, string $address, string $name = null, array $vars = [], bool $subscribed = true, bool $upsert = false)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
Assert::nullOrStringNotEmpty($name);
Assert::oneOf($subscribed, ['yes', 'no']);
Assert::oneOf($upsert, ['yes', 'no']);
$params = [
'address' => $address,
'name' => $name,
'vars' => $vars,
'subscribed' => $subscribed,
'upsert' => $upsert,
'subscribed' => $subscribed ? 'yes' : 'no',
'upsert' => $upsert ? 'yes' : 'no',
];
$response = $this->httpPost(sprintf('/v3/lists/%s/members', $list), $params);
@ -109,13 +110,13 @@ class Member extends HttpApi
*
* @param string $list Address of the mailing list
* @param array $members Array of members, each item should be either a single string address or an array of member properties
* @param string $upsert `yes` to update existing members, `no` (default) to ignore duplicates
* @param string $upsert `true` to update existing members, `false` (default) to ignore duplicates
*
* @return UpdateResponse
*
* @throws \Exception
*/
public function createMultiple($list, array $members, $upsert = 'no')
public function createMultiple(string $list, array $members, $upsert = false)
{
Assert::stringNotEmpty($list);
Assert::isArray($members);
@ -129,8 +130,6 @@ class Member extends HttpApi
));
}
Assert::oneOf($upsert, ['yes', 'no']);
foreach ($members as $data) {
if (is_string($data)) {
Assert::stringNotEmpty($data);
@ -164,7 +163,7 @@ class Member extends HttpApi
$params = [
'members' => json_encode($members),
'upsert' => $upsert,
'upsert' => $upsert ? 'yes' : 'no',
];
$response = $this->httpPost(sprintf('/v3/lists/%s/members.json', $list), $params);
@ -183,7 +182,7 @@ class Member extends HttpApi
*
* @throws \Exception
*/
public function update($list, $address, $parameters = [])
public function update(string $list, string $address, array $parameters = [])
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
@ -222,7 +221,7 @@ class Member extends HttpApi
*
* @throws \Exception
*/
public function delete($list, $address)
public function delete(string $list, string $address)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);

View File

@ -14,30 +14,22 @@ use Mailgun\Exception\InvalidArgumentException;
use Mailgun\Message\BatchMessage;
use Mailgun\Model\Message\SendResponse;
use Mailgun\Model\Message\ShowResponse;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Message extends HttpApi
{
/**
* @param string $domain
* @param bool $autoSend
*
* @return BatchMessage
*/
public function getBatchMessage($domain, $autoSend = true)
public function getBatchMessage(string $domain, bool $autoSend = true): BatchMessage
{
return new BatchMessage($this, $domain, $autoSend);
}
/**
* @param string $domain
* @param array $params
*
* @return SendResponse
* @return SendResponse|ResponseInterface
*/
public function send($domain, array $params)
public function send(string $domain, array $params)
{
Assert::string($domain);
Assert::notEmpty($domain);
@ -70,8 +62,10 @@ class Message extends HttpApi
* @param array $recipients with all you send emails to. Including bcc and cc
* @param string $message Message filepath or content
* @param array $params
*
* @return SendResponse|ResponseInterface
*/
public function sendMime($domain, array $recipients, $message, array $params)
public function sendMime(string $domain, array $recipients, string $message, array $params)
{
Assert::string($domain);
Assert::notEmpty($domain);
@ -103,9 +97,9 @@ class Message extends HttpApi
* @param string $url
* @param bool $rawMessage if true we will use "Accept: message/rfc2822" header
*
* @return ShowResponse
* @return ShowResponse|ResponseInterface
*/
public function show($url, $rawMessage = false)
public function show(string $url, bool $rawMessage = false)
{
Assert::notEmpty($url);
@ -120,16 +114,11 @@ class Message extends HttpApi
}
/**
* Prepare a file.
*
* @param string $fieldName
* @param array $filePath array('fileContent' => 'content') or array('filePath' => '/foo/bar')
*
* @return array
*
* @throws InvalidArgumentException
*/
private function prepareFile($fieldName, array $filePath)
private function prepareFile(string $fieldName, array $filePath): array
{
$filename = isset($filePath['filename']) ? $filePath['filename'] : null;
@ -161,12 +150,8 @@ class Message extends HttpApi
/**
* Prepare multipart parameters. Make sure each POST parameter is split into an array with 'name' and 'content' keys.
*
* @param array $params
*
* @return array
*/
private function prepareMultipartParameters(array $params)
private function prepareMultipartParameters(array $params): array
{
$postDataMultipart = [];
foreach ($params as $key => $value) {
@ -184,10 +169,8 @@ class Message extends HttpApi
/**
* Close open resources.
*
* @param array $params
*/
private function closeResources(array $params)
private function closeResources(array $params): void
{
foreach ($params as $param) {
if (is_array($param) && array_key_exists('content', $param) && is_resource($param['content'])) {

View File

@ -18,62 +18,36 @@ use Psr\Http\Message\ResponseInterface;
*/
trait Pagination
{
abstract protected function httpGet($path, array $parameters = [], array $requestHeaders = []);
abstract protected function httpGet(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface;
abstract protected function hydrateResponse(ResponseInterface $response, $className);
abstract protected function hydrateResponse(ResponseInterface $response, string $className);
/**
* @param PagingProvider $response
*
* @return PagingProvider|null
*/
public function nextPage(PagingProvider $response)
public function nextPage(PagingProvider $response): ?PagingProvider
{
return $this->getPaginationUrl($response->getNextUrl(), get_class($response));
}
/**
* @param PagingProvider $response
*
* @return PagingProvider|null
*/
public function previousPage(PagingProvider $response)
public function previousPage(PagingProvider $response): ?PagingProvider
{
return $this->getPaginationUrl($response->getPreviousUrl(), get_class($response));
}
/**
* @param PagingProvider $response
*
* @return PagingProvider|null
*/
public function firstPage(PagingProvider $response)
public function firstPage(PagingProvider $response): ?PagingProvider
{
return $this->getPaginationUrl($response->getFirstUrl(), get_class($response));
}
/**
* @param PagingProvider $response
*
* @return PagingProvider|null
*/
public function lastPage(PagingProvider $response)
public function lastPage(PagingProvider $response): ?PagingProvider
{
return $this->getPaginationUrl($response->getLastUrl(), get_class($response));
}
/**
* @param string $url
* @param string $class
*
* @return PagingProvider|null
*/
private function getPaginationUrl($url, $class)
private function getPaginationUrl(string $url, string $class): ?PagingProvider
{
Assert::stringNotEmpty($class);
if (empty($url)) {
return;
return null;
}
$response = $this->httpGet($url);

View File

@ -31,10 +31,8 @@ class Route extends HttpApi
*
* @return IndexResponse
*/
public function index($limit = 100, $skip = 0)
public function index(int $limit = 100, int $skip = 0)
{
Assert::integer($limit);
Assert::integer($skip);
Assert::greaterThan($limit, 0);
Assert::greaterThanEq($skip, 0);
@ -55,7 +53,7 @@ class Route extends HttpApi
*
* @return ShowResponse
*/
public function show($routeId)
public function show(string $routeId)
{
Assert::stringNotEmpty($routeId);
@ -74,12 +72,9 @@ class Route extends HttpApi
*
* @return CreateResponse
*/
public function create($expression, array $actions, $description, $priority = 0)
public function create(string $expression, array $actions, string $description, int $priority = 0)
{
Assert::string($expression);
Assert::isArray($actions);
Assert::string($description);
Assert::integer($priority);
$params = [
'priority' => $priority,
@ -105,14 +100,14 @@ class Route extends HttpApi
*
* @return UpdateResponse
*/
public function update($routeId, $expression = null, array $actions = [], $description = null, $priority = null)
{
public function update(
string $routeId,
string $expression = null,
array $actions = [],
string $description = null,
int $priority = null
) {
Assert::stringNotEmpty($routeId);
Assert::nullOrString($expression);
Assert::isArray($actions);
Assert::nullOrString($description);
Assert::nullOrInteger($priority);
$params = [];
if (!empty($expression)) {
@ -146,7 +141,7 @@ class Route extends HttpApi
*
* @return DeleteResponse
*/
public function delete($routeId)
public function delete(string $routeId)
{
Assert::stringNotEmpty($routeId);

View File

@ -21,12 +21,9 @@ use Mailgun\Model\Stats\TotalResponse;
class Stats extends HttpApi
{
/**
* @param string $domain
* @param array $params
*
* @return TotalResponse|array
*/
public function total($domain, array $params = [])
public function total(string $domain, array $params = [])
{
Assert::stringNotEmpty($domain);
@ -36,12 +33,9 @@ class Stats extends HttpApi
}
/**
* @param $domain
* @param array $params
*
* @return AllResponse|array
*/
public function all($domain, array $params = [])
public function all(string $domain, array $params = [])
{
Assert::stringNotEmpty($domain);

View File

@ -14,7 +14,7 @@ use Mailgun\Api\Suppression\Bounce;
use Mailgun\Api\Suppression\Complaint;
use Mailgun\Api\Suppression\Unsubscribe;
use Mailgun\Hydrator\Hydrator;
use Mailgun\RequestBuilder;
use Mailgun\HttpClient\RequestBuilder;
/**
* @see https://documentation.mailgun.com/api-suppressions.html
@ -38,11 +38,6 @@ class Suppression
*/
private $hydrator;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
@ -50,26 +45,17 @@ class Suppression
$this->hydrator = $hydrator;
}
/**
* @return Bounce
*/
public function bounces()
public function bounces(): Bounce
{
return new Bounce($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Complaint
*/
public function complaints()
public function complaints(): Complaint
{
return new Complaint($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Unsubscribe
*/
public function unsubscribes()
public function unsubscribes(): Unsubscribe
{
return new Unsubscribe($this->httpClient, $this->requestBuilder, $this->hydrator);
}

View File

@ -32,7 +32,7 @@ class Bounce extends HttpApi
*
* @return IndexResponse
*/
public function index($domain, $limit = 100)
public function index(string $domain, int $limit = 100)
{
Assert::stringNotEmpty($domain);
Assert::range($limit, 1, 10000, '"Limit" parameter must be between 1 and 10000');
@ -52,7 +52,7 @@ class Bounce extends HttpApi
*
* @return ShowResponse
*/
public function show($domain, $address)
public function show(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -69,7 +69,7 @@ class Bounce extends HttpApi
*
* @return CreateResponse
*/
public function create($domain, $address, array $params = [])
public function create(string $domain, string $address, array $params = [])
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -87,7 +87,7 @@ class Bounce extends HttpApi
*
* @return DeleteResponse
*/
public function delete($domain, $address)
public function delete(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -102,7 +102,7 @@ class Bounce extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View File

@ -32,7 +32,7 @@ class Complaint extends HttpApi
*
* @return IndexResponse
*/
public function index($domain, $limit = 100)
public function index(string $domain, int $limit = 100)
{
Assert::stringNotEmpty($domain);
Assert::range($limit, 1, 10000, 'Limit parameter must be between 1 and 10000');
@ -52,7 +52,7 @@ class Complaint extends HttpApi
*
* @return ShowResponse
*/
public function show($domain, $address)
public function show(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -68,7 +68,7 @@ class Complaint extends HttpApi
*
* @return CreateResponse
*/
public function create($domain, $address, $createdAt = null)
public function create(string $domain, string $address, string $createdAt = null)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -90,7 +90,7 @@ class Complaint extends HttpApi
*
* @return DeleteResponse
*/
public function delete($domain, $address)
public function delete(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -105,7 +105,7 @@ class Complaint extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View File

@ -32,7 +32,7 @@ class Unsubscribe extends HttpApi
*
* @return IndexResponse
*/
public function index($domain, $limit = 100)
public function index(string $domain, int $limit = 100)
{
Assert::stringNotEmpty($domain);
Assert::range($limit, 1, 10000, 'Limit parameter must be between 1 and 10000');
@ -52,7 +52,7 @@ class Unsubscribe extends HttpApi
*
* @return ShowResponse
*/
public function show($domain, $address)
public function show(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -69,7 +69,7 @@ class Unsubscribe extends HttpApi
*
* @return CreateResponse
*/
public function create($domain, $address, array $params = [])
public function create(string $domain, string $address, array $params = [])
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -87,7 +87,7 @@ class Unsubscribe extends HttpApi
*
* @return DeleteResponse
*/
public function delete($domain, $address)
public function delete(string $domain, string $address)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
@ -102,7 +102,7 @@ class Unsubscribe extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View File

@ -26,17 +26,13 @@ class Tag extends HttpApi
{
/**
* Returns a list of tags.
*
* @param string $domain
* @param int $limit
*
* @return IndexResponse|ResponseInterface
*/
public function index($domain, $limit = 100)
public function index(string $domain, int $limit = 100)
{
Assert::stringNotEmpty($domain);
Assert::integer($limit);
$params = [
'limit' => $limit,
];
@ -49,12 +45,9 @@ class Tag extends HttpApi
/**
* Returns a single tag.
*
* @param string $domain Name of the domain
* @param string $tag
*
* @return ShowResponse|ResponseInterface
*/
public function show($domain, $tag)
public function show(string $domain, string $tag)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
@ -67,17 +60,13 @@ class Tag extends HttpApi
/**
* Update a tag.
*
* @param string $domain
* @param string $tag
* @param string $description
*
* @return UpdateResponse|ResponseInterface
*/
public function update($domain, $tag, $description)
public function update(string $domain, string $tag, string $description)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
Assert::string($description);
$params = [
'description' => $description,
@ -91,17 +80,13 @@ class Tag extends HttpApi
/**
* Returns statistics for a single tag.
*
* @param string $domain Name of the domain
* @param string $tag
* @param array $params
*
* @return StatisticsResponse|ResponseInterface
*/
public function stats($domain, $tag, array $params)
public function stats(string $domain, string $tag, array $params)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
Assert::isArray($params);
$response = $this->httpGet(sprintf('/v3/%s/tags/%s/stats', $domain, $tag), $params);
@ -111,12 +96,10 @@ class Tag extends HttpApi
/**
* Removes a tag from the account.
*
* @param string $domain Name of the domain
* @param string $tag
*
* @return DeleteResponse|ResponseInterface
*/
public function delete($domain, $tag)
public function delete(string $domain, string $tag)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);

View File

@ -17,7 +17,8 @@ use Mailgun\Model\Webhook\DeleteResponse;
use Mailgun\Model\Webhook\IndexResponse;
use Mailgun\Model\Webhook\ShowResponse;
use Mailgun\Model\Webhook\UpdateResponse;
use Mailgun\RequestBuilder;
use Mailgun\HttpClient\RequestBuilder;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
@ -29,13 +30,7 @@ class Webhook extends HttpApi
*/
private $apiKey;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
* @param string $apiKey
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator, $apiKey)
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator, string $apiKey)
{
parent::__construct($httpClient, $requestBuilder, $hydrator);
$this->apiKey = $apiKey;
@ -46,14 +41,8 @@ class Webhook extends HttpApi
*
* If this function returns FALSE, you must not process the request.
* You should reject the request with status code 403 Forbidden.
*
* @param int $timestamp
* @param string $token
* @param string $signature
*
* @return bool
*/
public function verifyWebhookSignature($timestamp, $token, $signature)
public function verifyWebhookSignature(int $timestamp, string $token, string $signature): bool
{
if (empty($timestamp) || empty($token) || empty($signature)) {
return false;
@ -70,11 +59,9 @@ class Webhook extends HttpApi
}
/**
* @param string $domain
*
* @return IndexResponse
* @return IndexResponse|ResponseInterface
*/
public function index($domain)
public function index(string $domain)
{
Assert::notEmpty($domain);
$response = $this->httpGet(sprintf('/v3/domains/%s/webhooks', $domain));
@ -83,12 +70,9 @@ class Webhook extends HttpApi
}
/**
* @param string $domain
* @param string $webhook
*
* @return ShowResponse
* @return ShowResponse|ResponseInterface
*/
public function show($domain, $webhook)
public function show(string $domain, string $webhook)
{
Assert::notEmpty($domain);
Assert::notEmpty($webhook);
@ -98,13 +82,9 @@ class Webhook extends HttpApi
}
/**
* @param string $domain
* @param string $id
* @param string $url
*
* @return CreateResponse
* @return CreateResponse|ResponseInterface
*/
public function create($domain, $id, $url)
public function create(string $domain, string $id, string $url)
{
Assert::notEmpty($domain);
Assert::notEmpty($id);
@ -121,13 +101,9 @@ class Webhook extends HttpApi
}
/**
* @param string $domain
* @param string $id
* @param string $url
*
* @return UpdateResponse
* @return UpdateResponse|ResponseInterface
*/
public function update($domain, $id, $url)
public function update(string $domain, string $id, string $url)
{
Assert::notEmpty($domain);
Assert::notEmpty($id);
@ -143,12 +119,9 @@ class Webhook extends HttpApi
}
/**
* @param string $domain
* @param string $id
*
* @return DeleteResponse
* @return DeleteResponse|ResponseInterface
*/
public function delete($domain, $id)
public function delete(string $domain, string $id)
{
Assert::notEmpty($domain);
Assert::notEmpty($id);

View File

@ -14,6 +14,6 @@ namespace Mailgun;
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
interface Exception
interface Exception extends \Throwable
{
}

View File

@ -25,23 +25,17 @@ final class HttpClientException extends \RuntimeException implements Exception
/**
* @var array
*/
private $responseBody;
private $responseBody = [];
/**
* @var int
*/
private $responseCode;
/**
* @param string $message
* @param int $code
* @param ResponseInterface|null $response
*/
public function __construct($message, $code, ResponseInterface $response = null)
public function __construct(string $message, int $code, ResponseInterface $response)
{
parent::__construct($message, $code);
if ($response) {
$this->response = $response;
$this->responseCode = $response->getStatusCode();
$body = $response->getBody()->__toString();
@ -51,13 +45,9 @@ final class HttpClientException extends \RuntimeException implements Exception
$this->responseBody = json_decode($body, true);
}
}
}
public static function badRequest(ResponseInterface $response = null)
public static function badRequest(ResponseInterface $response)
{
$message = 'The parameters passed to the API were invalid. Check your inputs!';
if (null !== $response) {
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
$validationMessage = $body;
@ -66,52 +56,42 @@ final class HttpClientException extends \RuntimeException implements Exception
$validationMessage = isset($jsonDecoded['message']) ? $jsonDecoded['message'] : $body;
}
$message = sprintf("%s\n\n%s", $message, $validationMessage);
}
$message = sprintf("The parameters passed to the API were invalid. Check your inputs!\n\n%s", $validationMessage);
return new self($message, 400, $response);
}
public static function unauthorized(ResponseInterface $response = null)
public static function unauthorized(ResponseInterface $response)
{
return new self('Your credentials are incorrect.', 401, $response);
}
public static function requestFailed(ResponseInterface $response = null)
public static function requestFailed(ResponseInterface $response)
{
return new self('Parameters were valid but request failed. Try again.', 402, $response);
}
public static function notFound(ResponseInterface $response = null)
public static function notFound(ResponseInterface $response)
{
return new self('The endpoint you have tried to access does not exist. Check if the domain matches the domain you have configure on Mailgun.', 404, $response);
}
public static function payloadTooLarge(ResponseInterface $response = null)
public static function payloadTooLarge(ResponseInterface $response)
{
return new self('Payload too large, your total attachment size is too big.', 413, $response);
}
/**
* @return ResponseInterface
*/
public function getResponse()
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* @return array
*/
public function getResponseBody()
public function getResponseBody(): array
{
return $this->responseBody;
}
/**
* @return int
*/
public function getResponseCode()
public function getResponseCode(): int
{
return $this->responseCode;
}

View File

@ -16,7 +16,7 @@ use Mailgun\Exception;
*/
final class HttpServerException extends \RuntimeException implements Exception
{
public static function serverError($httpStatus = 500)
public static function serverError(int $httpStatus = 500)
{
return new self('An unexpected error occurred at Mailgun\'s servers. Try again later and contact support if the error still exists.', $httpStatus);
}
@ -26,7 +26,7 @@ final class HttpServerException extends \RuntimeException implements Exception
return new self('Mailgun\'s servers are currently unreachable.', 0, $previous);
}
public static function unknownHttpResponseCode($code)
public static function unknownHttpResponseCode(int $code)
{
return new self(sprintf('Unknown HTTP response code ("%d") received from the API server', $code));
}

View File

@ -7,7 +7,7 @@
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
namespace Mailgun\HttpClient;
use Http\Client\HttpClient;
use Http\Client\Common\PluginClient;
@ -62,10 +62,7 @@ final class HttpClientConfigurator
$this->responseHistory = new History();
}
/**
* @return PluginClient
*/
public function createConfiguredClient()
public function createConfiguredClient(): PluginClient
{
$plugins = [
new Plugin\AddHostPlugin($this->getUriFactory()->createUri($this->endpoint)),
@ -83,54 +80,33 @@ final class HttpClientConfigurator
return new PluginClient($this->getHttpClient(), $plugins);
}
/**
* @param bool $debug
*
* @return HttpClientConfigurator
*/
public function setDebug($debug)
public function setDebug(bool $debug): self
{
$this->debug = $debug;
return $this;
}
/**
* @param string $endpoint
*
* @return HttpClientConfigurator
*/
public function setEndpoint($endpoint)
public function setEndpoint(string $endpoint): self
{
$this->endpoint = $endpoint;
return $this;
}
/**
* @return string
*/
public function getApiKey()
public function getApiKey(): string
{
return $this->apiKey;
}
/**
* @param string $apiKey
*
* @return HttpClientConfigurator
*/
public function setApiKey($apiKey)
public function setApiKey(string $apiKey): self
{
$this->apiKey = $apiKey;
return $this;
}
/**
* @return UriFactory
*/
private function getUriFactory()
private function getUriFactory(): UriFactory
{
if (null === $this->uriFactory) {
$this->uriFactory = UriFactoryDiscovery::find();
@ -139,22 +115,14 @@ final class HttpClientConfigurator
return $this->uriFactory;
}
/**
* @param UriFactory $uriFactory
*
* @return HttpClientConfigurator
*/
public function setUriFactory(UriFactory $uriFactory)
public function setUriFactory(UriFactory $uriFactory): self
{
$this->uriFactory = $uriFactory;
return $this;
}
/**
* @return HttpClient
*/
private function getHttpClient()
private function getHttpClient(): HttpClient
{
if (null === $this->httpClient) {
$this->httpClient = HttpClientDiscovery::find();
@ -163,22 +131,14 @@ final class HttpClientConfigurator
return $this->httpClient;
}
/**
* @param HttpClient $httpClient
*
* @return HttpClientConfigurator
*/
public function setHttpClient(HttpClient $httpClient)
public function setHttpClient(HttpClient $httpClient): self
{
$this->httpClient = $httpClient;
return $this;
}
/**
* @return History
*/
public function getResponseHistory()
public function getResponseHistory(): History
{
return $this->responseHistory;
}

View File

@ -7,7 +7,7 @@
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
namespace Mailgun\HttpClient;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MultipartStream\MultipartStreamBuilder;
@ -46,7 +46,7 @@ class RequestBuilder
*
* @return RequestInterface
*/
public function create($method, $uri, array $headers = [], $body = null)
public function create(string $method, string $uri, array $headers = [], $body = null)
{
if (!is_array($body)) {
return $this->getRequestFactory()->createRequest($method, $uri, $headers, $body);

View File

@ -20,12 +20,9 @@ use Psr\Http\Message\ResponseInterface;
final class ArrayHydrator implements Hydrator
{
/**
* @param ResponseInterface $response
* @param string $class
*
* @return array
*/
public function hydrate(ResponseInterface $response, $class)
public function hydrate(ResponseInterface $response, string $class)
{
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {

View File

@ -18,12 +18,9 @@ use Psr\Http\Message\ResponseInterface;
interface Hydrator
{
/**
* @param ResponseInterface $response
* @param string $class
*
* @return mixed
*
* @throws HydrationException
*/
public function hydrate(ResponseInterface $response, $class);
public function hydrate(ResponseInterface $response, string $class);
}

View File

@ -21,12 +21,9 @@ use Psr\Http\Message\ResponseInterface;
final class ModelHydrator implements Hydrator
{
/**
* @param ResponseInterface $response
* @param string $class
*
* @return ResponseInterface
*/
public function hydrate(ResponseInterface $response, $class)
public function hydrate(ResponseInterface $response, string $class)
{
$body = $response->getBody()->__toString();
$contentType = $response->getHeaderLine('Content-Type');

View File

@ -19,12 +19,9 @@ use Psr\Http\Message\ResponseInterface;
final class NoopHydrator implements Hydrator
{
/**
* @param ResponseInterface $response
* @param string $class
*
* @throws \LogicException
*/
public function hydrate(ResponseInterface $response, $class)
public function hydrate(ResponseInterface $response, string $class)
{
throw new \LogicException('The NoopHydrator should never be called');
}

View File

@ -77,74 +77,52 @@ final class Mailgun
return $this->responseHistory->getLastResponse();
}
/**
* @return Api\Stats
*/
public function stats()
public function stats(): Api\Stats
{
return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Attachment
*/
public function attachment()
public function attachment(): Api\Attachment
{
return new Api\Attachment($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Domain
*/
public function domains()
public function domains(): Api\Domain
{
return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Tag
*/
public function tags()
public function tags(): Api\Tag
{
return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Event
*/
public function events()
public function events(): Api\Event
{
return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Route
*/
public function routes()
public function routes(): Api\Route
{
return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Webhook
*/
public function webhooks()
public function webhooks(): Api\Webhook
{
return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator, $this->apiKey);
}
/**
* @return Api\Message
*/
public function messages()
public function messages(): Api\Message
{
return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Suppression
*/
public function suppressions()
public function ips(): Api\Ip
{
return new Api\Ip($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function suppressions(): Api\Suppression
{
return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
}

View File

@ -30,7 +30,7 @@ class BatchMessage extends MessageBuilder
/**
* @var bool
*/
private $autoSend = true;
private $autoSend;
/**
* @var array
@ -47,12 +47,7 @@ class BatchMessage extends MessageBuilder
*/
private $api;
/**
* @param Message $messageApi
* @param string $domain
* @param bool $autoSend
*/
public function __construct(Message $messageApi, $domain, $autoSend)
public function __construct(Message $messageApi, string $domain, bool $autoSend)
{
$this->api = $messageApi;
$this->domain = $domain;
@ -72,10 +67,8 @@ class BatchMessage extends MessageBuilder
*
* @throws MissingRequiredParameter
* @throws TooManyRecipients
*
* @return BatchMessage
*/
protected function addRecipient($headerName, $address, array $variables)
protected function addRecipient(string $headerName, string $address, array $variables): MessageBuilder
{
if (array_key_exists($headerName, $this->counters['recipients'])) {
if (self::RECIPIENT_COUNT_LIMIT === $this->counters['recipients'][$headerName]) {
@ -101,7 +94,7 @@ class BatchMessage extends MessageBuilder
* @throws RuntimeException
* @throws MissingRequiredParameter
*/
public function finalize()
public function finalize(): void
{
$message = $this->message;
@ -132,7 +125,7 @@ class BatchMessage extends MessageBuilder
/**
* @return string[]
*/
public function getMessageIds()
public function getMessageIds(): array
{
return $this->messageIds;
}

View File

@ -13,7 +13,7 @@ use Mailgun\Exception;
class LimitExceeded extends \Exception implements Exception
{
public static function create($field, $limit)
public static function create(string $field, int $limit)
{
return new self(sprintf('You\'ve exceeded the maximum (%d) %s for a single message.', $limit, $field));
}

View File

@ -13,7 +13,7 @@ use Mailgun\Exception;
class MissingRequiredParameter extends \Exception implements Exception
{
public static function create($parameter, $message = null)
public static function create(string $parameter, string $message = null)
{
if (null === $message) {
$message = 'The parameters passed to the API were invalid. Please specify "%s".';

View File

@ -14,12 +14,12 @@ use Mailgun\Message\MessageBuilder;
class TooManyRecipients extends LimitExceeded implements Exception
{
public static function create($field, $limit = MessageBuilder::RECIPIENT_COUNT_LIMIT)
public static function create(string $field, int $limit = MessageBuilder::RECIPIENT_COUNT_LIMIT)
{
return new self(sprintf('You\'ve exceeded the maximum recipient count (%s) for filed "%s".', $limit, $field));
}
public static function whenAutoSendDisabled($limit = MessageBuilder::RECIPIENT_COUNT_LIMIT)
public static function whenAutoSendDisabled(int $limit = MessageBuilder::RECIPIENT_COUNT_LIMIT)
{
return new self(sprintf('You\'ve exceeded the maximum recipient count (%s) with autosend disabled.', $limit));
}

View File

@ -62,7 +62,7 @@ class MessageBuilder
*
* @return mixed
*/
private function get($params, $key, $default)
private function get(array $params, string $key, $default)
{
if (array_key_exists($key, $params)) {
return $params[$key];
@ -78,10 +78,8 @@ class MessageBuilder
* @var string $first
* @var string $last
* }
*
* @return string
*/
private function getFullName(array $params)
private function getFullName(array $params): string
{
if (isset($params['full_name'])) {
return $this->get($params, 'full_name', '');
@ -98,10 +96,8 @@ class MessageBuilder
* @var string $first
* @var string $last
* }
*
* @return string
*/
protected function parseAddress($address, array $variables)
protected function parseAddress(string $address, array $variables): string
{
$fullName = $this->getFullName($variables);
if (!empty($fullName)) {
@ -120,10 +116,8 @@ class MessageBuilder
* @var string $first
* @var string $last
* }
*
* @return MessageBuilder
*/
protected function addRecipient($headerName, $address, array $variables)
protected function addRecipient(string $headerName, string $address, array $variables): self
{
$compiledAddress = $this->parseAddress($address, $variables);
@ -152,10 +146,8 @@ class MessageBuilder
* }
*
* @throws TooManyRecipients
*
* @return MessageBuilder
*/
public function addToRecipient($address, array $variables = [])
public function addToRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['to'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('to');
@ -176,10 +168,8 @@ class MessageBuilder
* }
*
* @throws TooManyRecipients
*
* @return MessageBuilder
*/
public function addCcRecipient($address, array $variables = [])
public function addCcRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['cc'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('cc');
@ -201,10 +191,8 @@ class MessageBuilder
* }
*
* @throws TooManyRecipients
*
* @return MessageBuilder
*/
public function addBccRecipient($address, array $variables = [])
public function addBccRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['bcc'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('bcc');
@ -224,10 +212,8 @@ class MessageBuilder
* @var string $first
* @var string $last
* }
*
* @return MessageBuilder
*/
public function setFromAddress($address, array $variables = [])
public function setFromAddress(string $address, array $variables = []): self
{
$this->addRecipient('from', $address, $variables);
@ -243,22 +229,15 @@ class MessageBuilder
* @var string $first
* @var string $last
* }
*
* @return MessageBuilder
*/
public function setReplyToAddress($address, array $variables = [])
public function setReplyToAddress(string $address, array $variables = []): self
{
$this->addRecipient('h:reply-to', $address, $variables);
return $this;
}
/**
* @param string $subject
*
* @return MessageBuilder
*/
public function setSubject($subject)
public function setSubject(string $subject): self
{
$this->message['subject'] = $subject;
@ -268,10 +247,8 @@ class MessageBuilder
/**
* @param string $headerName
* @param mixed $headerData
*
* @return MessageBuilder
*/
public function addCustomHeader($headerName, $headerData)
public function addCustomHeader(string $headerName, $headerData): self
{
if (!preg_match('/^h:/i', $headerName)) {
$headerName = 'h:'.$headerName;
@ -290,37 +267,21 @@ class MessageBuilder
return $this;
}
/**
* @param string $textBody
*
* @return MessageBuilder
*/
public function setTextBody($textBody)
public function setTextBody(string $textBody): self
{
$this->message['text'] = $textBody;
return $this;
}
/**
* @param string $htmlBody
*
* @return MessageBuilder
*/
public function setHtmlBody($htmlBody)
public function setHtmlBody(string $htmlBody): self
{
$this->message['html'] = $htmlBody;
return $this;
}
/**
* @param string $attachmentPath
* @param string|null $attachmentName
*
* @return MessageBuilder
*/
public function addAttachment($attachmentPath, $attachmentName = null)
public function addAttachment(string $attachmentPath, string $attachmentName = null): self
{
if (!isset($this->message['attachment'])) {
$this->message['attachment'] = [];
@ -334,13 +295,7 @@ class MessageBuilder
return $this;
}
/**
* @param string $inlineImagePath
* @param string|null $inlineImageName
*
* @return MessageBuilder
*/
public function addInlineImage($inlineImagePath, $inlineImageName = null)
public function addInlineImage(string $inlineImagePath, string $inlineImageName = null): self
{
if (!isset($this->message['inline'])) {
$this->message['inline'] = [];
@ -354,26 +309,17 @@ class MessageBuilder
return $this;
}
/**
* @param bool $enabled
*
* @return MessageBuilder
*/
public function setTestMode($enabled)
public function setTestMode(bool $enabled): self
{
$this->message['o:testmode'] = $this->boolToString($enabled);
$this->message['o:testmode'] = $enabled ? 'yes' : 'no';
return $this;
}
/**
* @param string $campaignId
*
* @throws LimitExceeded
*
* @return MessageBuilder
*/
public function addCampaignId($campaignId)
public function addCampaignId(string $campaignId): self
{
if ($this->counters['attributes']['campaign_id'] >= self::CAMPAIGN_ID_LIMIT) {
throw LimitExceeded::create('campaigns', self::CAMPAIGN_ID_LIMIT);
@ -389,13 +335,9 @@ class MessageBuilder
}
/**
* @param string $tag
*
* @throws LimitExceeded
*
* @return MessageBuilder
*/
public function addTag($tag)
public function addTag(string $tag): self
{
if ($this->counters['attributes']['tag'] >= self::TAG_LIMIT) {
throw LimitExceeded::create('tags', self::TAG_LIMIT);
@ -411,49 +353,36 @@ class MessageBuilder
return $this;
}
/**
* @param bool $enabled
*
* @return MessageBuilder
*/
public function setDkim($enabled)
public function setDkim(bool $enabled): self
{
$this->message['o:dkim'] = $this->boolToString($enabled);
$this->message['o:dkim'] = $enabled ? 'yes' : 'no';
return $this;
}
/**
* @param bool $enabled
*
* @return MessageBuilder
*/
public function setOpenTracking($enabled)
public function setOpenTracking(bool $enabled): self
{
$this->message['o:tracking-opens'] = $this->boolToString($enabled);
$this->message['o:tracking-opens'] = $enabled ? 'yes' : 'no';
return $this;
}
/**
* @param bool $enabled
*
* @return MessageBuilder
*/
public function setClickTracking($enabled)
public function setClickTracking(bool $enabled, bool $htmlOnly = false): self
{
$this->message['o:tracking-clicks'] = $this->boolToString($enabled);
$value = 'no';
if ($enabled) {
$value = 'yes';
if ($htmlOnly) {
$value = 'htmlonly';
}
}
$this->message['o:tracking-clicks'] = $value;
return $this;
}
/**
* @param string $timeDate
* @param string|null $timeZone
*
* @return MessageBuilder
*/
public function setDeliveryTime($timeDate, $timeZone = null)
public function setDeliveryTime(string $timeDate, string $timeZone = null): self
{
if (null !== $timeZone) {
$timeZoneObj = new \DateTimeZone($timeZone);
@ -471,10 +400,8 @@ class MessageBuilder
/**
* @param string $customName
* @param mixed $data
*
* @return MessageBuilder
*/
public function addCustomData($customName, $data)
public function addCustomData(string $customName, $data): self
{
$this->message['v:'.$customName] = json_encode($data);
@ -484,10 +411,8 @@ class MessageBuilder
/**
* @param string $parameterName
* @param mixed $data
*
* @return MessageBuilder
*/
public function addCustomParameter($parameterName, $data)
public function addCustomParameter(string $parameterName, $data): self
{
if (isset($this->message[$parameterName])) {
$this->message[$parameterName][] = $data;
@ -498,41 +423,15 @@ class MessageBuilder
return $this;
}
/**
* @param array $message
*
* @return MessageBuilder
*/
public function setMessage($message)
public function setMessage(array $message): self
{
$this->message = $message;
return $this;
}
/**
* @return array
*/
public function getMessage()
public function getMessage(): array
{
return $this->message;
}
/**
* @param $enabled
*
* @return string
*/
private function boolToString($enabled)
{
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
$enabled = 'yes';
} elseif ('html' === $enabled) {
$enabled = 'html';
} else {
$enabled = 'no';
}
return $enabled;
}
}

View File

@ -20,7 +20,6 @@ class MemberTest extends TestCase
{
$data = [
'limit' => 100,
'subscribed' => null,
];
$api = $this->getApiMock();
@ -45,7 +44,7 @@ class MemberTest extends TestCase
->with('/v3/lists/address/members/pages', $data)
->willReturn(new Response());
$api->index('address', 100, 'yes');
$api->index('address', 100, true);
}
public function testIndexUnsubscribed()
@ -61,7 +60,7 @@ class MemberTest extends TestCase
->with('/v3/lists/address/members/pages', $data)
->willReturn(new Response());
$api->index('address', 100, 'no');
$api->index('address', 100, false);
}
public function testCreate()
@ -80,23 +79,21 @@ class MemberTest extends TestCase
->with('/v3/lists/address/members', $data)
->willReturn(new Response());
$api->create($list = 'address', $address = 'foo@example.com', $name = 'Foo', $vars = [], $subscribed = 'yes', $upsert = 'no');
$api->create($list = 'address', $address = 'foo@example.com', $name = 'Foo', $vars = [], $subscribed = true, $upsert = false);
}
public function testCreateInvalidAddress()
{
$this->setExpectedException(InvalidArgumentException::class);
$api = $this->getApiMock();
$this->expectException(InvalidArgumentException::class);
$api->create('address', '');
}
public function testCreateInvalidSubscribed()
{
$this->setExpectedException(InvalidArgumentException::class);
$api = $this->getApiMock();
$api->create('address', 'foo@example.com', null, [], true);
$this->expectException(InvalidArgumentException::class);
$api->create('', 'foo@example.com');
}
public function testCreateMultiple()
@ -128,12 +125,12 @@ class MemberTest extends TestCase
'name' => 'Billy',
'subscribed' => 'yes',
],
], $upsert = 'no');
], false);
}
public function testCreateMultipleInvalidMemberArgument()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$data = [
'bob@example.com',
@ -151,7 +148,7 @@ class MemberTest extends TestCase
public function testCreateMultipleCountMax1000()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$members = range(1, 1001);
$members = array_map('strval', $members);
@ -180,7 +177,7 @@ class MemberTest extends TestCase
public function testUpdateInvalidArgument()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$data = [
'vars' => 'foo=bar',

View File

@ -32,7 +32,7 @@ class MailingListTest extends TestCase
public function testPagesInvalidArgument()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$api = $this->getApiMock();
$limit = -1;
@ -59,7 +59,7 @@ class MailingListTest extends TestCase
public function testCreateInvalidAddress()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$api = $this->getApiMock();
$api->create($address = '', $name = 'Foo', $description = 'Description', $accessLevel = 'readonly');
@ -67,7 +67,7 @@ class MailingListTest extends TestCase
public function testCreateInvalidAccessLevel()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$api = $this->getApiMock();
$api->create($address = '', $name = 'Foo', $description = 'Description', $accessLevel = 'admin');
@ -86,7 +86,7 @@ class MailingListTest extends TestCase
public function testShowInvalidAddress()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$api = $this->getApiMock();
$api->show('');
@ -109,7 +109,7 @@ class MailingListTest extends TestCase
public function testUpdateInvalidArgument()
{
$this->setExpectedException(InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$data = [
'access_level' => 'foo',

View File

@ -12,14 +12,13 @@ namespace Mailgun\Tests\Api;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Mailgun\Hydrator\ModelHydrator;
use Mailgun\Mailgun;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
* @author Contributors of https://github.com/KnpLabs/php-github-api
*/
abstract class TestCase extends \PHPUnit_Framework_TestCase
abstract class TestCase extends \PHPUnit\Framework\TestCase
{
private $requestMethod;
@ -56,7 +55,7 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase
->method('sendRequest');
}
if (null === $requestClient) {
$requestClient = $this->getMockBuilder('Mailgun\RequestBuilder')
$requestClient = $this->getMockBuilder('Mailgun\HttpClient\RequestBuilder')
->setMethods(['create'])
->getMock();
}
@ -85,7 +84,7 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase
->method('sendRequest')
->willReturn(null === $this->httpResponse ? new Response() : $this->httpResponse);
$requestClient = $this->getMockBuilder('Mailgun\RequestBuilder')
$requestClient = $this->getMockBuilder('Mailgun\HttpClient\RequestBuilder')
->setMethods(['create'])
->getMock();
$requestClient->method('create')
@ -255,22 +254,4 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase
return is_callable($property) ? call_user_func($property, $value) : $value === $property;
}
/**
* Make sure expectException always exists, even on PHPUnit 4.
*
* @param string $exception
* @param string|null $message
*/
public function expectException($exception, $message = null)
{
if (method_exists($this, 'setExpectedException')) {
$this->setExpectedException($exception, $message);
} else {
parent::expectException($exception);
if (null !== $message) {
$this->expectExceptionMessage($message);
}
}
}
}

View File

@ -48,7 +48,7 @@ class WebhookTest extends TestCase
{
$api = $this->getApiInstance('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
$this->assertFalse($api->verifyWebhookSignature('', '', ''));
$this->assertFalse($api->verifyWebhookSignature(0, '', ''));
}
public function testIndex()

View File

@ -7,17 +7,17 @@
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Tests;
namespace Mailgun\Tests\HttpClient;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Http\Message\RequestFactory;
use Mailgun\RequestBuilder;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit_Framework_TestCase;
use Mailgun\HttpClient\RequestBuilder;
use Mailgun\Tests\MailgunTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
class RequestBuilderTest extends PHPUnit_Framework_TestCase
class RequestBuilderTest extends MailgunTestCase
{
/**
* @var MockObject|RequestFactory
@ -72,7 +72,7 @@ class RequestBuilderTest extends PHPUnit_Framework_TestCase
}),
$this->equalTo('content')
)
->willReturn($request = $this->getMock(RequestInterface::class));
->willReturn($request = $this->getMockBuilder(RequestInterface::class)->getMock());
$result = $this->requestBuilder
->create('GET', 'http://foo.bar', ['Content-Type' => 'application/json'], 'content');
@ -108,7 +108,7 @@ class RequestBuilderTest extends PHPUnit_Framework_TestCase
$multipartStreamBuilder
->expects($this->once())
->method('build')
->willReturn($stream = $this->getMock(StreamInterface::class));
->willReturn($stream = $this->getMockBuilder(StreamInterface::class)->getMock());
$multipartStreamBuilder
->expects($this->once())
@ -134,7 +134,7 @@ class RequestBuilderTest extends PHPUnit_Framework_TestCase
}),
$this->equalTo($stream)
)
->willReturn($request = $this->getMock(RequestInterface::class));
->willReturn($request = $this->getMockBuilder(RequestInterface::class)->getMock());
$this->requestBuilder->setMultipartStreamBuilder($multipartStreamBuilder);
$result = $this->requestBuilder

View File

@ -9,6 +9,8 @@
namespace Mailgun\Tests;
abstract class MailgunTestCase extends \PHPUnit_Framework_TestCase
use PHPUnit\Framework\TestCase;
abstract class MailgunTestCase extends TestCase
{
}

View File

@ -13,9 +13,10 @@ use Mailgun\Api\Message;
use Mailgun\Message\BatchMessage;
use Mailgun\Message\Exceptions\MissingRequiredParameter;
use Mailgun\Model\Message\SendResponse;
use Mailgun\Tests\MailgunTestCase;
use Nyholm\NSA;
class BatchMessageTest extends \PHPUnit_Framework_TestCase
class BatchMessageTest extends MailgunTestCase
{
/**
* @var BatchMessage
@ -146,7 +147,7 @@ class BatchMessageTest extends \PHPUnit_Framework_TestCase
$this->batchMessage->setSubject('This is the subject of the message!');
$this->batchMessage->setTextBody('This is the text body of the message!');
$this->setExpectedException(MissingRequiredParameter::class);
$this->expectException(MissingRequiredParameter::class);
$this->batchMessage->finalize();
}
@ -155,7 +156,7 @@ class BatchMessageTest extends \PHPUnit_Framework_TestCase
$this->batchMessage->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
$this->batchMessage->setSubject('This is the subject of the message!');
$this->batchMessage->setTextBody('This is the text body of the message!');
$this->setExpectedException(MissingRequiredParameter::class);
$this->expectException(MissingRequiredParameter::class);
$this->batchMessage->finalize();
}
@ -164,7 +165,7 @@ class BatchMessageTest extends \PHPUnit_Framework_TestCase
$this->batchMessage->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
$this->batchMessage->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
$this->batchMessage->setTextBody('This is the text body of the message!');
$this->setExpectedException(MissingRequiredParameter::class);
$this->expectException(MissingRequiredParameter::class);
$this->batchMessage->finalize();
}
@ -173,7 +174,7 @@ class BatchMessageTest extends \PHPUnit_Framework_TestCase
$this->batchMessage->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
$this->batchMessage->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
$this->batchMessage->setSubject('This is the subject of the message!');
$this->setExpectedException(MissingRequiredParameter::class);
$this->expectException(MissingRequiredParameter::class);
$this->batchMessage->finalize();
}
}

View File

@ -10,9 +10,10 @@
namespace Mailgun\Tests\Message;
use Mailgun\Message\MessageBuilder;
use Mailgun\Tests\MailgunTestCase;
use Nyholm\NSA;
class MessageBuilderTest extends \PHPUnit_Framework_TestCase
class MessageBuilderTest extends MailgunTestCase
{
/**
* @var MessageBuilder
@ -223,15 +224,10 @@ class MessageBuilderTest extends \PHPUnit_Framework_TestCase
$this->messageBuilder->setTestMode(true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:testmode' => 'yes'], $message);
$this->messageBuilder->setTestMode(false);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:testmode' => 'no'], $message);
$this->messageBuilder->setTestMode('yes');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:testmode' => 'yes'], $message);
$this->messageBuilder->setTestMode('no');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:testmode' => 'no'], $message);
}
public function testAddCampaignId()
@ -256,15 +252,10 @@ class MessageBuilderTest extends \PHPUnit_Framework_TestCase
$this->messageBuilder->setDkim(true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:dkim' => 'yes'], $message);
$this->messageBuilder->setDkim(false);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:dkim' => 'no'], $message);
$this->messageBuilder->setDkim('yes');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:dkim' => 'yes'], $message);
$this->messageBuilder->setDkim('no');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:dkim' => 'no'], $message);
}
public function testSetClickTracking()
@ -272,15 +263,18 @@ class MessageBuilderTest extends \PHPUnit_Framework_TestCase
$this->messageBuilder->setClickTracking(true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-clicks' => 'yes'], $message);
$this->messageBuilder->setClickTracking(false);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-clicks' => 'no'], $message);
$this->messageBuilder->setClickTracking('yes');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-clicks' => 'yes'], $message);
$this->messageBuilder->setClickTracking('no');
$this->messageBuilder->setClickTracking(false, true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-clicks' => 'no'], $message);
$this->messageBuilder->setClickTracking(true, true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-clicks' => 'htmlonly'], $message);
}
public function testSetOpenTracking()
@ -288,15 +282,10 @@ class MessageBuilderTest extends \PHPUnit_Framework_TestCase
$this->messageBuilder->setOpenTracking(true);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-opens' => 'yes'], $message);
$this->messageBuilder->setOpenTracking(false);
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-opens' => 'no'], $message);
$this->messageBuilder->setOpenTracking('yes');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-opens' => 'yes'], $message);
$this->messageBuilder->setOpenTracking('no');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:tracking-opens' => 'no'], $message);
}
public function testSetDeliveryTime()
@ -304,12 +293,15 @@ class MessageBuilderTest extends \PHPUnit_Framework_TestCase
$this->messageBuilder->setDeliveryTime('January 15, 2014 8:00AM', 'CST');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 -0600'], $message);
$this->messageBuilder->setDeliveryTime('January 15, 2014 8:00AM', 'UTC');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 +0000'], $message);
$this->messageBuilder->setDeliveryTime('January 15, 2014 8:00AM');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 +0000'], $message);
$this->messageBuilder->setDeliveryTime('1/15/2014 13:50:01', 'CDT');
$message = $this->messageBuilder->getMessage();
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 13:50:01 -0600'], $message);

View File

@ -9,6 +9,8 @@
namespace Mailgun\Tests\Model;
abstract class BaseModelTest extends \PHPUnit_Framework_TestCase
use PHPUnit\Framework\TestCase;
abstract class BaseModelTest extends TestCase
{
}