Compare commits

...

163 commits

Author SHA1 Message Date
Vitaliy Chesnokov
230b2ff67b
Explicit creation and deletion of a temporary file 2019-11-26 18:29:31 +03:00
Vitaliy Chesnokov
b27bab7b9f
Close resources on message send http exception 2019-11-26 17:42:57 +03:00
iwahara
5975310f0e fix. 2019-10-15 18:50:34 +01:00
iwahara
aeb82f7ac1 fix code format 2019-10-15 18:50:34 +01:00
iwahara
58c03ac34b fix code format error. 2019-10-15 18:50:34 +01:00
iwahara
14346359f1 format doc comment. 2019-10-15 18:50:34 +01:00
iwahara
c086ea8b6f format doc comment. 2019-10-15 18:50:34 +01:00
iwahara
8390bdd803 add unsubscribe delete parameter. 2019-10-15 18:50:34 +01:00
Tonin R. Bolzan
16d0a04014 Update Examples
Method `::configure` replaced by a constructor
2019-09-17 18:11:18 +01:00
David Garcia
4055fea33d Update Readme for Release 3.0.0
Provide additional notes for contribution.
Fix minor typos.
2019-09-13 21:14:46 +01:00
David Garcia
0345a5b7a7 Update Changelog for Release 3.0.0 2019-09-13 21:14:46 +01:00
David Garcia
22bc28947a Link Packagist's PSR7 Implementations and Clients
Link https://packagist.org/providers/php-http/client-implementation
2019-09-13 19:48:06 +01:00
Littlesqx
7b674dd2ca Fix mismatch 2019-08-30 19:49:02 +01:00
Littlesqx
4a2a4fe4a5 Add forbidden response test cases 2019-08-30 19:49:02 +01:00
Littlesqx
e0cb8023a7 Update forbidden response, set message from response body content. 2019-08-30 19:49:02 +01:00
Littlesqx
300dcc18bb Remove rule for ignoring .idea 2019-08-30 19:49:02 +01:00
徐哈哈
c88f1bc174 Add Forbidden response 2019-08-30 19:49:02 +01:00
David Garcia
5cad522151 Update README.md 2019-08-29 22:59:58 +01:00
Nathan Perkins
2db0619d8a Revise domain creation assertions and add tests
Based on feedback from @DavidGarciaCat.
2019-08-29 22:25:39 +01:00
Nathan Perkins
c9bbf8e45f Revise domain creation to allow select arguments
Previously, passing `$spamAction` only worked if an SMTP password (`$smtpPass`) was provided. This revision de-couples those two arguments.

In addition, it adds support for the `$wildcard` arguments (which appeared to not be used before).

Finally, this revision adds SMTP password validation (the same used in the `credentials` method).
2019-08-29 22:25:39 +01:00
Kevin Pohl
ae9a549e7f sort api methods by name 2019-05-18 01:34:42 +01:00
Kevin Pohl
4d77573ae6 add missing mailingList method 2019-05-18 01:34:42 +01:00
Tobias Nyholm
f30985c925 Added return types 2019-04-19 21:37:48 +01:00
Tobias Nyholm
c3ea40c94e
Fixed a few PRs and some cleanup (#589)
* fix for #581

* fix for #582

* Remove final

This will fix #584

* Type cast to string properly

* Convert to json string if needed

* cs
2019-04-09 20:37:32 +02:00
Tobias Nyholm
ad67b4179c
Make sure Attachment::show always return ResponseInterface (#590) 2019-04-09 20:10:33 +02:00
Louis Coulet
7705cb7666 Fix attachment and inline image renaming (#571)
* Fix file renaming

* Fix file renaming
2019-04-09 19:12:50 +02:00
Martijn
2162ade61a Update mime message docs for new Swiftmailer version and lib parameter update (#585) 2019-04-09 11:16:50 +02:00
David Garcia
abf2a0ae55 Mailgun-461: Validate limits (#565)
* Check limit for paginated domains

* Check limit for paginated events

* Check limit for paginated rotues

* Check limit for paginated tags

* Check limit for paginated mailing lists

* Replace unexpected Assert
2019-02-18 16:43:59 +01:00
Ilya Chekalskiy
7e438f4b4e Fixes #573 (#574)
because `\Http\Client\Common\HttpMethodsClientInterface` is an interface, not a class
2019-02-18 16:41:38 +01:00
David Baker
6ff2a713af Fixed a typo in the CHANGELOG 2019-02-12 21:45:20 +00:00
Tobias Nyholm
bbb88f0113 Make sure the link is updated 2019-02-03 21:58:26 +00:00
Nyholm
92d9d5ead8 minon 2019-02-03 21:57:45 +00:00
Nyholm
15624afa79 Adding Roave BC check 2019-02-03 21:57:45 +00:00
Nyholm
f84f757ae2 Use PSR-17 and mark classes as final 2019-02-03 21:55:05 +00:00
David Garcia
466af8b9a8 Update README.md
Co-Authored-By: Nyholm <tobias.nyholm@gmail.com>
2019-02-03 21:40:14 +00:00
Tobias Nyholm
f50304aa65 Show that we supoprt PSR-18 2019-02-03 21:40:14 +00:00
Alex Fesiuk
0bcc9b3aa5 Add link to the Drupal module. (#559) 2019-02-02 15:18:00 +01:00
Tobias Nyholm
cb6aed8170
Added 2.8.1 changelog (#558) 2019-02-02 08:30:58 +01:00
Tobias Nyholm
6954b4dd2a
Use PSR-18 (#522)
* Use PSR-18

* minor fixes

* phpstan fixes

* cs
2019-02-02 08:30:04 +01:00
David Garcia
398989de61 Include API endpoint in README (#557) 2019-02-02 08:09:51 +01:00
David Garcia
c51c6b10a0 Revert "Add helper for MailingList"
This reverts commit 787811d08b.
2019-01-30 00:08:47 +00:00
David Garcia
b18b4b4f5f Revert "Fix PHPStan validation error"
This reverts commit 3329924ebc.
2019-01-30 00:08:47 +00:00
David Garcia
3329924ebc Fix PHPStan validation error
Class Mailgun\Api\MailingList referenced with incorrect case: Mailgun\API\MailingList.
2019-01-29 23:52:40 +00:00
David Garcia
787811d08b Add helper for MailingList 2019-01-29 23:52:40 +00:00
Tobias Nyholm
cbb13527b9
Minor cleanup and cs (#550)
* Minor cleanup and cs

* minor
2019-01-23 10:35:58 +01:00
Radoje Albijanic
a79b8bb86f CS fixes 2019-01-23 00:46:28 +00:00
Radoje Albijanic
58a353e5f3 Refactor models to php7 2019-01-23 00:46:28 +00:00
Radoje Albijanic
272033dff2 Refactor Tag models to php7 code (#548)
* Refactor models to php7 code

* return model from create method fix
2019-01-22 18:38:44 +01:00
Radoje Albijanic
259d91cb75 Update Suppression models to php7 (#547)
* PHP7 code in Suppression/Bounce

* PHP7 code in Suppression/Complaint and some fixes

* PHP7 code in Suppression/Unsubscribe and some fixes

* Minor

* Empty constructors, changed DateTimeImmutable instead of DateTime

* Code format

* Refactor and consistency fixes

* Nullable getter return values, nullable address fixes
2019-01-22 16:43:20 +01:00
Nyholm
2fe264038b Bugfix 2019-01-20 11:03:18 +00:00
Nyholm
997d545e61 Bugfixes 2019-01-20 11:03:18 +00:00
Nyholm
d0cafddeab Moved MailingList, Message and Route to PHP7 code 2019-01-20 11:03:18 +00:00
Nyholm
ac056e9f75 Updated paging to PHP7 2019-01-20 11:01:02 +00:00
Nyholm
61ae9bc945 Updating Stats models to PHP7 code 2019-01-20 10:59:47 +00:00
Tobias Nyholm
a7f8c14fe8 Cs 2019-01-17 08:31:01 +00:00
Nyholm
9dab02afd4 Make PHP-stan happy 2019-01-17 08:31:01 +00:00
Nyholm
28a4454c63 Fixed PHP7 on Event model and Ip model 2019-01-17 08:31:01 +00:00
Tobias Nyholm
51cff9dbdc cs 2019-01-15 10:43:26 +00:00
Nyholm
47ef0542f0 Updated other domain models 2019-01-15 10:43:26 +00:00
Nyholm
0c3b716cf2 Updated some models with PHP 7 code 2019-01-15 10:43:26 +00:00
Nyholm
3fbd33f640 Make sure we dont use any risky tests 2019-01-12 16:56:42 +00:00
Nyholm
0f54332d0e CS and fixes 2019-01-12 10:34:44 +00:00
Nyholm
2ec2c16227 Added PHP7 code and did some refactoring. 2019-01-12 10:34:44 +00:00
Nyholm
2b60fba811 Moved Mailgun\Model\Route\Response to Mailgun\Model\Route 2019-01-12 10:28:05 +00:00
David Garcia
6a943ddce3 Include missed use statements 2019-01-10 22:15:40 +00:00
David Garcia
de2902aac4 Review assets 2019-01-10 22:15:40 +00:00
David Garcia
88a9e4b1ff Relocate files 2019-01-10 22:15:40 +00:00
David Garcia
c40fe862cc Remove removed file
It was restored as part of a rebase.
Removing it again not to cause a namespace\class conflict.
2019-01-10 22:15:40 +00:00
David Garcia
f3566026b6 Remove egulias/email-validator and dependencies 2019-01-10 22:15:40 +00:00
David Garcia
5927cb162e Add method to get access to Email Validation 2019-01-10 22:15:40 +00:00
David Garcia
961ae177fa Add new lines to improve readability 2019-01-10 22:15:40 +00:00
David Garcia
2c98efc519 Re-order API methods by name
Easier to read
2019-01-10 22:15:40 +00:00
David Garcia
9f61a1e6dc Missed annotation 2019-01-10 22:15:40 +00:00
David Garcia
f775795b85 Test EmailValidation Model 2019-01-10 22:15:40 +00:00
David Garcia
39feab32e5 Remove unused use statement 2019-01-10 22:15:40 +00:00
David Garcia
34b33a9127 Add Header comment 2019-01-10 22:15:40 +00:00
David Garcia
df7043343e Test Parse model for Parseable and Unparseable data 2019-01-10 22:15:40 +00:00
David Garcia
6fc5b1e938 Test Parts model 2019-01-10 22:15:40 +00:00
David Garcia
8cb9a0e48a Provide test to parse a valid email address 2019-01-10 22:15:40 +00:00
David Garcia
2c37651097 Remove non-required tests
Egulias/EmailValidator validates these cases,
is useless to test it
2019-01-10 22:15:40 +00:00
David Garcia
18d948be0f Provide test to validate a valid email address 2019-01-10 22:15:40 +00:00
David Garcia
3f097bb178 Add EmailValidationTest 2019-01-10 22:15:40 +00:00
David Garcia
f12480e313 Remove public endpoints & implement private endpoints 2019-01-10 22:15:40 +00:00
David Garcia
e90f829eb4 Add ParsePesponse 2019-01-10 22:15:40 +00:00
David Garcia
0039e26be2 Add model to map the Parse response 2019-01-10 22:15:40 +00:00
David Garcia
1fb0d0bbc5 Email Validation does not return a key name, just the resource itself 2019-01-10 22:15:40 +00:00
David Garcia
3cf9aca200 StyleCI fixes 2019-01-10 22:15:40 +00:00
David Garcia
d15dbc4f69 Extract the email address from the string
me@davidgarcia.cat => me@davidgarcia.cat
David Garcia <me@davidgarcia.cat> => me@davidgarcia.cat
David Garcia me@davidgarcia.cat => me@davidgarcia.cat
David me@davidgarcia.cat Garcia => me@davidgarcia.cat
2019-01-10 22:15:40 +00:00
David Garcia
756b63ef54 Provide the EmailValidator entry point to send the API requests
So far we just validate the provided arguments.
Waiting for @Nyholm confirmation about the best way to proceed.
Please refer to
https://github.com/mailgun/mailgun-php/issues/191#issuecomment-350133021
2019-01-10 22:15:40 +00:00
David Garcia
682d7919ad Update error messages and provide @author annotation
http://docs.phpdoc.org/references/phpdoc/tags/author.html
2019-01-10 22:15:40 +00:00
David Garcia
e94334b4f1 Provide new Assert to validate an email address 2019-01-10 22:15:40 +00:00
David Garcia
77b50d3d17 Provide Validate Response 2019-01-10 22:15:40 +00:00
David Garcia
96b2242d5b Provide model to map the Email Validation 2019-01-10 22:15:40 +00:00
David Garcia
3079b8a75c Provide model to map the Email Validation Parts 2019-01-10 22:15:40 +00:00
David Garcia
f7b9fe7f79 composer require egulias/email-validator 2019-01-10 22:15:40 +00:00
Tobias Nyholm
a1ca1a3b2f
Added PHPStan test (#537)
* Added PHPStan test

This will fix #536

* Somce code style updates
2019-01-10 20:29:58 +01:00
Tobias Nyholm
3b3e977995
Added changelog for 3.0.0 (#525) 2019-01-10 17:33:11 +01:00
Nyholm
750a7270e3 cs 2019-01-10 08:25:29 +00:00
Nyholm
34432e0517 Minor bugfixes detected with PHPStan 2019-01-10 08:25:29 +00:00
Nyholm
dd7c1d2361 Added new CS rules
Declare strict and no superfluous phpdoc
2019-01-10 08:25:29 +00:00
Nyholm
6dff177387 typo 2019-01-09 20:51:05 +00:00
Nyholm
f915b103a3 cs 2019-01-09 20:51:05 +00:00
Nyholm
b619b66732 Adding tag aggregates 2019-01-09 20:51:05 +00:00
Tobias Nyholm
fb9892f1f8
Added PHPStan action (#530) 2019-01-09 20:36:21 +01:00
Tobias Nyholm
b725ab728e
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
2019-01-09 20:18:58 +01:00
Tobias Nyholm
4a903b2ec0
Added test for BC breaks (#531)
* Added test for BC breaks

* typo

* Disable the BC test

* Update .travis.yml

* Try to disable test better
2019-01-09 20:17:37 +01:00
Tobias Nyholm
6e65a0613e Updated links 2019-01-07 18:38:45 +00:00
Tobias Nyholm
6d5d396f79 Removed some badges 2019-01-07 08:19:41 +00:00
Tobias Nyholm
538ea52b37
Removed "final" for classes with known sub-classes (#520) 2019-01-07 06:15:44 +01:00
Tobias Nyholm
519fd7a674
Added proper PHP CS fixer rules (#527)
* Added proper PHP CS fixer rules

* Adding Symfony cs rules

* Updated CS on tests
2019-01-07 06:12:53 +01:00
Tobias Nyholm
6aecbd5be4
Updated composer scripts to run tests (#519) 2019-01-06 10:37:07 +01:00
Tobias Nyholm
e341a44a5c
Removed deprecated code (#521)
* Removed deprecated code

* cs

* Removed more deprecated code

* minor
2019-01-06 10:07:06 +01:00
Matěj Humpál
12fee2f714 MessageBuilder setters entirely fluent (#507) 2019-01-06 10:06:52 +01:00
Tobias Nyholm
90eb1d6d32
Drop PHP5 (#518)
* drop PHP5

* Added branch alias
2019-01-06 09:01:37 +01:00
Tobias Nyholm
1bcce53387
Use PSR-4 (#517) 2019-01-06 08:34:49 +01:00
Tobias Nyholm
1623c7e48a
Update composer.json (#428) 2019-01-06 08:14:24 +01:00
Tobias Nyholm
7020c01cca
Make all model constructors private (#512) 2019-01-06 08:14:07 +01:00
Tobias Nyholm
e32031f671
Make all models final (#513) 2019-01-06 08:13:29 +01:00
Tobias Nyholm
da5ccde2a7
Adding support for Mailing list (#514)
* Adding Mailing list API

* Added tests

* cs

* Fixed the tests

* code cleanup
2019-01-06 08:11:37 +01:00
David Garcia
4b0611df15 Prepare for 2.8.0 (#516)
* Prepare for 2.8.0

* Update CHANGELOG.md
2019-01-06 08:05:56 +01:00
Tobias Nyholm
56655ad6c0
Added IP API class, models and test (#515)
* Added IP API class, models and test

* cs

* bugfix
2019-01-05 20:31:38 +01:00
Tobias Nyholm
c0a386027b
Added more tests for models (#511)
* Added more tests for models

* cs
2019-01-05 20:30:55 +01:00
Tobias Nyholm
09113482ea
Added "complaints" to TotalResponse (#509) 2019-01-05 19:56:55 +01:00
Paul R Rogers
02e3191bc9 Change exception message of HttpClientException when badRequest to us… (#466)
* Change exception message of HttpClientException when badRequest to use server content's message to aid resolving problems with user input.

* style(HttpClientException): Removed space to comply with styleCI.

* Fix missing assoc flag.

* Refactor to reuse constructor parsing when passing along server error.
Add tests covering passing along of server message.

* Updated tests

* cs

* bugfix
2019-01-05 12:52:40 +01:00
Matias Barletta
07da83776a fix: Validate file name length (#463)
* fix: Validate file name length

$message could contain a large email text that if sent to is_file it could break with this error:
` is_file(): File name is longer than the maximum allowed path `
This validation prevents using is_file if the $message is longer than the allowed path.

* style: Fix extra space

* Added a small test

* cs

* cs
2019-01-05 12:44:50 +01:00
Tobias Nyholm
7b24312f6c
Added support for HTTPlug 2.0 (#510) 2019-01-05 09:10:36 +01:00
Tobias Nyholm
59f67e8671
Updated changelog for 2.7.0 (#508) 2019-01-05 08:54:09 +01:00
David Garcia
ce641a6846 Prepare for 2.7.0 (#481)
* Prepare for 2.7.0

* Remove `declare(strict_types=1)`

* Remove missed `declare(strict_types=1)`
2019-01-05 08:24:22 +01:00
Tobias Nyholm
d4e4d4efbe
Close open resources (#473)
* Make sure to close any open resources

* Fixed test
2019-01-05 08:23:41 +01:00
Matěj Humpál
80a82508c7 Added deprecated notices to non-fluent MessageBuilder setters (#505) 2019-01-03 12:16:01 +01:00
Matěj Humpál
5398e0ad9c Added throws RuntimeException annotation to BatchMessage (#506) 2019-01-03 11:38:58 +01:00
Matěj Humpál
54aa0a7553 Fluent interface for MessageBuilder and BatchMessage 2019-01-03 09:56:56 +00:00
Arliee
1f5bd4200d Fix type error when creating tags (#501)
* Fix fatal error due to not using DateTime instead of string when creating a tag.

* Add unit tests to prove tag creation.

* Add unit tests to prove tag creation.

* Add first seen and last seen accessors to tags, and unit tests to prove correctness.
2019-01-03 10:55:24 +01:00
Tobias Nyholm
bec1da39aa
Removed integration tests. (#490) 2018-12-09 11:45:32 +00:00
Kuma
453b104bfd fix: typo (#500) 2018-11-29 09:37:44 +01:00
semijoelon
36be6c3f30 Fixed broken link in README.md 2018-10-29 21:42:05 +00:00
semijoelon
bc637a7282 Fixed broken link in README.md 2018-10-29 21:42:05 +00:00
Ruud Kamphuis
3fb0f8210e MessageBuilder > addBccRecipient > Make $variables optional (#485)
This way, it's the same as `addToRecipient` and `addCcRecipient`
2018-09-07 22:37:59 +02:00
Tobias Nyholm
a4aba16061
Added a way to get attachments (#476)
* Added a way to get attachments

* Added some tests

* cs

* minor

* Removed declare_strict

* Typos

* Bugfixes

* Fixed bugs
2018-08-09 18:59:38 +02:00
Nyholm
0c70fa1f0e Make BaseModelTest abstract 2018-08-08 20:50:52 +01:00
Nyholm
6229b39aa3 cs 2018-08-08 20:50:52 +01:00
Nyholm
94d0406bcc FIXED A BUG! 2018-08-08 20:50:52 +01:00
Nyholm
0145ddd481 Added more tests 2018-08-08 20:50:52 +01:00
Nyholm
61c0f32dfb cs 2018-08-08 20:50:52 +01:00
Nyholm
17eafbf9c9 Added tests for our models 2018-08-08 20:50:52 +01:00
Nyholm
2337184f85 Added docs 2018-08-08 20:49:30 +01:00
Nyholm
860d49d9d2 Add endpoint to the create function 2018-08-08 20:49:30 +01:00
Nyholm
1835bc28d7 cs 2018-08-08 20:48:35 +01:00
Nyholm
1ed1c2557c Added test for webhook 2018-08-08 20:48:35 +01:00
Nyholm
6e209aaee2 Added Unsubscribe test 2018-08-08 20:48:35 +01:00
Nyholm
fa30639f99 Added complaint test 2018-08-08 20:48:35 +01:00
Nyholm
55547572aa Added bounce test 2018-08-08 20:48:35 +01:00
Nyholm
d6e48c6bc2 Added test for Message API 2018-08-08 20:48:35 +01:00
Nyholm
15bd5ae156 Added tests for Route 2018-08-08 20:48:35 +01:00
Nyholm
42503f72ce Added test for Domain API 2018-08-08 20:48:35 +01:00
Nyholm
afc8671eac We need both getApiMock and getApiInstance 2018-08-08 20:48:35 +01:00
Nyholm
75bab3016c cs 2018-08-08 20:48:35 +01:00
Nyholm
3d81db203e Add tests 2018-08-08 20:48:35 +01:00
Nyholm
bdcca2db0d Added more mock for tests 2018-08-08 20:48:35 +01:00
Nyholm
952198a5d7 Disable duplicate code warning 2018-08-04 21:22:47 +01:00
Tobias Nyholm
eb07576e6a
Ported MessageBuilder and BatchMessage (#472)
* Ported MessageBuilder and BatchMessage

* Added test for MessageBuilder

* Added test for BatchMessageTest

* cs

* cs

* Removed PHP7 code
2018-08-04 21:30:15 +02:00
David Garcia
48e5b8956b Suggest packages used on Dev (#440) 2018-08-04 15:18:41 +02:00
Radoje Albijanic
83c5f76f87 Cast campaign ID-s to string (#460)
* 413 error proper handle.

* Cast campaign id-s to string. Added tests for that.

* Style fixes
2018-04-09 18:51:09 +02:00
260 changed files with 9554 additions and 8431 deletions

16
.github/main.workflow vendored Normal file
View file

@ -0,0 +1,16 @@
workflow "Main" {
on = "push"
resolves = ["Roave BC Check", "PHPStan"]
}
action "Roave BC Check" {
uses = "docker://nyholm/roave-bc-check-ga"
secrets = ["GITHUB_TOKEN"]
args = ""
}
action "PHPStan" {
uses = "docker://oskarstark/phpstan-ga"
secrets = ["GITHUB_TOKEN"]
args = "analyse"
}

37
.php_cs
View file

@ -1,13 +1,32 @@
<?php
/*
* In order to make it work, fabpot/php-cs-fixer and sllh/php-cs-fixer-styleci-bridge must be installed globally
* with composer.
*
* @link https://github.com/Soullivaneuh/php-cs-fixer-styleci-bridge
* @link https://github.com/FriendsOfPHP/PHP-CS-Fixer
*/
$header = <<<TXT
Copyright (C) 2013 Mailgun
use SLLH\StyleCIBridge\ConfigBridge;
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
TXT;
return ConfigBridge::create();
$finder = PhpCsFixer\Finder::create()
->in('src')
->in('tests');
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'@Symfony' => true,
'strict_param' => true,
'array_syntax' => ['syntax' => 'short'],
'declare_strict_types' => true,
'no_empty_phpdoc' => true,
'no_superfluous_phpdoc_tags' => true,
'header_comment' => [
'commentType' => 'comment',
'header' => $header,
'location' => 'after_declare_strict',
'separate' => 'both',
],
])
->setFinder($finder)
;

View file

@ -5,5 +5,6 @@ checks:
code_rating: true
duplication: true
tools:
external_code_coverage:
external_code_coverage:
timeout: 1200 # Timeout in seconds.
php_cpd: false

View file

@ -7,41 +7,46 @@ cache:
- $HOME/.composer/cache/files
php:
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
- 7.3
branches:
except:
- /^analysis-.*$/
- /^patch-.*$/
env:
- TEST_COMMAND="composer test-all"
- TEST_COMMAND="composer test"
matrix:
fast_finish: true
include:
- php: 5.5
- php: 7.1
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" PREFER_COVERAGE=true
- php: hhvm
dist: trusty
- name: Backward compatibility test (Disabled)
php: 7.3
env: DEPENDENCIES="roave/backward-compatibility-check"
script: ./vendor/bin/roave-backward-compatibility-check || true
- name: PHPStan
php: 7.2
env: DEPENDENCIES="phpstan/phpstan"
script:
- ./vendor/bin/phpstan --version
- ./vendor/bin/phpstan analyse
before_install:
- if [[ "$PREFER_COVERAGE" = true ]] && [[ "$TRAVIS_PULL_REQUEST" = false ]]; then TEST_COMMAND="composer test-coverage" COVERAGE=true; fi
- if ! [ -z "$DEPENDENCIES" ]; then composer require --no-update ${DEPENDENCIES}; fi;
install:
- travis_retry composer update ${COMPOSER_FLAGS} --prefer-source --no-interaction
before_script:
- if [[ "COVERAGE" = true ]]; then TEST_COMMAND="composer test-coverage"; fi
- if ! [[ "$TRAVIS_PULL_REQUEST" = false ]]; then TEST_COMMAND="composer test"; fi
- if [[ "$PREFER_COVERAGE" = true ]] && [[ "$TRAVIS_PULL_REQUEST" = false ]]; then TEST_COMMAND="composer test-coverage" COVERAGE=true; fi
- composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction
script:
- composer validate --strict --no-check-lock
- echo $TEST_COMMAND
- $TEST_COMMAND
after_success:
- if [[ "$COVERAGE" = true ]]; then wget https://scrutinizer-ci.com/ocular.phar; fi
- if [[ "$COVERAGE" = true ]]; then php ocular.phar code-coverage:upload --format=php-clover build/coverage.xml; fi
notifications:
slack:
rooms:
secure: Xa/LYWGRDOt1Gjw10YTgYmVriSt/MSDOuzqoqQ8OWekJp05C2oRTor8dztEATTM4HQSLrwTa8CTnkFyD8+Z4fbnuvQ0dJ4j5CJYs5AjyirEWwblqS0PIATEEGKffDocsMh4VyMEPSwWXZY319bvG79mUq0E57VmT3y2ROMUuuec=

View file

@ -1,6 +1,84 @@
# Change Log
The change log describes what is "Added", "Removed", "Changed" or "Fixed" between each release.
The change log describes what is "Added", "Removed", "Changed" or "Fixed" between each release.
## 3.0.0
### Added
- Support for PSR-4
- All classes `Mailgun\Model` are final or abstract.
### Changed
- Dropped PHP5 support
- Removed deprecated code
- Moved `RequestBuilder` and `HttpClientConfigurator` to `Mailgun\HttpClient` namespace
- Updated signature of `Mailgun::__construct()`
### Removed
- Dependency on `php-http/message`.
### [Unreleased]
- API v4 Email Validation; please use US Servers with your public key instead
(please check the Issues [617](https://github.com/mailgun/mailgun-php/issues/617)
and [619](https://github.com/mailgun/mailgun-php/issues/619) for further details)
## 2.8.1
### Fixed
- Added missing method to use all Mailing List and Ip features.
## 2.8.0
### Added
- Add support for IPs endpoints
- Add spport for Mailing Lists
- Add `complaints` to Stats / Total Response
- Add more tests for our models
### Changed
- Change the PHP Exception message for Bad Request errors to help to find the issue
### Fixed
- Fix an issue validating the max path length
## 2.7.0
### Added
- Allow to set the Mailgun server when instantiating the Mailgun's client: `$mailgun = Mailgun::create('key', 'server');`
- Add new PHPUnit tests for our models
- Add new PHPUnit tests for our API
- Added `Mailgun\Api\Attachment`
- Fluent interface for `MessageBuilder` and `BatchMessage`
- Support for HTTPlug 2.0
### Changed
- Second argument to `Mailgun\Message\MessageBuilder::addBccRecipient()` is now optional.
- We try to close open resources
### Fixed
- Fixed the type error when creating tags.
## 2.6.0
### Added
- Ported MessageBuilder and BatchMessage #472
### Changed
- Cast campaign IDs to string #460
- Suggest packages used on Dev #440
## 2.5.0

View file

@ -1,14 +1,11 @@
# Mailgun PHP client
This is the Mailgun PHP SDK. This SDK contains methods for easily interacting
with the Mailgun API.
Below are examples to get you started. For additional examples, please see our
official documentation
at http://documentation.mailgun.com
This is the Mailgun PHP SDK. This SDK contains methods for easily interacting
with the Mailgun API. Below are examples to get you started. For additional
examples, please see our official documentation at http://documentation.mailgun.com
[![Latest Version](https://img.shields.io/github/release/mailgun/mailgun-php.svg?style=flat-square)](https://github.com/mailgun/mailgun-php/releases)
[![Build Status](https://img.shields.io/travis/mailgun/mailgun-php/master.svg?style=flat-square)](https://travis-ci.org/mailgun/mailgun-php)
[![StyleCI](https://styleci.io/repos/11654443/shield?branch=master)](https://styleci.io/repos/11654443)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/mailgun/mailgun-php.svg?style=flat-square)](https://scrutinizer-ci.com/g/mailgun/mailgun-php)
[![Quality Score](https://img.shields.io/scrutinizer/g/mailgun/mailgun-php.svg?style=flat-square)](https://scrutinizer-ci.com/g/mailgun/mailgun-php)
[![Total Downloads](https://img.shields.io/packagist/dt/mailgun/mailgun-php.svg?style=flat-square)](https://packagist.org/packages/mailgun/mailgun-php)
@ -25,25 +22,23 @@ composer:
curl -sS https://getcomposer.org/installer | php
```
The Mailgun api client is not hard coupled to Guzzle or any other library that sends HTTP messages. It uses an abstraction
called HTTPlug. This will give you the flexibilty to choose what PSR-7 implementation and HTTP client to use.
The Mailgun API Client is not hard coupled to Guzzle, Buzz or any other library that sends
HTTP messages. Instead, it uses the [PSR-18](https://www.php-fig.org/psr/psr-18/) client abstraction.
This will give you the flexibility to choose what
[PSR-7 implementation and HTTP client](https://packagist.org/providers/php-http/client-implementation)
you want to use.
If you just want to get started quickly you should run the following command:
```bash
php composer.phar require mailgun/mailgun-php php-http/curl-client guzzlehttp/psr7
composer require mailgun/mailgun-php kriswallsmith/buzz nyholm/psr7
```
### Why requiring so many packages?
Mailgun has a dependency on the virtual package
[php-http/client-implementation](https://packagist.org/providers/php-http/client-implementation) which requires you to install **an** adapter, but we do not care which one. That is an implementation detail in your application. We also need **a** PSR-7 implementation and **a** message factory.
You do not have to use the `php-http/curl-client` if you do not want to. You may use the `php-http/guzzle6-adapter`. Read more about the virtual packages, why this is a good idea and about the flexibility it brings at the [HTTPlug docs](http://docs.php-http.org/en/latest/httplug/users.html).
## Usage
You should always use Composer's autoloader in your application to automatically load the your dependencies. All examples below assumes you've already included this in your file:
You should always use Composer autoloader in your application to automatically load
your dependencies. All the examples below assume you've already included this in your
file:
```php
require 'vendor/autoload.php';
@ -53,11 +48,12 @@ use Mailgun\Mailgun;
Here's how to send a message using the SDK:
```php
# First, instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example');
// First, instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example'); // For US servers
$mg = Mailgun::create('key-example', 'https://api.eu.mailgun.net'); // For EU servers
# Now, compose and send your message.
# $mg->messages()->send($domain, $params);
// Now, compose and send your message.
// $mg->messages()->send($domain, $params);
$mg->messages()->send('example.com', [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
@ -70,7 +66,7 @@ Attention: `$domain` must match to the domain you have configured on [app.mailgu
### All usage examples
You find more detailed documentation at [/doc](doc/index.md) and on
You will find more detailed documentation at [/doc](doc/index.md) and on
[https://documentation.mailgun.com](https://documentation.mailgun.com/api_reference.html).
### Response
@ -97,7 +93,7 @@ use Mailgun\Hydrator\ArrayHydrator;
$configurator = new HttpClientConfigurator();
$configurator->setApiKey('key-example');
$mg = Mailgun::configure($configurator, new ArrayHydrator());
$mg = new Mailgun($configurator, new ArrayHydrator());
$data = $mg->domains()->show('example.com');
foreach ($data['receiving_dns_records'] as $record) {
@ -112,12 +108,12 @@ the API calls.
### Debugging
Debugging the PHP SDK can be really helpful when things aren't working quite right.
Debugging the PHP SDK can be helpful when things aren't working quite right.
To debug the SDK, here are some suggestions:
Set the endpoint to Mailgun's Postbin. A Postbin is a web service that allows you to
post data, which is then displayed through a browser. This allows you to quickly determine
what is actually being transmitted to Mailgun's API.
Set the endpoint to Mailgun's Postbin. A Postbin is a web service that allows you to
post data, which then you can display it through a browser. Using Postbin is an easy way
to quickly determine what data you're transmitting to Mailgun's API.
**Step 1 - Create a new Postbin.**
Go to http://bin.mailgun.net. The Postbin will generate a special URL. Save that URL.
@ -125,13 +121,13 @@ Go to http://bin.mailgun.net. The Postbin will generate a special URL. Save that
**Step 2 - Instantiate the Mailgun client using Postbin.**
*Tip: The bin id will be the URL part after bin.mailgun.net. It will be random generated letters and numbers.
For example, the bin id in this URL, http://bin.mailgun.net/aecf68de, is "aecf68de".*
For example, the bin id in this URL (http://bin.mailgun.net/aecf68de) is `aecf68de`.*
```php
$configurator = new HttpClientConfigurator();
$configurator->setEndpoint('http://bin.mailgun.net/aecf68de');
$configurator->setDebug(true);
$mg = Mailgun::configure($configurator);
$mg = new Mailgun($configurator);
# Now, compose and send your message.
$mg->messages()->send('example.com', [
@ -163,15 +159,17 @@ If you are using a framework you might consider these composer packages to make
* [Bogardo/Mailgun](https://github.com/Bogardo/Mailgun) for Laravel
* [katanyoo/yii2-mailgun-mailer](https://github.com/katanyoo/yii2-mailgun-mailer) for Yii2
* [narendravaghela/cakephp-mailgun](https://github.com/narendravaghela/cakephp-mailgun) for CakePHP
* [drupal/mailgun](https://www.drupal.org/project/mailgun) for Drupal
## Contribute
We are currently building a new object oriented API client. Feel free to contribute in any way. As an example you may:
* Trying out dev-master the code
This SDK is an Open Source under the MIT license. It is, thus, maintained by collaborators and contributors.
Feel free to contribute in any way. As an example you may:
* Trying out the `dev-master` code
* Create issues if you find problems
* Reply to other people's issues
* Review PRs
* Write PR. You find our current milestone [here](https://github.com/mailgun/mailgun-php/milestone/1)
### Running the test code
@ -193,6 +191,5 @@ information about our API.
If you find a bug, please submit the issue in Github directly.
[Mailgun-PHP Issues](https://github.com/mailgun/mailgun-php/issues)
As always, if you need additional assistance, drop us a note through your Control Panel at
[https://mailgun.com/cp/support](https://mailgun.com/cp/support).
As always, if you need additional assistance, drop us a note through your account at
[https://app.mailgun.com/app/support/list](https://app.mailgun.com/app/support/list).

View file

@ -2,22 +2,22 @@
"name": "mailgun/mailgun-php",
"description": "The Mailgun SDK provides methods for all API functions.",
"require": {
"php": "^5.5|^7.0",
"php-http/httplug": "^1.0",
"php": "^7.1",
"psr/http-client": "^1.0",
"php-http/multipart-stream-builder": "^1.0",
"php-http/message": "^1.0",
"php-http/client-common": "^1.1",
"php-http/discovery": "^1.0",
"php-http/client-common": "^1.9 || ^2.0",
"php-http/discovery": "^1.6",
"webmozart/assert": "^1.2"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"phpunit/phpunit": "^7.5",
"php-http/guzzle6-adapter": "^1.0",
"guzzlehttp/psr7": "^1.4"
"nyholm/psr7": "^1.0",
"nyholm/nsa": "^1.1"
},
"autoload": {
"psr-0": {
"Mailgun": "src/"
"psr-4": {
"Mailgun\\": "src/"
}
},
"autoload-dev": {
@ -25,6 +25,10 @@
"Mailgun\\Tests\\": "tests/"
}
},
"suggest": {
"php-http/curl-client": "cURL client for PHP-HTTP",
"guzzlehttp/psr7": "PSR-7 message implementation that also provides common utility methods"
},
"license": "MIT",
"authors": [
{
@ -33,9 +37,12 @@
}
],
"scripts": {
"test": "vendor/bin/phpunit --testsuite unit && vendor/bin/phpunit --testsuite functional",
"test-all": "vendor/bin/phpunit --testsuite all",
"test-integration": "vendor/bin/phpunit --testsuite integration",
"test-coverage": "vendor/bin/phpunit --testsuite all --coverage-text --coverage-clover=build/coverage.xml"
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-text --coverage-clover=build/coverage.xml"
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
}
}

View file

@ -5,7 +5,7 @@ You may attach a file from memory or by a file path.
## From file path
```php
$mg->message()->send('example.com', [
$mg->messages()->send('example.com', [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'Test file path attachments',
@ -21,7 +21,7 @@ $mg->message()->send('example.com', [
// Some how load the file to memory
$binaryFile = '[Binary data]';
$mg->message()->send('example.com', [
$mg->messages()->send('example.com', [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'Test memory attachments',
@ -35,7 +35,7 @@ $mg->message()->send('example.com', [
## Inline attachments
```php
$mg->message()->send('example.com', [
$mg->messages()->send('example.com', [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'Test inline attachments',

View file

@ -3,13 +3,12 @@
This page will document the API classes and ways to properly use the API. These resources will eventually move to
the official documentation at [https://documentation.mailgun.com](https://documentation.mailgun.com/api_reference.html).
Other relevant documentation pages might be:
Other relevant documentation pages might be:
* [Attachments](attachments.md)
* [Pagination](pagination.md)
* [Message Builder](src/Mailgun/Messages/README.md) (Legacy code)
* [Batch Message](src/Mailgun/Messages/README.md) (Legacy code)
* [Opt-In Handler](src/Mailgun/Lists/README.md) (Legacy code)
* [Message Builder](/src/Message/README.md)
* [Batch Message](/src/Message/README.md)
## Domain API
@ -91,9 +90,9 @@ $mailgun->events()->get('example.com');
#### Send a message
```php
$parameters = [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'The PHP SDK is awesome!',
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'The PHP SDK is awesome!',
'text' => 'It is so simple to send a message.'
];
$mailgun->messages()->send('example.com', $parameters);
@ -103,10 +102,10 @@ $mailgun->messages()->send('example.com', $parameters);
Below in an example how to create a Mime message with SwiftMailer.
```php
$message = \Swift_Message::newInstance('Mail Subject');
$message = new Swift_Message('Mail Subject');
$message->setFrom(['from@exemple.com' => 'Example Inc']);
$message->setTo(['user0gmail.com' => 'User 0', 'user1@hotmail.com' => 'User 1']);
// $message->setBcc('admin@example.com'); Do not do this, BCC will be visible for all receipients if you do.
// $message->setBcc('admin@example.com'); Do not do this, BCC will be visible for all receipients if you do.
$message->setCc('invoice@example.com');
$messageBody = 'Look at the <b>fancy</b> HTML body.';
@ -116,7 +115,7 @@ $message->setBody($messageBody, 'text/html');
$to = ['admin@example.com', 'user0gmail.com', 'user1@hotmail.com', 'invoice@example.com']
// Send the message
$mailgun->messages()->sendMime('example.com', $to, $message->toString());
$mailgun->messages()->sendMime('example.com', $to, $message->toString(), []);
```
#### Show a stored message
@ -303,7 +302,7 @@ $valid = $mailgun->webhooks()->verifyWebhookSignature($timestamp, $token, $signa
if (!$valid) {
// Create a 403 response
exit();
}

7
phpstan.neon Normal file
View file

@ -0,0 +1,7 @@
parameters:
level: 5
paths:
- src
excludes_analyse:
- %currentWorkingDirectory%/src/HttpClient/Plugin/HistoryTrait.php

View file

@ -3,30 +3,14 @@
colors="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader">
convertWarningsToExceptions="true">
<testsuites>
<testsuite name="all">
<testsuite name="Mailgun test suite">
<directory>tests</directory>
</testsuite>
<testsuite name="unit">
<directory>tests</directory>
<exclude>tests/Integration</exclude>
<exclude>test/Functional</exclude>
</testsuite>
<testsuite name="integration">
<directory>tests/Integration</directory>
</testsuite>
<testsuite name="functional">
<directory>tests/Functional</directory>
</testsuite>
</testsuites>
<filter>

39
src/Api/Attachment.php Normal file
View file

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api;
use Mailgun\Assert;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Attachment extends HttpApi
{
/**
* @return ResponseInterface
*/
public function show(string $url)
{
Assert::stringNotEmpty($url);
Assert::regex($url, '@https://.*mailgun\.(net|org)/v.+@');
Assert::regex($url, '|/attachments/[0-9]+|');
$response = $this->httpGet($url);
if (200 !== $response->getStatusCode()) {
$this->handleErrors($response);
}
return $response;
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -24,7 +26,7 @@ use Mailgun\Model\Domain\VerifyResponse;
use Psr\Http\Message\ResponseInterface;
/**
* {@link https://documentation.mailgun.com/api-domains.html}.
* @see https://documentation.mailgun.com/api-domains.html
*
* @author Sean Johnson <sean@mailgun.com>
*/
@ -33,15 +35,12 @@ class Domain extends HttpApi
/**
* Returns a list of domains on the account.
*
* @param int $limit
* @param int $skip
*
* @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::range($limit, 1, 1000);
$params = [
'limit' => $limit,
@ -56,11 +55,11 @@ class Domain extends HttpApi
/**
* Returns a single domain.
*
* @param string $domain Name of the domain.
* @param string $domain name of the domain
*
* @return ShowResponse|array|ResponseInterface
*/
public function show($domain)
public function show(string $domain)
{
Assert::stringNotEmpty($domain);
@ -76,29 +75,38 @@ class Domain extends HttpApi
*
* @see https://documentation.mailgun.com/en/latest/api-domains.html#domains
*
* @param string $domain Name of the domain.
* @param string $smtpPass Password for SMTP authentication.
* @param string $spamAction `disable` or `tag` - inbound spam filtering.
* @param bool $wildcard Domain will accept email for subdomains.
* @param string $domain name of the domain
* @param string $smtpPass password for SMTP authentication
* @param string $spamAction `disable` or `tag` - inbound spam filtering
* @param bool $wildcard domain will accept email for subdomains
*
* @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);
$params['name'] = $domain;
// If at least smtpPass available, check for the fields spamAction wildcard
if (!empty($smtpPass)) {
// TODO(sean.johnson): Extended spam filter input validation.
Assert::stringNotEmpty($spamAction);
Assert::boolean($wildcard);
Assert::stringNotEmpty($smtpPass);
$params['smtp_password'] = $smtpPass;
}
if (!empty($spamAction)) {
// TODO(sean.johnson): Extended spam filter input validation.
Assert::stringNotEmpty($spamAction);
$params['spam_action'] = $spamAction;
}
if (null !== $wildcard) {
Assert::boolean($wildcard);
$params['wildcard'] = $wildcard ? 'true' : 'false';
}
$response = $this->httpPost('/v3/domains', $params);
return $this->hydrateResponse($response, CreateResponse::class);
@ -108,11 +116,11 @@ class Domain extends HttpApi
* Removes a domain from the account.
* WARNING: This action is irreversible! Be cautious!
*
* @param string $domain Name of the domain.
* @param string $domain name of the domain
*
* @return DeleteResponse|array|ResponseInterface
*/
public function delete($domain)
public function delete(string $domain)
{
Assert::stringNotEmpty($domain);
@ -124,18 +132,15 @@ class Domain extends HttpApi
/**
* Returns a list of SMTP credentials for the specified domain.
*
* @param string $domain Name of the domain.
* @param string $domain name of the domain
* @param int $limit Number of credentials to return
* @param int $skip Number of credentials to omit from the list
*
* @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,
@ -149,13 +154,13 @@ class Domain extends HttpApi
/**
* Create a new SMTP credential pair for the specified domain.
*
* @param string $domain Name of the domain.
* @param string $login SMTP Username.
* @param string $domain name of the domain
* @param string $login SMTP Username
* @param string $password SMTP Password. Length min 5, max 32.
*
* @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);
@ -175,13 +180,13 @@ class Domain extends HttpApi
/**
* Update a set of SMTP credentials for the specified domain.
*
* @param string $domain Name of the domain.
* @param string $login SMTP Username.
* @param string $domain name of the domain
* @param string $login SMTP Username
* @param string $pass New SMTP Password. Length min 5, max 32.
*
* @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);
@ -200,12 +205,12 @@ class Domain extends HttpApi
/**
* Remove a set of SMTP credentials from the specified domain.
*
* @param string $domain Name of the domain.
* @param string $login SMTP Username.
* @param string $domain name of the domain
* @param string $login SMTP Username
*
* @return DeleteCredentialResponse|array|ResponseInterface
*/
public function deleteCredential($domain, $login)
public function deleteCredential(string $domain, string $login)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($login);
@ -224,11 +229,11 @@ class Domain extends HttpApi
/**
* Returns delivery connection settings for the specified domain.
*
* @param string $domain Name of the domain.
* @param string $domain name of the domain
*
* @return ConnectionResponse|ResponseInterface
*/
public function connection($domain)
public function connection(string $domain)
{
Assert::stringNotEmpty($domain);
@ -241,18 +246,15 @@ class Domain extends HttpApi
* Updates the specified delivery connection settings for the specified domain.
* If a parameter is passed in as null, it will not be updated.
*
* @param string $domain Name of the domain.
* @param bool|null $requireTLS Enforces that messages are sent only over a TLS connection.
* @param bool|null $noVerify Disables TLS certificate and hostname verification.
* @param string $domain name of the domain
* @param bool|null $requireTLS enforces that messages are sent only over a TLS connection
* @param bool|null $noVerify disables TLS certificate and hostname verification
*
* @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) {
@ -271,11 +273,11 @@ class Domain extends HttpApi
/**
* Returns a single domain.
*
* @param string $domain Name of the domain.
* @param string $domain name of the domain
*
* @return VerifyResponse|array|ResponseInterface
*/
public function verify($domain)
public function verify(string $domain)
{
Assert::stringNotEmpty($domain);

View file

@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Exception\HttpClientException;
use Mailgun\Exception\HttpServerException;
use Mailgun\Exception\InvalidArgumentException;
use Mailgun\Model\EmailValidation\ParseResponse;
use Mailgun\Model\EmailValidation\ValidateResponse;
use Psr\Http\Message\ResponseInterface;
/**
* @see https://documentation.mailgun.com/en/latest/api-email-validation.html
*
* @author David Garcia <me@davidgarcia.cat>
*/
class EmailValidation extends HttpApi
{
/**
* Addresses are validated based off defined checks.
*
* This operation is only accessible with the private API key and not subject to the daily usage limits.
*
* @param string $address An email address to validate. Maximum: 512 characters.
* @param bool $mailboxVerification If set to true, a mailbox verification check will be performed
* against the address. The default is False.
*
* @throws InvalidArgumentException Thrown when local validation returns an error
* @throws HttpClientException Thrown when there's an error on Client side
* @throws HttpServerException Thrown when there's an error on Server side
* @throws \Exception Thrown when we don't catch a Client or Server side Exception
*
* @return ValidateResponse|ResponseInterface
*/
public function validate(string $address, bool $mailboxVerification = false)
{
Assert::stringNotEmpty($address);
$params = [
'address' => $address,
'mailbox_verification' => $mailboxVerification,
];
$response = $this->httpGet('/address/private/validate', $params);
return $this->hydrateResponse($response, ValidateResponse::class);
}
/**
* Parses a delimiter-separated list of email addresses into two lists: parsed addresses and unparsable portions.
*
* The parsed addresses are a list of addresses that are syntactically valid
* (and optionally pass DNS and ESP specific grammar checks).
*
* The unparsable list is a list of character sequences that could not be parsed
* (or optionally failed DNS or ESP specific grammar checks).
*
* Delimiter characters are comma (,) and semicolon (;).
*
* This operation is only accessible with the private API key and not subject to the daily usage limits.
*
* @param string $addresses A delimiter separated list of addresses. Maximum: 8000 characters.
* @param bool $syntaxOnly Perform only syntax checks or DNS and ESP specific validation as well.
* The default is True.
*
* @throws InvalidArgumentException Thrown when local validation returns an error
* @throws HttpClientException Thrown when there's an error on Client side
* @throws HttpServerException Thrown when there's an error on Server side
* @throws \Exception Thrown when we don't catch a Client or Server side Exception
*
* @return ParseResponse|ResponseInterface
*/
public function parse(string $addresses, bool $syntaxOnly = true)
{
Assert::stringNotEmpty($addresses);
Assert::maxLength($addresses, 8000);
$params = [
'addresses' => $addresses,
'syntax_only' => $syntaxOnly,
];
$response = $this->httpGet('/address/private/parse', $params);
return $this->hydrateResponse($response, ParseResponse::class);
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -13,7 +15,7 @@ use Mailgun\Assert;
use Mailgun\Model\Event\EventResponse;
/**
* {@link https://documentation.mailgun.com/api-events.html}.
* @see https://documentation.mailgun.com/en/latest/api-events.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
@ -22,15 +24,16 @@ class Event extends HttpApi
use Pagination;
/**
* @param string $domain
* @param array $params
*
* @return EventResponse
*/
public function get($domain, array $params = [])
public function get(string $domain, array $params = [])
{
Assert::stringNotEmpty($domain);
if (array_key_exists('limit', $params)) {
Assert::range($params['limit'], 1, 300);
}
$response = $this->httpGet(sprintf('/v3/%s/events', $domain), $params);
return $this->hydrateResponse($response, EventResponse::class);

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -9,14 +11,14 @@
namespace Mailgun\Api;
use Http\Client\Exception as HttplugException;
use Http\Client\HttpClient;
use Mailgun\Exception\UnknownErrorException;
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\Client as Psr18;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
/**
@ -27,12 +29,12 @@ abstract class HttpApi
/**
* The HTTP client.
*
* @var HttpClient
* @var ClientInterface
*/
private $httpClient;
protected $httpClient;
/**
* @var Hydrator
* @var Hydrator|null
*/
protected $hydrator;
@ -41,12 +43,7 @@ abstract class HttpApi
*/
protected $requestBuilder;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
public function __construct(ClientInterface $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
$this->requestBuilder = $requestBuilder;
@ -56,16 +53,13 @@ abstract class HttpApi
}
/**
* @param ResponseInterface $response
* @param string $class
*
* @return mixed|ResponseInterface
*
* @throws \Exception
*/
protected function hydrateResponse(ResponseInterface $response, $class)
protected function hydrateResponse(ResponseInterface $response, string $class)
{
if (!$this->hydrator) {
if (null === $this->hydrator) {
return $response;
}
@ -79,8 +73,6 @@ abstract class HttpApi
/**
* Throw the correct exception for this error.
*
* @param ResponseInterface $response
*
* @throws \Exception
*/
protected function handleErrors(ResponseInterface $response)
@ -93,6 +85,8 @@ abstract class HttpApi
throw HttpClientException::unauthorized($response);
case 402:
throw HttpClientException::requestFailed($response);
case 403:
throw HttpClientException::forbidden($response);
case 404:
throw HttpClientException::notFound($response);
case 413:
@ -110,10 +104,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);
@ -123,7 +115,7 @@ abstract class HttpApi
$response = $this->httpClient->sendRequest(
$this->requestBuilder->create('GET', $path, $requestHeaders)
);
} catch (HttplugException\NetworkException $e) {
} catch (Psr18\NetworkExceptionInterface $e) {
throw HttpServerException::networkError($e);
}
@ -136,10 +128,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,16 +140,14 @@ 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(
$this->requestBuilder->create('POST', $path, $requestHeaders, $body)
);
} catch (HttplugException\NetworkException $e) {
} catch (Psr18\NetworkExceptionInterface $e) {
throw HttpServerException::networkError($e);
}
@ -172,16 +160,14 @@ 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(
$this->requestBuilder->create('PUT', $path, $requestHeaders, $this->createRequestBody($parameters))
);
} catch (HttplugException\NetworkException $e) {
} catch (Psr18\NetworkExceptionInterface $e) {
throw HttpServerException::networkError($e);
}
@ -194,16 +180,14 @@ 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(
$this->requestBuilder->create('DELETE', $path, $requestHeaders, $this->createRequestBody($parameters))
);
} catch (HttplugException\NetworkException $e) {
} catch (Psr18\NetworkExceptionInterface $e) {
throw HttpServerException::networkError($e);
}
@ -214,10 +198,8 @@ abstract class HttpApi
* Prepare a set of key-value-pairs to be encoded as multipart/form-data.
*
* @param array $parameters Request parameters
*
* @return array
*/
protected function createRequestBody(array $parameters)
private function createRequestBody(array $parameters): array
{
$resources = [];
foreach ($parameters as $key => $values) {

112
src/Api/Ip.php Normal file
View file

@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Model\Ip\IndexResponse;
use Mailgun\Model\Ip\ShowResponse;
use Mailgun\Model\Ip\UpdateResponse;
use Psr\Http\Message\ResponseInterface;
/**
* @see https://documentation.mailgun.com/en/latest/api-ips.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Ip extends HttpApi
{
/**
* Returns a list of IPs.
*
*
* @return IndexResponse|ResponseInterface
*/
public function index(bool $dedicated = false)
{
Assert::boolean($dedicated);
$params = [
'dedicated' => $dedicated,
];
$response = $this->httpGet('/v3/ips', $params);
return $this->hydrateResponse($response, IndexResponse::class);
}
/**
* Returns a list of IPs assigned to a domain.
*
*
* @return IndexResponse|ResponseInterface
*/
public function domainIndex(string $domain)
{
Assert::stringNotEmpty($domain);
$response = $this->httpGet(sprintf('/v3/domains/%s/ip', $domain));
return $this->hydrateResponse($response, IndexResponse::class);
}
/**
* Returns a single ip.
*
*
* @return ShowResponse|ResponseInterface
*/
public function show(string $ip)
{
Assert::ip($ip);
$response = $this->httpGet(sprintf('/v3/ips/%s', $ip));
return $this->hydrateResponse($response, ShowResponse::class);
}
/**
* Assign a dedicated IP to the domain specified.
*
*
* @return UpdateResponse|ResponseInterface
*/
public function assign(string $domain, string $ip)
{
Assert::stringNotEmpty($domain);
Assert::ip($ip);
$params = [
'id' => $ip,
];
$response = $this->httpPost(sprintf('/v3/domains/%s/ips', $domain), $params);
return $this->hydrateResponse($response, UpdateResponse::class);
}
/**
* Unassign an IP from the domain specified.
*
*
* @return UpdateResponse|ResponseInterface
*/
public function unassign(string $domain, string $ip)
{
Assert::stringNotEmpty($domain);
Assert::ip($ip);
$response = $this->httpDelete(sprintf('/v3/domains/%s/ips/%s', $domain, $ip));
return $this->hydrateResponse($response, UpdateResponse::class);
}
}

155
src/Api/MailingList.php Normal file
View file

@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api;
use Mailgun\Api\MailingList\Member;
use Mailgun\Assert;
use Mailgun\Model\MailingList\CreateResponse;
use Mailgun\Model\MailingList\DeleteResponse;
use Mailgun\Model\MailingList\PagesResponse;
use Mailgun\Model\MailingList\ShowResponse;
use Mailgun\Model\MailingList\UpdateResponse;
/**
* @see https://documentation.mailgun.com/en/latest/api-mailinglists.html
*/
class MailingList extends HttpApi
{
public function member(): Member
{
return new Member($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* Returns a paginated list of mailing lists on the domain.
*
* @param int $limit Maximum number of records to return (optional: 100 by default)
*
* @return PagesResponse
*
* @throws \Exception
*/
public function pages(int $limit = 100)
{
Assert::range($limit, 1, 1000);
$params = [
'limit' => $limit,
];
$response = $this->httpGet('/v3/lists/pages', $params);
return $this->hydrateResponse($response, PagesResponse::class);
}
/**
* Creates a new mailing list on the current domain.
*
* @param string $address Address for the new mailing list
* @param string $name Name for the new mailing list (optional)
* @param string $description Description for the new mailing list (optional)
* @param string $accessLevel List access level, one of: readonly (default), members, everyone
*
* @return CreateResponse
*
* @throws \Exception
*/
public function create(string $address, string $name = null, string $description = null, string $accessLevel = 'readonly')
{
Assert::stringNotEmpty($address);
Assert::nullOrStringNotEmpty($name);
Assert::nullOrStringNotEmpty($description);
Assert::oneOf($accessLevel, ['readonly', 'members', 'everyone']);
$params = [
'address' => $address,
'name' => $name,
'description' => $description,
'access_level' => $accessLevel,
];
$response = $this->httpPost('/v3/lists', $params);
return $this->hydrateResponse($response, CreateResponse::class);
}
/**
* Returns a single mailing list.
*
* @param string $address Address of the mailing list
*
* @return ShowResponse
*
* @throws \Exception
*/
public function show(string $address)
{
Assert::stringNotEmpty($address);
$response = $this->httpGet(sprintf('/v3/lists/%s', $address));
return $this->hydrateResponse($response, ShowResponse::class);
}
/**
* Updates a mailing list.
*
* @param string $address Address of the mailing list
* @param array $parameters Array of field => value pairs to update
*
* @return UpdateResponse
*
* @throws \Exception
*/
public function update(string $address, array $parameters = [])
{
Assert::stringNotEmpty($address);
Assert::isArray($parameters);
foreach ($parameters as $field => $value) {
switch ($field) {
case 'address':
case 'name':
case 'description':
Assert::stringNotEmpty($value);
break;
case 'access_level':
Assert::oneOf($value, ['readonly', 'members', 'everyone']);
break;
}
}
$response = $this->httpPut(sprintf('/v3/lists/%s', $address), $parameters);
return $this->hydrateResponse($response, UpdateResponse::class);
}
/**
* Removes a mailing list from the domain.
*
* @param string $address Address of the mailing list
*
* @return DeleteResponse
*
* @throws \Exception
*/
public function delete(string $address)
{
Assert::stringNotEmpty($address);
$response = $this->httpDelete(sprintf('/v3/lists/%s', $address));
return $this->hydrateResponse($response, DeleteResponse::class);
}
}

View file

@ -0,0 +1,242 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api\MailingList;
use Mailgun\Api\HttpApi;
use Mailgun\Assert;
use Mailgun\Exception\InvalidArgumentException;
use Mailgun\Model\MailingList\Member\CreateResponse;
use Mailgun\Model\MailingList\Member\DeleteResponse;
use Mailgun\Model\MailingList\Member\IndexResponse;
use Mailgun\Model\MailingList\Member\ShowResponse;
use Mailgun\Model\MailingList\Member\UpdateResponse;
use Mailgun\Model\MailingList\UpdateResponse as MailingListUpdateResponse;
/**
* @see https://documentation.mailgun.com/en/latest/api-mailinglists.html
*/
class Member extends HttpApi
{
/**
* Returns a paginated list of members of the mailing list.
*
* @param string $address Address of the mailing list
* @param int $limit Maximum number of records to return (optional: 100 by default)
* @param bool|null $subscribed `true` to lists subscribed, `false` for unsubscribed. list all if null
*
* @return IndexResponse
*
* @throws \Exception
*/
public function index(string $address, int $limit = 100, bool $subscribed = null)
{
Assert::stringNotEmpty($address);
Assert::greaterThan($limit, 0);
$params = [
'limit' => $limit,
];
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);
}
/**
* Shows a single member of the mailing list.
*
* @param string $list Address of the mailing list
* @param string $address Address of the member
*
* @return ShowResponse
*
* @throws \Exception
*/
public function show(string $list, string $address)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
$response = $this->httpGet(sprintf('/v3/lists/%s/members/%s', $list, $address));
return $this->hydrateResponse($response, ShowResponse::class);
}
/**
* Creates (or updates) a member of the mailing list.
*
* @param string $list Address of the mailing list
* @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 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(string $list, string $address, string $name = null, array $vars = [], bool $subscribed = true, bool $upsert = false)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
Assert::nullOrStringNotEmpty($name);
$params = [
'address' => $address,
'name' => $name,
'vars' => \json_encode($vars),
'subscribed' => $subscribed ? 'yes' : 'no',
'upsert' => $upsert ? 'yes' : 'no',
];
$response = $this->httpPost(sprintf('/v3/lists/%s/members', $list), $params);
return $this->hydrateResponse($response, CreateResponse::class);
}
/**
* Adds multiple members (up to 1000) to the mailing list.
*
* @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 bool $upsert `true` to update existing members, `false` (default) to ignore duplicates
*
* @return UpdateResponse
*
* @throws \Exception
*/
public function createMultiple(string $list, array $members, $upsert = false)
{
Assert::stringNotEmpty($list);
Assert::isArray($members);
// workaround for webmozart/asserts <= 1.2
if (count($members) > 1000) {
throw new InvalidArgumentException(sprintf(
'Expected an Array to contain at most %2$d elements. Got: %d',
1000,
count($members)
));
}
foreach ($members as $data) {
if (is_string($data)) {
Assert::stringNotEmpty($data);
// single address - no additional validation required
continue;
}
Assert::isArray($data);
foreach ($data as $field => &$value) {
switch ($field) {
case 'address':
Assert::stringNotEmpty($value);
break;
case 'vars':
if (is_array($value)) {
$value = json_encode($value);
}
// We should assert that "vars"'s $value is a string.
// no break
case 'name':
Assert::string($value);
break;
case 'subscribed':
Assert::oneOf($value, ['yes', 'no']);
break;
}
}
}
$params = [
'members' => json_encode($members),
'upsert' => $upsert ? 'yes' : 'no',
];
$response = $this->httpPost(sprintf('/v3/lists/%s/members.json', $list), $params);
return $this->hydrateResponse($response, MailingListUpdateResponse::class);
}
/**
* Updates a member on the mailing list.
*
* @param string $list Address of the mailing list
* @param string $address Address of the member
* @param array $parameters Array of key => value pairs to update
*
* @return UpdateResponse
*
* @throws \Exception
*/
public function update(string $list, string $address, array $parameters = [])
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
Assert::isArray($parameters);
foreach ($parameters as $field => $value) {
switch ($field) {
case 'vars':
if (is_array($value)) {
$value = json_encode($value);
}
// We should assert that "vars"'s $value is a string.
// no break
case 'address':
case 'name':
Assert::stringNotEmpty($value);
break;
case 'subscribed':
Assert::oneOf($value, ['yes', 'no']);
break;
}
}
$response = $this->httpPut(sprintf('/v3/lists/%s/members/%s', $list, $address), $parameters);
return $this->hydrateResponse($response, UpdateResponse::class);
}
/**
* Removes a member from the mailing list.
*
* @param string $list Address of the mailing list
* @param string $address Address of the member
*
* @return DeleteResponse
*
* @throws \Exception
*/
public function delete(string $list, string $address)
{
Assert::stringNotEmpty($list);
Assert::stringNotEmpty($address);
$response = $this->httpDelete(sprintf('/v3/lists/%s/members/%s', $list, $address));
return $this->hydrateResponse($response, DeleteResponse::class);
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -11,21 +13,29 @@ namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Exception\InvalidArgumentException;
use Mailgun\Message\BatchMessage;
use Mailgun\Model\Message\SendResponse;
use Mailgun\Model\Message\ShowResponse;
use Psr\Http\Message\ResponseInterface;
/**
* @see https://documentation.mailgun.com/en/latest/api-sending.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Message extends HttpApi
{
public function getBatchMessage(string $domain, bool $autoSend = true): BatchMessage
{
return new BatchMessage($this, $domain, $autoSend);
}
/**
* @param string $domain
* @param array $params
* @see https://documentation.mailgun.com/en/latest/api-sending.html#sending
*
* @return SendResponse
* @return SendResponse|ResponseInterface
*/
public function send($domain, array $params)
public function send(string $domain, array $params)
{
Assert::string($domain);
Assert::notEmpty($domain);
@ -47,18 +57,24 @@ class Message extends HttpApi
}
$postDataMultipart = array_merge($this->prepareMultipartParameters($params), $postDataMultipart);
$response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart);
try {
$response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart);
} finally {
$this->closeResources($postDataMultipart);
}
return $this->hydrateResponse($response, SendResponse::class);
}
/**
* @param string $domain
* @see https://documentation.mailgun.com/en/latest/api-sending.html#sending
*
* @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);
@ -69,7 +85,7 @@ class Message extends HttpApi
$params['to'] = $recipients;
$postDataMultipart = $this->prepareMultipartParameters($params);
if (is_file($message)) {
if (strlen($message) < PHP_MAXPATHLEN && is_file($message)) {
$fileData = ['filePath' => $message];
} else {
$fileData = [
@ -78,7 +94,11 @@ class Message extends HttpApi
];
}
$postDataMultipart[] = $this->prepareFile('message', $fileData);
$response = $this->httpPostRaw(sprintf('/v3/%s/messages.mime', $domain), $postDataMultipart);
try {
$response = $this->httpPostRaw(sprintf('/v3/%s/messages.mime', $domain), $postDataMultipart);
} finally {
$this->closeResources($postDataMultipart);
}
return $this->hydrateResponse($response, SendResponse::class);
}
@ -86,12 +106,13 @@ class Message extends HttpApi
/**
* Get stored message.
*
* @param string $url
* @param bool $rawMessage if true we will use "Accept: message/rfc2822" header
* @see https://documentation.mailgun.com/en/latest/api-sending.html#retrieving-stored-messages
*
* @return ShowResponse
* @param bool $rawMessage if true we will use "Accept: message/rfc2822" header
*
* @return ShowResponse|ResponseInterface
*/
public function show($url, $rawMessage = false)
public function show(string $url, bool $rawMessage = false)
{
Assert::notEmpty($url);
@ -106,24 +127,22 @@ class Message extends HttpApi
}
/**
* Prepare a file.
*
* @param string $fieldName
* @param array $filePath array('fileContent' => 'content') or array('filePath' => '/foo/bar')
*
* @return array
* @param array $filePath array('fileContent' => 'content') or array('filePath' => '/foo/bar')
*
* @throws InvalidArgumentException
*/
private function prepareFile($fieldName, array $filePath)
private function prepareFile(string $fieldName, array $filePath): array
{
$filename = isset($filePath['filename']) ? $filePath['filename'] : null;
$deleteRequired = false;
if (isset($filePath['fileContent'])) {
// File from memory
$resource = fopen('php://temp', 'r+');
$filename = tempnam(sys_get_temp_dir(), "MAILGUN_TMP");
$resource = fopen($filename, 'r+');
fwrite($resource, $filePath['fileContent']);
rewind($resource);
$deleteRequired = true;
} elseif (isset($filePath['filePath'])) {
// File form path
$path = $filePath['filePath'];
@ -142,17 +161,14 @@ class Message extends HttpApi
'name' => $fieldName,
'content' => $resource,
'filename' => $filename,
'deleteRequired' => $deleteRequired,
];
}
/**
* 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) {
@ -167,4 +183,23 @@ class Message extends HttpApi
return $postDataMultipart;
}
/**
* Close open resources.
*/
private function closeResources(array $params): void
{
foreach ($params as $param) {
if (is_array($param) && array_key_exists('content', $param) && is_resource($param['content'])) {
fclose($param['content']);
}
if (is_array($param)) {
$isFile = array_key_exists('filename', $param) && is_file($param['filename']);
$deleteRequired = $param['deleteRequired'] ?? false;
if ($isFile && $deleteRequired) {
unlink($param['filename']);
}
}
}
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -18,62 +20,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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -10,14 +12,14 @@
namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Model\Route\Response\CreateResponse;
use Mailgun\Model\Route\Response\DeleteResponse;
use Mailgun\Model\Route\Response\IndexResponse;
use Mailgun\Model\Route\Response\ShowResponse;
use Mailgun\Model\Route\Response\UpdateResponse;
use Mailgun\Model\Route\CreateResponse;
use Mailgun\Model\Route\DeleteResponse;
use Mailgun\Model\Route\IndexResponse;
use Mailgun\Model\Route\ShowResponse;
use Mailgun\Model\Route\UpdateResponse;
/**
* {@link https://documentation.mailgun.com/api-routes.html}.
* @see https://documentation.mailgun.com/api-routes.html
*
* @author David Garcia <me@davidgarcia.cat>
*/
@ -31,12 +33,11 @@ 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);
Assert::range($limit, 1, 1000);
$params = [
'limit' => $limit,
@ -55,7 +56,7 @@ class Route extends HttpApi
*
* @return ShowResponse
*/
public function show($routeId)
public function show(string $routeId)
{
Assert::stringNotEmpty($routeId);
@ -74,15 +75,12 @@ 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,
'priority' => (string) $priority,
'expression' => $expression,
'action' => $actions,
'description' => $description,
@ -99,20 +97,20 @@ class Route extends HttpApi
*
* @param string $routeId Route ID returned by the Routes::index() method
* @param string|null $expression A filter expression like "match_recipient('.*@gmail.com')"
* @param array|null $actions Route action. This action is executed when the expression evaluates to True. Example: "forward('alice@example.com')"
* @param array $actions Route action. This action is executed when the expression evaluates to True. Example: "forward('alice@example.com')"
* @param string|null $description An arbitrary string
* @param int|null $priority Integer: smaller number indicates higher priority. Higher priority routes are handled first. Defaults to 0.
*
* @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)) {
@ -131,7 +129,7 @@ class Route extends HttpApi
}
if (!empty($priority)) {
$params['priority'] = $priority;
$params['priority'] = (string) $priority;
}
$response = $this->httpPut(sprintf('/v3/routes/%s', $routeId), $params);
@ -146,7 +144,7 @@ class Route extends HttpApi
*
* @return DeleteResponse
*/
public function delete($routeId)
public function delete(string $routeId)
{
Assert::stringNotEmpty($routeId);

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -14,19 +16,16 @@ use Mailgun\Model\Stats\AllResponse;
use Mailgun\Model\Stats\TotalResponse;
/**
* {@link https://documentation.mailgun.com/api-stats.html}.
* @see https://documentation.mailgun.com/en/latest/api-stats.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
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 +35,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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -9,12 +11,12 @@
namespace Mailgun\Api;
use Http\Client\HttpClient;
use Mailgun\Api\Suppression\Bounce;
use Mailgun\Api\Suppression\Complaint;
use Mailgun\Api\Suppression\Unsubscribe;
use Mailgun\Hydrator\Hydrator;
use Mailgun\RequestBuilder;
use Psr\Http\Client\ClientInterface;
use Mailgun\HttpClient\RequestBuilder;
/**
* @see https://documentation.mailgun.com/api-suppressions.html
@ -24,7 +26,7 @@ use Mailgun\RequestBuilder;
class Suppression
{
/**
* @var HttpClient
* @var ClientInterface
*/
private $httpClient;
@ -38,38 +40,24 @@ class Suppression
*/
private $hydrator;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
public function __construct(ClientInterface $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
$this->requestBuilder = $requestBuilder;
$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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -32,7 +34,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 +54,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 +71,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 +89,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 +104,7 @@ class Bounce extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -32,7 +34,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 +54,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,14 +70,14 @@ 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);
Assert::stringNotEmpty($createdAt);
$params['address'] = $address;
if (null !== $createdAt) {
Assert::stringNotEmpty($createdAt);
$params['created_at'] = $createdAt;
}
@ -90,7 +92,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 +107,7 @@ class Complaint extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -32,7 +34,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 +54,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 +71,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);
@ -82,17 +84,24 @@ class Unsubscribe extends HttpApi
}
/**
* @param string $domain Domain to delete unsubscribe for
* @param string $address Unsubscribe address
* @param string $domain Domain to delete unsubscribe for
* @param string $address Unsubscribe address
* @param string|null $tag Unsubscribe tag
*
* @return DeleteResponse
*/
public function delete($domain, $address)
public function delete(string $domain, string $address, string $tag = null)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($address);
Assert::nullOrStringNotEmpty($tag);
$response = $this->httpDelete(sprintf('/v3/%s/unsubscribes/%s', $domain, $address));
$params = [];
if (!is_null($tag)) {
$params['tag'] = $tag;
}
$response = $this->httpDelete(sprintf('/v3/%s/unsubscribes/%s', $domain, $address), $params);
return $this->hydrateResponse($response, DeleteResponse::class);
}
@ -102,7 +111,7 @@ class Unsubscribe extends HttpApi
*
* @return DeleteResponse
*/
public function deleteAll($domain)
public function deleteAll(string $domain)
{
Assert::stringNotEmpty($domain);

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -10,15 +12,18 @@
namespace Mailgun\Api;
use Mailgun\Assert;
use Mailgun\Model\Tag\CountryResponse;
use Mailgun\Model\Tag\DeleteResponse;
use Mailgun\Model\Tag\DeviceResponse;
use Mailgun\Model\Tag\IndexResponse;
use Mailgun\Model\Tag\ProviderResponse;
use Mailgun\Model\Tag\ShowResponse;
use Mailgun\Model\Tag\StatisticsResponse;
use Mailgun\Model\Tag\UpdateResponse;
use Psr\Http\Message\ResponseInterface;
/**
* {@link https://documentation.mailgun.com/api-tags.html#tags}.
* @see https://documentation.mailgun.com/en/latest/api-tags.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
@ -26,16 +31,14 @@ 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);
Assert::range($limit, 1, 1000);
$params = [
'limit' => $limit,
@ -49,12 +52,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 +67,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 +87,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 +103,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);
@ -125,4 +115,43 @@ class Tag extends HttpApi
return $this->hydrateResponse($response, DeleteResponse::class);
}
/**
* @return CountryResponse|ResponseInterface
*/
public function countries(string $domain, string $tag)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
$response = $this->httpGet(sprintf('/v3/%s/tags/%s/stats/aggregates/countries', $domain, $tag));
return $this->hydrateResponse($response, CountryResponse::class);
}
/**
* @return ProviderResponse|ResponseInterface
*/
public function providers(string $domain, string $tag)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
$response = $this->httpGet(sprintf('/v3/%s/tags/%s/stats/aggregates/providers', $domain, $tag));
return $this->hydrateResponse($response, ProviderResponse::class);
}
/**
* @return DeviceResponse|ResponseInterface
*/
public function devices(string $domain, string $tag)
{
Assert::stringNotEmpty($domain);
Assert::stringNotEmpty($tag);
$response = $this->httpGet(sprintf('/v3/%s/tags/%s/stats/aggregates/devices', $domain, $tag));
return $this->hydrateResponse($response, DeviceResponse::class);
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -9,7 +11,6 @@
namespace Mailgun\Api;
use Http\Client\HttpClient;
use Mailgun\Assert;
use Mailgun\Hydrator\Hydrator;
use Mailgun\Model\Webhook\CreateResponse;
@ -17,9 +18,13 @@ 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;
use Psr\Http\Client\ClientInterface;
/**
* @see https://documentation.mailgun.com/en/latest/api-webhooks.html
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Webhook extends HttpApi
@ -29,13 +34,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(ClientInterface $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator, string $apiKey)
{
parent::__construct($httpClient, $requestBuilder, $hydrator);
$this->apiKey = $apiKey;
@ -46,14 +45,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 +63,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 +74,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 +86,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 +105,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 +123,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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -14,6 +16,6 @@ namespace Mailgun;
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
interface Exception
interface Exception extends \Throwable
{
}

View file

@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Exception;
use Mailgun\Exception;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class HttpClientException extends \RuntimeException implements Exception
{
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var array
*/
private $responseBody = [];
/**
* @var int
*/
private $responseCode;
public function __construct(string $message, int $code, ResponseInterface $response)
{
parent::__construct($message, $code);
$this->response = $response;
$this->responseCode = $response->getStatusCode();
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
$this->responseBody['message'] = $body;
} else {
$this->responseBody = json_decode($body, true);
}
}
public static function badRequest(ResponseInterface $response)
{
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
$validationMessage = $body;
} else {
$jsonDecoded = json_decode($body, true);
$validationMessage = isset($jsonDecoded['message']) ? $jsonDecoded['message'] : $body;
}
$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)
{
return new self('Your credentials are incorrect.', 401, $response);
}
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)
{
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)
{
return new self('Payload too large, your total attachment size is too big.', 413, $response);
}
public static function forbidden(ResponseInterface $response)
{
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
$validationMessage = $body;
} else {
$jsonDecoded = json_decode($body, true);
$validationMessage = isset($jsonDecoded['Error']) ? $jsonDecoded['Error'] : $body;
}
$message = sprintf("Forbidden!\n\n%s", $validationMessage);
return new self($message, 403, $response);
}
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
public function getResponseBody(): array
{
return $this->responseBody;
}
public function getResponseCode(): int
{
return $this->responseCode;
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -16,17 +18,17 @@ 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);
}
public static function networkError(\Exception $previous)
public static function networkError(\Throwable $previous)
{
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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -7,16 +9,16 @@
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
namespace Mailgun\HttpClient;
use Http\Client\HttpClient;
use Http\Client\Common\PluginClient;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\UriFactoryDiscovery;
use Http\Message\UriFactory;
use Http\Client\Common\Plugin;
use Http\Client\Common\PluginClient;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Mailgun\HttpClient\Plugin\History;
use Mailgun\HttpClient\Plugin\ReplaceUriPlugin;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\UriFactoryInterface;
/**
* Configure a HTTP client.
@ -43,12 +45,12 @@ final class HttpClientConfigurator
private $apiKey;
/**
* @var UriFactory
* @var UriFactoryInterface
*/
private $uriFactory;
/**
* @var HttpClient
* @var ClientInterface
*/
private $httpClient;
@ -62,10 +64,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,102 +82,65 @@ 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(): UriFactoryInterface
{
if (null === $this->uriFactory) {
$this->uriFactory = UriFactoryDiscovery::find();
$this->uriFactory = Psr17FactoryDiscovery::findUrlFactory();
}
return $this->uriFactory;
}
/**
* @param UriFactory $uriFactory
*
* @return HttpClientConfigurator
*/
public function setUriFactory(UriFactory $uriFactory)
public function setUriFactory(UriFactoryInterface $uriFactory): self
{
$this->uriFactory = $uriFactory;
return $this;
}
/**
* @return HttpClient
*/
private function getHttpClient()
private function getHttpClient(): ClientInterface
{
if (null === $this->httpClient) {
$this->httpClient = HttpClientDiscovery::find();
$this->httpClient = Psr18ClientDiscovery::find();
}
return $this->httpClient;
}
/**
* @param HttpClient $httpClient
*
* @return HttpClientConfigurator
*/
public function setHttpClient(HttpClient $httpClient)
public function setHttpClient(ClientInterface $httpClient): self
{
$this->httpClient = $httpClient;
return $this;
}
/**
* @return History
*/
public function getResponseHistory()
public function getResponseHistory(): History
{
return $this->responseHistory;
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -10,7 +12,6 @@
namespace Mailgun\HttpClient\Plugin;
use Http\Client\Common\Plugin\Journal;
use Http\Client\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@ -21,6 +22,7 @@ use Psr\Http\Message\ResponseInterface;
*/
final class History implements Journal
{
use HistoryTrait;
/**
* @var ResponseInterface
*/
@ -38,8 +40,4 @@ final class History implements Journal
{
$this->lastResponse = $response;
}
public function addFailure(RequestInterface $request, Exception $exception)
{
}
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\HttpClient\Plugin;
use Http\Client\Exception;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
/*
* Below is a some code to make the History plugin compatible with both 1.x and 2.x of php-client/client-common
*/
if (\interface_exists(\Http\Client\Common\HttpMethodsClientInterface::class)) {
/**
* @internal code for php-http/client-common:2.x
*/
trait HistoryTrait
{
public function addFailure(RequestInterface $request, ClientExceptionInterface $exception)
{
}
}
} else {
/**
* @internal code for php-http/client-common:1.x
*/
trait HistoryTrait
{
public function addFailure(RequestInterface $request, Exception $exception)
{
}
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -20,23 +22,19 @@ use Psr\Http\Message\UriInterface;
*/
final class ReplaceUriPlugin implements Plugin
{
use Plugin\VersionBridgePlugin;
/**
* @var UriInterface
*/
private $uri;
/**
* @param UriInterface $uri
*/
public function __construct(UriInterface $uri)
{
$this->uri = $uri;
}
/**
* {@inheritdoc}
*/
public function handleRequest(RequestInterface $request, callable $next, callable $first)
public function doHandleRequest(RequestInterface $request, callable $next, callable $first)
{
$request = $request->withUri($this->uri);

View file

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\HttpClient;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class RequestBuilder
{
/**
* @var RequestFactoryInterface|null
*/
private $requestFactory;
/**
* @var StreamFactoryInterface|null
*/
private $streamFactory;
/**
* @var MultipartStreamBuilder
*/
private $multipartStreamBuilder;
/**
* Creates a new PSR-7 request.
*
* @param array|string|null $body Request body. If body is an array we will send a as multipart stream request.
* If array, each array *item* MUST look like:
* array (
* 'content' => string|resource|StreamInterface,
* 'name' => string,
* 'filename'=> string (optional)
* 'headers' => array (optinal) ['header-name' => 'header-value']
* )
*/
public function create(string $method, string $uri, array $headers = [], $body = null): RequestInterface
{
if (!is_array($body)) {
$stream = $this->getStreamFactory()->createStream((string) $body);
return $this->createRequest($method, $uri, $headers, $stream);
}
$builder = $this->getMultipartStreamBuilder();
foreach ($body as $item) {
$name = $item['name'];
$content = $item['content'];
unset($item['name']);
unset($item['content']);
$builder->addResource($name, $content, $item);
}
$multipartStream = $builder->build();
$boundary = $builder->getBoundary();
$builder->reset();
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$boundary.'"';
return $this->createRequest($method, $uri, $headers, $multipartStream);
}
private function getRequestFactory(): RequestFactoryInterface
{
if (null === $this->requestFactory) {
$this->requestFactory = Psr17FactoryDiscovery::findRequestFactory();
}
return $this->requestFactory;
}
public function setRequestFactory(RequestFactoryInterface $requestFactory): self
{
$this->requestFactory = $requestFactory;
return $this;
}
private function getStreamFactory(): StreamFactoryInterface
{
if (null === $this->streamFactory) {
$this->streamFactory = Psr17FactoryDiscovery::findStreamFactory();
}
return $this->streamFactory;
}
public function setStreamFactory(StreamFactoryInterface $streamFactory): self
{
$this->streamFactory = $streamFactory;
return $this;
}
private function getMultipartStreamBuilder(): MultipartStreamBuilder
{
if (null === $this->multipartStreamBuilder) {
$this->multipartStreamBuilder = new MultipartStreamBuilder();
}
return $this->multipartStreamBuilder;
}
public function setMultipartStreamBuilder(MultipartStreamBuilder $multipartStreamBuilder): self
{
$this->multipartStreamBuilder = $multipartStreamBuilder;
return $this;
}
private function createRequest(string $method, string $uri, array $headers, StreamInterface $stream)
{
$request = $this->getRequestFactory()->createRequest($method, $uri);
$request = $request->withBody($stream);
foreach ($headers as $name => $value) {
$request = $request->withAddedHeader($name, $value);
}
return $request;
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -20,12 +22,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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -18,12 +20,7 @@ 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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -21,20 +23,19 @@ 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');
if (0 !== strpos($contentType, 'application/json') && 0 !== strpos($contentType, 'application/octet-stream')) {
throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type: '.$contentType);
}
$data = json_decode($body, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -19,12 +21,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');
}

141
src/Mailgun.php Normal file
View file

@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
use Http\Client\Common\PluginClient;
use Mailgun\HttpClient\HttpClientConfigurator;
use Mailgun\HttpClient\Plugin\History;
use Mailgun\HttpClient\RequestBuilder;
use Mailgun\Hydrator\ModelHydrator;
use Mailgun\Hydrator\Hydrator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Client\ClientInterface;
/**
* This class is the base class for the Mailgun SDK.
*/
class Mailgun
{
/**
* @var string|null
*/
private $apiKey;
/**
* @var ClientInterface|PluginClient
*/
private $httpClient;
/**
* @var Hydrator
*/
private $hydrator;
/**
* @var RequestBuilder
*/
private $requestBuilder;
/**
* This is a object that holds the last response from the API.
*
* @var History
*/
private $responseHistory;
public function __construct(
HttpClientConfigurator $configurator,
Hydrator $hydrator = null,
RequestBuilder $requestBuilder = null
) {
$this->requestBuilder = $requestBuilder ?: new RequestBuilder();
$this->hydrator = $hydrator ?: new ModelHydrator();
$this->httpClient = $configurator->createConfiguredClient();
$this->apiKey = $configurator->getApiKey();
$this->responseHistory = $configurator->getResponseHistory();
}
public static function create(string $apiKey, string $endpoint = 'https://api.mailgun.net'): self
{
$httpClientConfigurator = (new HttpClientConfigurator())
->setApiKey($apiKey)
->setEndpoint($endpoint);
return new self($httpClientConfigurator);
}
public function getLastResponse(): ?ResponseInterface
{
return $this->responseHistory->getLastResponse();
}
public function attachment(): Api\Attachment
{
return new Api\Attachment($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function domains(): Api\Domain
{
return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function emailValidation(): Api\EmailValidation
{
return new Api\EmailValidation($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function events(): Api\Event
{
return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function ips(): Api\Ip
{
return new Api\Ip($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function mailingList(): Api\MailingList
{
return new Api\MailingList($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function messages(): Api\Message
{
return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function routes(): Api\Route
{
return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function suppressions(): Api\Suppression
{
return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function stats(): Api\Stats
{
return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function tags(): Api\Tag
{
return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function webhooks(): Api\Webhook
{
return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator, $this->apiKey);
}
}

View file

@ -1,40 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection\Exceptions;
use Mailgun\Exception;
/**
* @deprecated Will be removed in 3.0
*/
class GenericHTTPError extends \Exception implements Exception
{
protected $httpResponseCode;
protected $httpResponseBody;
public function __construct($message = null, $response_code = null, $response_body = null, $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->httpResponseCode = $response_code;
$this->httpResponseBody = $response_body;
}
public function getHttpResponseCode()
{
return $this->httpResponseCode;
}
public function getHttpResponseBody()
{
return $this->httpResponseBody;
}
}

View file

@ -1,19 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection\Exceptions;
use Mailgun\Exception;
/**
* @deprecated Will be removed in 3.0
*/
class InvalidCredentials extends \Exception implements Exception
{
}

View file

@ -1,19 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection\Exceptions;
use Mailgun\Exception;
/**
* @deprecated Will be removed in 3.0
*/
class MissingEndpoint extends \Exception implements Exception
{
}

View file

@ -1,19 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection\Exceptions;
use Mailgun\Exception;
/**
* @deprecated Will be removed in 3.0
*/
class MissingRequiredParameters extends \Exception implements Exception
{
}

View file

@ -1,19 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection\Exceptions;
use Mailgun\Exception;
/**
* @deprecated Will be removed in 3.0
*/
class NoDomainsConfigured extends \Exception implements Exception
{
}

View file

@ -1,379 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Connection;
use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Mailgun\Connection\Exceptions\GenericHTTPError;
use Mailgun\Connection\Exceptions\InvalidCredentials;
use Mailgun\Connection\Exceptions\MissingEndpoint;
use Mailgun\Connection\Exceptions\MissingRequiredParameters;
use Mailgun\Constants\Api;
use Mailgun\Constants\ExceptionMessages;
use Psr\Http\Message\ResponseInterface;
/**
* This class is a wrapper for the HTTP client.
*
* @deprecated Will be removed in 3.0
*/
class RestClient
{
/**
* Your API key.
*
* @var string
*/
private $apiKey;
/**
* @var HttpClient
*/
protected $httpClient;
/**
* @var string
*/
protected $apiHost;
/**
* The version of the API to use.
*
* @var string
*/
protected $apiVersion = 'v2';
/**
* If we should use SSL or not.
*
* @var bool
*
* @deprecated To be removed in 3.0
*/
protected $sslEnabled = true;
/**
* @param string $apiKey
* @param string $apiHost
* @param HttpClient $httpClient
*/
public function __construct($apiKey, $apiHost, HttpClient $httpClient = null)
{
$this->apiKey = $apiKey;
$this->apiHost = $apiHost;
$this->httpClient = $httpClient;
}
/**
* @param string $method
* @param string $uri
* @param mixed $body
* @param array $files
* @param array $headers
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
protected function send($method, $uri, $body = null, $files = [], array $headers = [])
{
$headers['User-Agent'] = Api::SDK_USER_AGENT.'/'.Api::SDK_VERSION;
$headers['Authorization'] = 'Basic '.base64_encode(sprintf('%s:%s', Api::API_USER, $this->apiKey));
if (!empty($files)) {
$builder = new MultipartStreamBuilder();
foreach ($files as $file) {
$builder->addResource($file['name'], $file['contents'], $file);
}
$body = $builder->build();
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$builder->getBoundary().'"';
} elseif (is_array($body)) {
$body = http_build_query($body);
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
$request = MessageFactoryDiscovery::find()->createRequest($method, $this->getApiUrl($uri), $headers, $body);
$response = $this->getHttpClient()->sendRequest($request);
return $this->responseHandler($response);
}
/**
* @param string $url
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function getAttachment($url)
{
$headers['User-Agent'] = Api::SDK_USER_AGENT.'/'.Api::SDK_VERSION;
$headers['Authorization'] = 'Basic '.base64_encode(sprintf('%s:%s', Api::API_USER, $this->apiKey));
$request = MessageFactoryDiscovery::find()->createRequest('get', $url, $headers);
$response = HttpClientDiscovery::find()->sendRequest($request);
return $this->responseHandler($response);
}
/**
* @param string $endpointUrl
* @param array $postData
* @param array $files
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function post($endpointUrl, array $postData = [], $files = [])
{
$postFiles = [];
$fields = ['message', 'attachment', 'inline'];
foreach ($fields as $fieldName) {
if (isset($files[$fieldName])) {
if (is_array($files[$fieldName])) {
foreach ($files[$fieldName] as $file) {
$postFiles[] = $this->prepareFile($fieldName, $file);
}
} else {
$postFiles[] = $this->prepareFile($fieldName, $files[$fieldName]);
}
}
}
$postDataMultipart = [];
foreach ($postData as $key => $value) {
if (is_array($value)) {
foreach ($value as $subValue) {
$postDataMultipart[] = [
'name' => $key,
'contents' => $subValue,
];
}
} else {
$postDataMultipart[] = [
'name' => $key,
'contents' => $value,
];
}
}
return $this->send('POST', $endpointUrl, [], array_merge($postDataMultipart, $postFiles));
}
/**
* @param string $endpointUrl
* @param array $queryString
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function get($endpointUrl, $queryString = [])
{
return $this->send('GET', $endpointUrl.'?'.http_build_query($queryString));
}
/**
* @param string $endpointUrl
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function delete($endpointUrl)
{
return $this->send('DELETE', $endpointUrl);
}
/**
* @param string $endpointUrl
* @param mixed $putData
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function put($endpointUrl, $putData)
{
return $this->send('PUT', $endpointUrl, $putData);
}
/**
* @param ResponseInterface $responseObj
*
* @throws GenericHTTPError
* @throws InvalidCredentials
* @throws MissingEndpoint
* @throws MissingRequiredParameters
*
* @return \stdClass
*/
public function responseHandler(ResponseInterface $responseObj)
{
$httpResponseCode = (int) $responseObj->getStatusCode();
switch ($httpResponseCode) {
case 200:
$data = (string) $responseObj->getBody();
$jsonResponseData = json_decode($data, false);
$result = new \stdClass();
// return response data as json if possible, raw if not
$result->http_response_body = $data && null === $jsonResponseData ? $data : $jsonResponseData;
$result->http_response_code = $httpResponseCode;
return $result;
case 400:
throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS.$this->getResponseExceptionMessage($responseObj));
case 401:
throw new InvalidCredentials(ExceptionMessages::EXCEPTION_INVALID_CREDENTIALS);
case 404:
throw new MissingEndpoint(ExceptionMessages::EXCEPTION_MISSING_ENDPOINT.$this->getResponseExceptionMessage($responseObj));
default:
throw new GenericHTTPError(ExceptionMessages::EXCEPTION_GENERIC_HTTP_ERROR, $httpResponseCode, $responseObj->getBody());
}
}
/**
* @param ResponseInterface $responseObj
*
* @return string
*/
protected function getResponseExceptionMessage(ResponseInterface $responseObj)
{
$body = (string) $responseObj->getBody();
$response = json_decode($body);
if (JSON_ERROR_NONE == json_last_error() && isset($response->message)) {
return ' '.$response->message;
}
return '';
}
/**
* Prepare a file for the postBody.
*
* @param string $fieldName
* @param string|array $filePath
*
* @return array
*/
protected function prepareFile($fieldName, $filePath)
{
$filename = null;
if (is_array($filePath) && isset($filePath['fileContent'])) {
// File from memory
$filename = $filePath['filename'];
$resource = fopen('php://temp', 'r+');
fwrite($resource, $filePath['fileContent']);
rewind($resource);
} else {
// Backward compatibility code
if (is_array($filePath) && isset($filePath['filePath'])) {
$filename = $filePath['remoteName'];
$filePath = $filePath['filePath'];
}
// Remove leading @ symbol
if (0 === strpos($filePath, '@')) {
$filePath = substr($filePath, 1);
}
$resource = fopen($filePath, 'r');
}
return [
'name' => $fieldName,
'contents' => $resource,
'filename' => $filename,
];
}
/**
* @return HttpClient
*/
protected function getHttpClient()
{
if (null === $this->httpClient) {
$this->httpClient = HttpClientDiscovery::find();
}
return $this->httpClient;
}
/**
* @param string $uri
*
* @return string
*/
private function getApiUrl($uri)
{
return $this->generateEndpoint($this->apiHost, $this->apiVersion, $this->sslEnabled).$uri;
}
/**
* @param string $apiEndpoint
* @param string $apiVersion
* @param bool $ssl
*
* @return string
*/
private function generateEndpoint($apiEndpoint, $apiVersion, $ssl)
{
return ($ssl ? 'https://' : 'http://').$apiEndpoint.'/'.$apiVersion.'/';
}
/**
* @param string $apiVersion
*
* @return RestClient
*/
public function setApiVersion($apiVersion)
{
$this->apiVersion = $apiVersion;
return $this;
}
/**
* @param bool $sslEnabled
*
* @return RestClient
*
* @deprecated To be removed in 3.0
*/
public function setSslEnabled($sslEnabled)
{
$this->sslEnabled = $sslEnabled;
return $this;
}
}

View file

@ -1,30 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Constants;
/**
* @deprecated Will be removed in 3.0
*/
class Api
{
const API_USER = 'api';
const SDK_VERSION = '1.7';
const SDK_USER_AGENT = 'mailgun-sdk-php';
const RECIPIENT_COUNT_LIMIT = 1000;
const CAMPAIGN_ID_LIMIT = 3;
const TAG_LIMIT = 3;
const DEFAULT_TIME_ZONE = 'UTC';
}

View file

@ -1,40 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Constants;
/**
* @deprecated Will be removed in 3.0
*/
class ExceptionMessages
{
const EXCEPTION_INVALID_CREDENTIALS = 'Your credentials are incorrect.';
const EXCEPTION_GENERIC_HTTP_ERROR = 'An HTTP Error has occurred! Check your network connection and try again.';
const EXCEPTION_MISSING_REQUIRED_PARAMETERS = 'The parameters passed to the API were invalid. Check your inputs!';
const EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS = 'The parameters passed to the API were invalid. Check your inputs!';
const EXCEPTION_MISSING_ENDPOINT = "The endpoint you've tried to access does not exist. Check if the domain matches the domain you have configure on Mailgun.";
const TOO_MANY_RECIPIENTS = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
const INVALID_PARAMETER_NON_ARRAY = "The parameter you've passed in position 2 must be an array.";
const INVALID_PARAMETER_ATTACHMENT = 'Attachments must be passed with an "@" preceding the file path. Web resources not supported.';
const INVALID_PARAMETER_INLINE = 'Inline images must be passed with an "@" preceding the file path. Web resources not supported.';
const TOO_MANY_PARAMETERS_CAMPAIGNS = "You've exceeded the maximum (3) campaigns for a single message.";
const TOO_MANY_PARAMETERS_TAGS = "You've exceeded the maximum (3) tags for a single message.";
const TOO_MANY_PARAMETERS_RECIPIENT = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
}

View file

@ -1,104 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Exception;
use Mailgun\Exception;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class HttpClientException extends \RuntimeException implements Exception
{
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var array
*/
private $responseBody;
/**
* @var int
*/
private $responseCode;
/**
* @param string $message
* @param int $code
* @param ResponseInterface|null $response
*/
public function __construct($message, $code, ResponseInterface $response = null)
{
parent::__construct($message, $code);
if ($response) {
$this->response = $response;
$this->responseCode = $response->getStatusCode();
$body = $response->getBody()->__toString();
if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
$this->responseBody['message'] = $body;
} else {
$this->responseBody = json_decode($body, true);
}
}
}
public static function badRequest(ResponseInterface $response = null)
{
return new self('The parameters passed to the API were invalid. Check your inputs!', 400, $response);
}
public static function unauthorized(ResponseInterface $response = null)
{
return new self('Your credentials are incorrect.', 401, $response);
}
public static function requestFailed(ResponseInterface $response = null)
{
return new self('Parameters were valid but request failed. Try again.', 402, $response);
}
public static function notFound(ResponseInterface $response = null)
{
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)
{
return new self('Payload too large, your total attachment size is too big.', 413, $response);
}
/**
* @return ResponseInterface
*/
public function getResponse()
{
return $this->response;
}
/**
* @return array
*/
public function getResponseBody()
{
return $this->responseBody;
}
/**
* @return int
*/
public function getResponseCode()
{
return $this->responseCode;
}
}

View file

@ -1,60 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Lists;
/**
* This class is used for creating a unique hash for
* mailing list subscription double-opt in requests.
*
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Lists/README.md
*/
class OptInHandler
{
/**
* @param string $mailingList
* @param string $secretAppId
* @param string $recipientAddress
*
* @return string
*/
public function generateHash($mailingList, $secretAppId, $recipientAddress)
{
$innerPayload = ['r' => $recipientAddress, 'l' => $mailingList];
$encodedInnerPayload = base64_encode(json_encode($innerPayload));
$innerHash = hash_hmac('sha1', $encodedInnerPayload, $secretAppId);
$outerPayload = ['h' => $innerHash, 'p' => $encodedInnerPayload];
return urlencode(base64_encode(json_encode($outerPayload)));
}
/**
* @param string $secretAppId
* @param string $uniqueHash
*
* @return array|bool
*/
public function validateHash($secretAppId, $uniqueHash)
{
$decodedOuterPayload = json_decode(base64_decode(urldecode($uniqueHash)), true);
$decodedHash = $decodedOuterPayload['h'];
$innerPayload = $decodedOuterPayload['p'];
$decodedInnerPayload = json_decode(base64_decode($innerPayload), true);
$computedInnerHash = hash_hmac('sha1', $innerPayload, $secretAppId);
if ($computedInnerHash == $decodedHash) {
return ['recipientAddress' => $decodedInnerPayload['r'], 'mailingList' => $decodedInnerPayload['l']];
}
return false;
}
}

View file

@ -1,116 +0,0 @@
Mailgun - Lists
====================
This is the Mailgun PHP *Lists* utilities.
The below assumes you've already installed the Mailgun PHP SDK in to your project.
If not, go back to the master README for instructions.
There is currently one utility provided.
OptInHandler: Provides methods for authenticating an OptInRequest.
The typical flow for using this utility would be as follows:
**Recipient Requests Subscribe** -> [Validate Recipient Address] -> [Generate Opt In Link] -> [Email Recipient Opt In Link]
**Recipient Clicks Opt In Link** -> [Validate Opt In Link] -> [Subscribe User] -> [Send final confirmation]
The above flow is modeled below.
Usage - Opt-In Handler (Recipient Requests Subscribe)
-----------------------------------------------------
Here's how to use Opt-In Handler to validate Opt-In requests.
```php
# First, instantiate the SDK with your API credentials, domain, and required parameters for example.
$mg = new Mailgun('key-example');
$mgValidate = new Mailgun('pub-key-example');
$domain = 'example.com';
$mailingList = 'youlist@example.com';
$secretPassphrase = 'a_secret_passphrase';
$recipientAddress = 'recipient@example.com';
# Let's validate the customer's email address, using Mailgun's validation endpoint.
$result = $mgValidate->get('address/validate', array('address' => $recipientAddress));
if($result->http_response_body->is_valid == true){
# Next, instantiate an OptInHandler object from the SDK.
$optInHandler = $mg->OptInHandler();
# Next, generate a hash.
$generatedHash = $optInHandler->generateHash($mailingList, $secretPassphrase, $recipientAddress);
# Now, let's send a confirmation to the recipient with our link.
$mg->sendMessage($domain, array('from' => 'bob@example.com',
'to' => $recipientAddress,
'subject' => 'Please Confirm!',
'html' => "<html><body>Hello,<br><br>You have requested to be subscribed
to the mailing list $mailingList. Please <a
href=\"http://yourdomain.com/subscribe.php?hash=$generatedHash\">
confirm</a> your subscription.<br><br>Thank you!</body></html>"));
# Finally, let's add the subscriber to a Mailing List, as unsubscribed, so we can track non-conversions.
$mg->post("lists/$mailingList/members", array('address' => $recipientAddress,
'subscribed' => 'no',
'upsert' => 'yes'));
}
```
Usage - Opt-In Handler (Recipient Clicks Opt In Link)
-----------------------------------------------------
Here's how to use Opt-In Handler to validate an Opt-In Hash.
```php
# First, instantiate the SDK with your API credentials and domain.
$mg = new Mailgun('key-example');
$domain = 'example.com';
# Next, instantiate an OptInHandler object from the SDK.
$optInHandler = $mg->OptInHandler();
# Next, grab the hash.
$inboundHash = $_GET['hash'];
$secretPassphrase = 'a_secret_passphrase';
# Now, validate the captured hash.
$hashValidation = $optInHandler->validateHash($secretPassphrase, $inboundHash);
# Lastly, check to see if we have results, parse, subscribe, and send confirmation.
if($hashValidation){
$validatedList = $hashValidation['mailingList'];
$validatedRecipient = $hashValidation['recipientAddress'];
$mg->put("lists/$validatedList/members/$validatedRecipient",
array('address' => $validatedRecipient,
'subscribed' => 'yes'));
$mg->sendMessage($domain, array('from' => 'bob@example.com',
'to' => $validatedRecipient,
'subject' => 'Confirmation Received!',
'html' => "<html><body>Hello,<br><br>We've successfully subscribed
you to the list, $validatedList!<br><br>Thank you!
</body></html>"));
}
```
A few notes:
1. 'a_secret_passphrase' can be anything. It's used as the *key* in hashing,
since your email address will vary.
2. validateHash() will return an array containing the recipient address and list
address.
3. You should *always* send an email confirmation before and after the
subscription request.
4. WARNING: On $_GET['hash'], you need to sanitize this value to prevent
malicious attempts to inject code.
Available Functions
-----------------------------------------------------
`string generateHash(string $mailingList, string $secretAppId, string $recipientAddress)`
`array validateHash(string $secretAppId, string $uniqueHash)`
More Documentation
------------------
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
for more information.

View file

@ -1,381 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
use Http\Client\Common\HttpMethodsClient;
use Http\Client\HttpClient;
use Mailgun\Connection\RestClient;
use Mailgun\Constants\ExceptionMessages;
use Mailgun\HttpClient\Plugin\History;
use Mailgun\Lists\OptInHandler;
use Mailgun\Messages\BatchMessage;
use Mailgun\Messages\Exceptions;
use Mailgun\Messages\MessageBuilder;
use Mailgun\Hydrator\ModelHydrator;
use Mailgun\Hydrator\Hydrator;
use Psr\Http\Message\ResponseInterface;
/**
* This class is the base class for the Mailgun SDK.
*/
class Mailgun
{
/**
* @var RestClient
*
* @depracated Will be removed in 3.0
*/
protected $restClient;
/**
* @var null|string
*/
protected $apiKey;
/**
* @var HttpMethodsClient
*/
private $httpClient;
/**
* @var Hydrator
*/
private $hydrator;
/**
* @var RequestBuilder
*/
private $requestBuilder;
/**
* This is a object that holds the last response from the API.
*
* @var History
*/
private $responseHistory = null;
/**
* @param string|null $apiKey
* @param HttpClient|null $httpClient
* @param string $apiEndpoint
* @param Hydrator|null $hydrator
* @param RequestBuilder|null $requestBuilder
*
* @internal Use Mailgun::configure or Mailgun::create instead.
*/
public function __construct(
$apiKey = null, /* Deprecated, will be removed in 3.0 */
HttpClient $httpClient = null,
$apiEndpoint = 'api.mailgun.net', /* Deprecated, will be removed in 3.0 */
Hydrator $hydrator = null,
RequestBuilder $requestBuilder = null
) {
$this->apiKey = $apiKey;
$this->restClient = new RestClient($apiKey, $apiEndpoint, $httpClient);
$this->httpClient = $httpClient;
$this->requestBuilder = $requestBuilder ?: new RequestBuilder();
$this->hydrator = $hydrator ?: new ModelHydrator();
}
/**
* @param HttpClientConfigurator $configurator
* @param Hydrator|null $hydrator
* @param RequestBuilder|null $requestBuilder
*
* @return Mailgun
*/
public static function configure(
HttpClientConfigurator $configurator,
Hydrator $hydrator = null,
RequestBuilder $requestBuilder = null
) {
$httpClient = $configurator->createConfiguredClient();
return new self($configurator->getApiKey(), $httpClient, 'api.mailgun.net', $hydrator, $requestBuilder);
}
/**
* @param string $apiKey
*
* @return Mailgun
*/
public static function create($apiKey)
{
$httpClientConfigurator = (new HttpClientConfigurator())->setApiKey($apiKey);
return self::configure($httpClientConfigurator);
}
/**
* This function allows the sending of a fully formed message OR a custom
* MIME string. If sending MIME, the string must be passed in to the 3rd
* position of the function call.
*
* @param string $workingDomain
* @param array $postData
* @param array $postFiles
*
* @throws Exceptions\MissingRequiredMIMEParameters
*
* @return \stdClass
*
* @deprecated Use Mailgun->messages()->send() instead. Will be removed in 3.0
*/
public function sendMessage($workingDomain, $postData, $postFiles = [])
{
if (is_array($postFiles)) {
return $this->post("$workingDomain/messages", $postData, $postFiles);
} elseif (is_string($postFiles)) {
$tempFile = tempnam(sys_get_temp_dir(), 'MG_TMP_MIME');
$fileHandle = fopen($tempFile, 'w');
fwrite($fileHandle, $postFiles);
$result = $this->post("$workingDomain/messages.mime", $postData, ['message' => $tempFile]);
fclose($fileHandle);
unlink($tempFile);
return $result;
} else {
throw new Exceptions\MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
}
/**
* This function checks the signature in a POST request to see if it is
* authentic.
*
* Pass an array of parameters. If you pass nothing, $_POST will be
* used instead.
*
* If this function returns FALSE, you must not process the request.
* You should reject the request with status code 403 Forbidden.
*
* @param array|null $postData
*
* @return bool
*
* @deprecated Use Mailgun->webhook() instead. Will be removed in 3.0
*/
public function verifyWebhookSignature($postData = null)
{
if (null === $postData) {
$postData = $_POST;
}
if (!isset($postData['timestamp']) || !isset($postData['token']) || !isset($postData['signature'])) {
return false;
}
$hmac = hash_hmac('sha256', "{$postData['timestamp']}{$postData['token']}", $this->apiKey);
$sig = $postData['signature'];
if (function_exists('hash_equals')) {
// hash_equals is constant time, but will not be introduced until PHP 5.6
return hash_equals($hmac, $sig);
} else {
return $hmac === $sig;
}
}
/**
* @return ResponseInterface|null
*/
public function getLastResponse()
{
return $this->responseHistory->getLastResponse();
}
/**
* @param string $endpointUrl
* @param array $postData
* @param array $files
*
* @return \stdClass
*
* @deprecated Will be removed in 3.0
*/
public function post($endpointUrl, $postData = [], $files = [])
{
return $this->restClient->post($endpointUrl, $postData, $files);
}
/**
* @param string $endpointUrl
* @param array $queryString
*
* @return \stdClass
*
* @deprecated Will be removed in 3.0
*/
public function get($endpointUrl, $queryString = [])
{
return $this->restClient->get($endpointUrl, $queryString);
}
/**
* @param string $url
*
* @return \stdClass
*
* @deprecated Will be removed in 3.0
*/
public function getAttachment($url)
{
return $this->restClient->getAttachment($url);
}
/**
* @param string $endpointUrl
*
* @return \stdClass
*
* @deprecated Will be removed in 3.0
*/
public function delete($endpointUrl)
{
return $this->restClient->delete($endpointUrl);
}
/**
* @param string $endpointUrl
* @param array $putData
*
* @return \stdClass
*
* @deprecated Will be removed in 3.0
*/
public function put($endpointUrl, $putData)
{
return $this->restClient->put($endpointUrl, $putData);
}
/**
* @param string $apiVersion
*
* @return Mailgun
*
* @deprecated Will be removed in 3.0
*/
public function setApiVersion($apiVersion)
{
$this->restClient->setApiVersion($apiVersion);
return $this;
}
/**
* @param bool $sslEnabled
*
* @return Mailgun
*
* @deprecated This will be removed in 3.0. Mailgun does not support non-secure connections to their API.
*/
public function setSslEnabled($sslEnabled)
{
$this->restClient->setSslEnabled($sslEnabled);
return $this;
}
/**
* @return MessageBuilder
*
* @deprecated Will be removed in 3.0
*/
public function MessageBuilder()
{
return new MessageBuilder();
}
/**
* @return OptInHandler
*
* @deprecated Will be removed in 3.0
*/
public function OptInHandler()
{
return new OptInHandler();
}
/**
* @param string $workingDomain
* @param bool $autoSend
*
* @return BatchMessage
*
* @deprecated Will be removed in 3.0
*/
public function BatchMessage($workingDomain, $autoSend = true)
{
return new BatchMessage($this->restClient, $workingDomain, $autoSend);
}
/**
* @return Api\Stats
*/
public function stats()
{
return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Domain
*/
public function domains()
{
return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Tag
*/
public function tags()
{
return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Event
*/
public function events()
{
return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Route
*/
public function routes()
{
return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Webhook
*/
public function webhooks()
{
return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator, $this->apiKey);
}
/**
* @return Api\Message
*/
public function messages()
{
return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
}
/**
* @return Api\Suppression
*/
public function suppressions()
{
return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
}
}

View file

@ -1,154 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Messages;
use Mailgun\Constants\Api;
use Mailgun\Constants\ExceptionMessages;
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Messages\Exceptions\TooManyParameters;
/**
* This class is used for batch sending. See the official documentation (link below)
* for usage instructions.
*
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Messages/README.md
*/
class BatchMessage extends MessageBuilder
{
/**
* @var array
*/
private $batchRecipientAttributes;
/**
* @var bool
*/
private $autoSend;
/**
* @var \Mailgun\Connection\RestClient
*/
private $restClient;
/**
* @var string
*/
private $workingDomain;
/**
* @var array
*/
private $messageIds = [];
/**
* @var string
*/
private $endpointUrl;
/**
* @param \Mailgun\Connection\RestClient $restClient
* @param string $workingDomain
* @param bool $autoSend
*/
public function __construct($restClient, $workingDomain, $autoSend)
{
$this->batchRecipientAttributes = [];
$this->autoSend = $autoSend;
$this->restClient = $restClient;
$this->workingDomain = $workingDomain;
$this->endpointUrl = $workingDomain.'/messages';
}
/**
* @param string $headerName
* @param string $address
* @param array $variables
*
* @throws MissingRequiredMIMEParameters
* @throws TooManyParameters
*/
protected function addRecipient($headerName, $address, $variables)
{
if (array_key_exists($headerName, $this->counters['recipients'])) {
if ($this->counters['recipients'][$headerName] == Api::RECIPIENT_COUNT_LIMIT) {
if (false === $this->autoSend) {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_RECIPIENTS);
}
$this->sendMessage();
}
}
$compiledAddress = $this->parseAddress($address, $variables);
if (isset($this->message[$headerName])) {
array_push($this->message[$headerName], $compiledAddress);
} elseif ('h:reply-to' == $headerName) {
$this->message[$headerName] = $compiledAddress;
} else {
$this->message[$headerName] = [$compiledAddress];
}
if (array_key_exists($headerName, $this->counters['recipients'])) {
$this->counters['recipients'][$headerName] += 1;
if (is_array($variables) && !array_key_exists('id', $variables)) {
$variables['id'] = $this->counters['recipients'][$headerName];
}
}
$this->batchRecipientAttributes["$address"] = $variables;
}
/**
* @param array $message
* @param array $files
*
* @throws MissingRequiredMIMEParameters
*/
public function sendMessage($message = [], $files = [])
{
if (count($message) < 1) {
$message = $this->message;
$files = $this->files;
}
if (!array_key_exists('from', $message)) {
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
} elseif (!array_key_exists('to', $message)) {
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
} elseif (!array_key_exists('subject', $message)) {
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
} elseif ((!array_key_exists('text', $message) && !array_key_exists('html', $message))) {
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
} else {
$message['recipient-variables'] = json_encode($this->batchRecipientAttributes);
$response = $this->restClient->post($this->endpointUrl, $message, $files);
$this->batchRecipientAttributes = [];
$this->counters['recipients']['to'] = 0;
$this->counters['recipients']['cc'] = 0;
$this->counters['recipients']['bcc'] = 0;
unset($this->message['to']);
array_push($this->messageIds, $response->http_response_body->id);
}
}
/**
* @throws MissingRequiredMIMEParameters
*/
public function finalize()
{
$this->sendMessage();
}
/**
* @return string[]
*/
public function getMessageIds()
{
return $this->messageIds;
}
}

View file

@ -1,16 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Messages\Exceptions;
use Mailgun\Exception;
class InvalidParameter extends \Exception implements Exception
{
}

View file

@ -1,16 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Messages\Exceptions;
use Mailgun\Exception;
class InvalidParameterType extends \Exception implements Exception
{
}

View file

@ -1,529 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Messages;
use Mailgun\Constants\Api;
use Mailgun\Constants\ExceptionMessages;
use Mailgun\Messages\Exceptions\InvalidParameter;
use Mailgun\Messages\Exceptions\TooManyParameters;
/**
* This class is used for composing a properly formed
* message object. Dealing with arrays can be cumbersome,
* this class makes the process easier. See the official
* documentation (link below) for usage instructions.
*
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Messages/README.md
*/
class MessageBuilder
{
/**
* @var array
*/
protected $message = [];
/**
* @var array
*/
protected $variables = [];
/**
* @var array
*/
protected $files = [];
/**
* @var array
*/
protected $counters = [
'recipients' => [
'to' => 0,
'cc' => 0,
'bcc' => 0,
],
'attributes' => [
'attachment' => 0,
'campaign_id' => 0,
'custom_option' => 0,
'tag' => 0,
],
];
/**
* @param array $params
* @param string $key
* @param mixed $default
*
* @return mixed
*/
protected function safeGet($params, $key, $default)
{
if (array_key_exists($key, $params)) {
return $params[$key];
}
return $default;
}
/**
* @param array $params
*
* @return mixed|string
*/
protected function getFullName($params)
{
if (array_key_exists('first', $params)) {
$first = $this->safeGet($params, 'first', '');
$last = $this->safeGet($params, 'last', '');
return trim("$first $last");
}
return $this->safeGet($params, 'full_name', '');
}
/**
* @param string $address
* @param array $variables
*
* @return string
*/
protected function parseAddress($address, $variables)
{
if (!is_array($variables)) {
return $address;
}
$fullName = $this->getFullName($variables);
if (null != $fullName) {
return sprintf('"%s" <%s>', $fullName, $address);
}
return $address;
}
/**
* @param string $headerName
* @param string $address
* @param array $variables
*/
protected function addRecipient($headerName, $address, $variables)
{
$compiledAddress = $this->parseAddress($address, $variables);
if ('h:reply-to' === $headerName) {
$this->message[$headerName] = $compiledAddress;
} elseif (isset($this->message[$headerName])) {
array_push($this->message[$headerName], $compiledAddress);
} else {
$this->message[$headerName] = [$compiledAddress];
}
if (array_key_exists($headerName, $this->counters['recipients'])) {
$this->counters['recipients'][$headerName] += 1;
}
}
/**
* @param string $address
* @param array|null $variables
*
* @throws TooManyParameters
*
* @return mixed
*/
public function addToRecipient($address, $variables = null)
{
if ($this->counters['recipients']['to'] > Api::RECIPIENT_COUNT_LIMIT) {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
}
$variables = is_array($variables) ? $variables : [];
$this->addRecipient('to', $address, $variables);
return end($this->message['to']);
}
/**
* @param string $address
* @param array|null $variables
*
* @throws TooManyParameters
*
* @return mixed
*/
public function addCcRecipient($address, $variables = null)
{
if ($this->counters['recipients']['cc'] > Api::RECIPIENT_COUNT_LIMIT) {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
}
$variables = is_array($variables) ? $variables : [];
$this->addRecipient('cc', $address, $variables);
return end($this->message['cc']);
}
/**
* @param string $address
* @param array|null $variables
*
* @throws TooManyParameters
*
* @return mixed
*/
public function addBccRecipient($address, $variables = null)
{
if ($this->counters['recipients']['bcc'] > Api::RECIPIENT_COUNT_LIMIT) {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
}
$variables = is_array($variables) ? $variables : [];
$this->addRecipient('bcc', $address, $variables);
return end($this->message['bcc']);
}
/**
* @param string $address
* @param array|null $variables
*
* @return mixed
*/
public function setFromAddress($address, $variables = null)
{
$variables = is_array($variables) ? $variables : [];
$this->addRecipient('from', $address, $variables);
return $this->message['from'];
}
/**
* @param string $address
* @param array|null $variables
*
* @return mixed
*/
public function setReplyToAddress($address, $variables = null)
{
$variables = is_array($variables) ? $variables : [];
$this->addRecipient('h:reply-to', $address, $variables);
return $this->message['h:reply-to'];
}
/**
* @param string $subject
*
* @return mixed
*/
public function setSubject($subject = '')
{
if (null == $subject || '' == $subject) {
$subject = ' ';
}
$this->message['subject'] = $subject;
return $this->message['subject'];
}
/**
* @param string $headerName
* @param mixed $headerData
*
* @return mixed
*/
public function addCustomHeader($headerName, $headerData)
{
if (!preg_match('/^h:/i', $headerName)) {
$headerName = 'h:'.$headerName;
}
if (array_key_exists($headerName, $this->message)) {
if (is_array($this->message[$headerName])) {
$this->message[$headerName][] = $headerData;
} else {
$this->message[$headerName] = [$this->message[$headerName], $headerData];
}
} else {
$this->message[$headerName] = $headerData;
}
return $this->message[$headerName];
}
/**
* @param string $textBody
*
* @return string
*/
public function setTextBody($textBody)
{
if (null == $textBody || '' == $textBody) {
$textBody = ' ';
}
$this->message['text'] = $textBody;
return $this->message['text'];
}
/**
* @param string $htmlBody
*
* @return string
*/
public function setHtmlBody($htmlBody)
{
if (null == $htmlBody || '' == $htmlBody) {
$htmlBody = ' ';
}
$this->message['html'] = $htmlBody;
return $this->message['html'];
}
/**
* @param string $attachmentPath
* @param string|null $attachmentName
*
* @return bool
*/
public function addAttachment($attachmentPath, $attachmentName = null)
{
if (isset($this->files['attachment'])) {
$attachment = [
'filePath' => $attachmentPath,
'remoteName' => $attachmentName,
];
array_push($this->files['attachment'], $attachment);
} else {
$this->files['attachment'] = [
[
'filePath' => $attachmentPath,
'remoteName' => $attachmentName,
],
];
}
return true;
}
/**
* @param string $inlineImagePath
* @param string|null $inlineImageName
*
* @throws InvalidParameter
*
* @return bool
*/
public function addInlineImage($inlineImagePath, $inlineImageName = null)
{
if (0 !== strpos($inlineImagePath, '@')) {
throw new InvalidParameter(ExceptionMessages::INVALID_PARAMETER_INLINE);
}
$this->files['inline'][] = [
'filePath' => $inlineImagePath,
'remoteName' => $inlineImageName,
];
return true;
}
/**
* @param bool $testMode
*
* @return string
*/
public function setTestMode($testMode)
{
if (filter_var($testMode, FILTER_VALIDATE_BOOLEAN)) {
$testMode = 'yes';
} else {
$testMode = 'no';
}
$this->message['o:testmode'] = $testMode;
return $this->message['o:testmode'];
}
/**
* @param string|int $campaignId
*
* @throws TooManyParameters
*
* @return string|int
*/
public function addCampaignId($campaignId)
{
if ($this->counters['attributes']['campaign_id'] < Api::CAMPAIGN_ID_LIMIT) {
if (isset($this->message['o:campaign'])) {
array_push($this->message['o:campaign'], $campaignId);
} else {
$this->message['o:campaign'] = [$campaignId];
}
$this->counters['attributes']['campaign_id'] += 1;
return $this->message['o:campaign'];
} else {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_CAMPAIGNS);
}
}
/**
* @param string $tag
*
* @throws TooManyParameters
*/
public function addTag($tag)
{
if ($this->counters['attributes']['tag'] < Api::TAG_LIMIT) {
if (isset($this->message['o:tag'])) {
array_push($this->message['o:tag'], $tag);
} else {
$this->message['o:tag'] = [$tag];
}
$this->counters['attributes']['tag'] += 1;
return $this->message['o:tag'];
} else {
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_TAGS);
}
}
/**
* @param bool $enabled
*
* @return mixed
*/
public function setDkim($enabled)
{
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
$enabled = 'yes';
} else {
$enabled = 'no';
}
$this->message['o:dkim'] = $enabled;
return $this->message['o:dkim'];
}
/**
* @param bool $enabled
*
* @return string
*/
public function setOpenTracking($enabled)
{
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
$enabled = 'yes';
} else {
$enabled = 'no';
}
$this->message['o:tracking-opens'] = $enabled;
return $this->message['o:tracking-opens'];
}
/**
* @param bool $enabled
*
* @return string
*/
public function setClickTracking($enabled)
{
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
$enabled = 'yes';
} elseif ('html' == $enabled) {
$enabled = 'html';
} else {
$enabled = 'no';
}
$this->message['o:tracking-clicks'] = $enabled;
return $this->message['o:tracking-clicks'];
}
/**
* @param string $timeDate
* @param string|null $timeZone
*
* @return string
*/
public function setDeliveryTime($timeDate, $timeZone = null)
{
if (isset($timeZone)) {
$timeZoneObj = new \DateTimeZone("$timeZone");
} else {
$timeZoneObj = new \DateTimeZone(Api::DEFAULT_TIME_ZONE);
}
$dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
$formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
$this->message['o:deliverytime'] = $formattedTimeDate;
return $this->message['o:deliverytime'];
}
/**
* @param string $customName
* @param mixed $data
*/
public function addCustomData($customName, $data)
{
$this->message['v:'.$customName] = json_encode($data);
}
/**
* @param string $parameterName
* @param mixed $data
*
* @return mixed
*/
public function addCustomParameter($parameterName, $data)
{
if (isset($this->message[$parameterName])) {
array_push($this->message[$parameterName], $data);
return $this->message[$parameterName];
} else {
$this->message[$parameterName] = [$data];
return $this->message[$parameterName];
}
}
/**
* @param array $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* @return array
*/
public function getMessage()
{
return $this->message;
}
/**
* @return array
*/
public function getFiles()
{
return $this->files;
}
}

View file

@ -1,136 +0,0 @@
Mailgun - Messages
====================
This is the Mailgun PHP *Message* utilities.
The below assumes you've already installed the Mailgun PHP SDK in to your
project. If not, go back to the master README for instructions.
There are two utilities included, Message Builder and Batch Message.
Message Builder: Allows you to build a message object by calling methods for
each MIME attribute.
Batch Message: Inherits Message Builder and allows you to iterate through
recipients from a list. Messages will fire after the 1,000th recipient has been
added.
Usage - Message Builder
-----------------------
Here's how to use Message Builder to build your Message.
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";
# Next, instantiate a Message Builder object from the SDK.
$messageBldr = $mg->MessageBuilder();
# Define the from address.
$messageBldr->setFromAddress("me@example.com", array("first"=>"PHP", "last" => "SDK"));
# Define a to recipient.
$messageBldr->addToRecipient("john.doe@example.com", array("first" => "John", "last" => "Doe"));
# Define a cc recipient.
$messageBldr->addCcRecipient("sally.doe@example.com", array("first" => "Sally", "last" => "Doe"));
# Define the subject.
$messageBldr->setSubject("A message from the PHP SDK using Message Builder!");
# Define the body of the message.
$messageBldr->setTextBody("This is the text body of the message!");
# Other Optional Parameters.
$messageBldr->addCampaignId("My-Awesome-Campaign");
$messageBldr->addCustomHeader("Customer-Id", "12345");
$messageBldr->addAttachment("@/tron.jpg");
$messageBldr->setDeliveryTime("tomorrow 8:00AM", "PST");
$messageBldr->setClickTracking(true);
# Finally, send the message.
$mg->post("{$domain}/messages", $messageBldr->getMessage(), $messageBldr->getFiles());
```
Available Functions
-----------------------------------------------------
`string addToRecipient(string $address, array $attributes)`
`string addCcRecipient(string $address, array $attributes)`
`string addBccRecipient(string $address, array $attributes)`
`string setFromAddress(string $address, array $attributes)`
`string setSubject(string $subject)`
`string setTextBody(string $textBody)`
`string setHtmlBody(string $htmlBody)`
`bool addAttachment(string $attachmentPath, $attachmentName = null)`
`bool addInlineImage(string $inlineImagePath)`
`string setTestMode(bool $testMode)`
`string addCampaignId(string $campaignId)`
`string setDkim(bool $enabled)`
`string setOpenTracking($enabled)`
`string setClickTracking($enabled)`
`string setDeliveryTime(string $timeDate, string $timeZone)`
`string addCustomData(string $optionName, string $data)`
`string addCustomParameter(string $parameterName, string $data)`
`array getMessage()`
`array getFiles()`
Usage - Batch Message
---------------------
Here's how to use Batch Message to easily handle batch sending jobs.
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";
# Next, instantiate a Message Builder object from the SDK, pass in your sending domain.
$batchMsg = $mg->BatchMessage($domain);
# Define the from address.
$batchMsg->setFromAddress("me@example.com", array("first"=>"PHP", "last" => "SDK"));
# Define the subject.
$batchMsg->setSubject("A Batch Message from the PHP SDK!");
# Define the body of the message.
$batchMsg->setTextBody("This is the text body of the message!");
# Next, let's add a few recipients to the batch job.
$batchMsg->addToRecipient("john.doe@example.com", array("first" => "John", "last" => "Doe"));
$batchMsg->addToRecipient("sally.doe@example.com", array("first" => "Sally", "last" => "Doe"));
$batchMsg->addToRecipient("mike.jones@example.com", array("first" => "Mike", "last" => "Jones"));
...
// After 1,000 recipients, Batch Message will automatically post your message to the messages endpoint.
// Call finalize() to send any remaining recipients still in the buffer.
$batchMsg->finalize();
```
Available Functions (Inherits all Batch Message and Messages Functions)
-----------------------------------------------------------------------
`addToRecipient(string $address, string $attributes)`
`sendMessage(array $message, array $files)`
`array finalize()`
More Documentation
------------------
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
for more information.

View file

@ -1,72 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
use Mailgun\Model\ApiResponse;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
final class ConnectionResponse implements ApiResponse
{
/**
* @var bool
*/
private $noVerify;
/**
* @var bool
*/
private $requireTLS;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
if (!isset($data['connection'])) {
return;
}
$connSettings = $data['connection'];
return new self(
isset($connSettings['skip_verification']) ? $connSettings['skip_verification'] : null,
isset($connSettings['require_tls']) ? $connSettings['require_tls'] : null
);
}
/**
* @param bool $noVerify Disable remote TLS certificate verification
* @param bool $requireTLS Requires TLS for all outbound communication
*/
private function __construct($noVerify, $requireTLS)
{
$this->noVerify = $noVerify;
$this->requireTLS = $requireTLS;
}
/**
* @return bool
*/
public function getSkipVerification()
{
return $this->noVerify;
}
/**
* @return bool
*/
public function getRequireTLS()
{
return $this->requireTLS;
}
}

View file

@ -1,97 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
final class CredentialResponseItem
{
/**
* @var int|null
*/
private $sizeBytes;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var string
*/
private $mailbox;
/**
* @var string
*/
private $login;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
$sizeBytes = isset($data['size_bytes']) ? $data['size_bytes'] : null;
$mailbox = isset($data['mailbox']) ? $data['mailbox'] : null;
$login = isset($data['login']) ? $data['login'] : null;
$createdAt = isset($data['created_at']) ? new \DateTime($data['created_at']) : null;
return new self($sizeBytes, $createdAt, $mailbox, $login);
}
/**
* @param int $sizeBytes
* @param \DateTime $createdAt
* @param string $mailbox
* @param string $login
*/
private function __construct($sizeBytes, \DateTime $createdAt, $mailbox, $login)
{
$this->sizeBytes = $sizeBytes;
$this->createdAt = $createdAt;
$this->mailbox = $mailbox;
$this->login = $login;
}
/**
* @return int|null
*/
public function getSizeBytes()
{
return $this->sizeBytes;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @return string
*/
public function getMailbox()
{
return $this->mailbox;
}
/**
* @return string
*/
public function getLogin()
{
return $this->login;
}
}

View file

@ -1,83 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class DeleteCredentialResponse implements ApiResponse
{
/**
* @var string
*/
private $message;
/**
* @var string
*/
private $error;
/**
* @var string
*/
private $spec;
/**
* @param string $message
* @param string $error
* @param string $spec
*/
private function __construct($message, $error, $spec)
{
$this->message = $message;
$this->error = $error;
$this->spec = $spec;
}
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['message']) ? $data['message'] : null,
isset($data['error']) ? $data['error'] : null,
isset($data['spec']) ? $data['spec'] : null
);
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @return string
*/
public function getSpec()
{
return $this->spec;
}
}

View file

@ -1,67 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class DeleteResponse implements ApiResponse
{
/**
* @var string
*/
private $message;
/**
* @var string
*/
private $error;
/**
* @param string $message
* @param string $error
*/
private function __construct($message, $error)
{
$this->message = $message;
$this->error = $error;
}
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['message']) ? $data['message'] : null,
isset($data['error']) ? $data['error'] : null
);
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
}

View file

@ -1,139 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
/**
* Represents a single DNS record for a domain.
*
* @author Sean Johnson <sean@mailgun.com>
*/
final class DnsRecord
{
/**
* @var string|null
*/
private $name;
/**
* @var string
*/
private $type;
/**
* @var string
*/
private $value;
/**
* @var string|null
*/
private $priority;
/**
* @var string
*/
private $valid;
/**
* @var array
*/
private $cached;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
$name = isset($data['name']) ? $data['name'] : null;
$priority = isset($data['priority']) ? $data['priority'] : null;
$recordType = isset($data['record_type']) ? $data['record_type'] : null;
$value = isset($data['value']) ? $data['value'] : null;
$valid = isset($data['valid']) ? $data['valid'] : null;
$cached = isset($data['cached']) ? $data['cached'] : null;
return new self($name, $recordType, $value, $priority, $valid, $cached);
}
/**
* @param string|null $name Name of the record, as used in CNAME, etc.
* @param string $type DNS record type
* @param string $value DNS record value
* @param string|null $priority Record priority, used for MX
* @param string $valid DNS record has been added to domain DNS?
* @param array $cached DNS record current value
*/
private function __construct($name, $type, $value, $priority, $valid, $cached)
{
$this->name = $name;
$this->type = $type;
$this->value = $value;
$this->priority = $priority;
$this->valid = $valid;
$this->cached = $cached;
}
/**
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @return string|null
*/
public function getPriority()
{
return $this->priority;
}
/**
* @return bool
*/
public function isValid()
{
return 'valid' === $this->valid;
}
/**
* @return string
*/
public function getValidity()
{
return $this->valid;
}
/**
* @return array
*/
public function getCached()
{
return $this->cached;
}
}

View file

@ -1,147 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
/**
* Represents domain information in its simplest form.
*
* @author Sean Johnson <sean@ramcloud.io>
*/
final class Domain
{
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var string
*/
private $smtpLogin;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $smtpPassword;
/**
* @var bool
*/
private $wildcard;
/**
* @var string
*/
private $spamAction;
/**
* @var string
*/
private $state;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['name']) ? $data['name'] : null,
isset($data['smtp_login']) ? $data['smtp_login'] : null,
isset($data['smtp_password']) ? $data['smtp_password'] : null,
isset($data['wildcard']) ? $data['wildcard'] : null,
isset($data['spam_action']) ? $data['spam_action'] : null,
isset($data['state']) ? $data['state'] : null,
isset($data['created_at']) ? new \DateTime($data['created_at']) : null
);
}
/**
* @param string $name
* @param string $smtpLogin
* @param string $smtpPassword
* @param bool $wildcard
* @param string $spamAction
* @param string $state
* @param \DateTime $createdAt
*/
private function __construct($name, $smtpLogin, $smtpPassword, $wildcard, $spamAction, $state, \DateTime $createdAt)
{
$this->name = $name;
$this->smtpLogin = $smtpLogin;
$this->smtpPassword = $smtpPassword;
$this->wildcard = $wildcard;
$this->spamAction = $spamAction;
$this->state = $state;
$this->createdAt = $createdAt;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getSmtpUsername()
{
return $this->smtpLogin;
}
/**
* @return string
*/
public function getSmtpPassword()
{
return $this->smtpPassword;
}
/**
* @return bool
*/
public function isWildcard()
{
return $this->wildcard;
}
/**
* @return string
*/
public function getSpamAction()
{
return $this->spamAction;
}
/**
* @return string
*/
public function getState()
{
return $this->state;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}

View file

@ -1,83 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Domain;
use Mailgun\Model\ApiResponse;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
final class UpdateConnectionResponse implements ApiResponse
{
/**
* @var string
*/
private $message;
/**
* @var bool
*/
private $noVerify;
/**
* @var bool
*/
private $requireTLS;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
$message = isset($data['message']) ? $data['message'] : null;
$noVerify = isset($data['skip_verification']) ? $data['skip_verification'] : null;
$requireTLS = isset($data['require_tls']) ? $data['require_tls'] : null;
return new self($message, $noVerify, $requireTLS);
}
/**
* @param string $message
* @param bool $noVerify
* @param bool $requireTLS
*/
private function __construct($message, $noVerify, $requireTLS)
{
$this->message = $message;
$this->noVerify = $noVerify;
$this->requireTLS = $requireTLS;
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return bool
*/
public function getSkipVerification()
{
return $this->noVerify;
}
/**
* @return bool
*/
public function getRequireTLS()
{
return $this->requireTLS;
}
}

View file

@ -1,505 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Event;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class Event
{
/**
* @var string status
*/
private $event;
/**
* @var string
*/
private $id;
/**
* @var float
*/
private $timestamp;
/**
* A \DateTime representation of $timestamp.
*
* @var \DateTime
*/
private $eventDate;
/**
* @var array|string[]
*/
private $tags = [];
/**
* @var string
*/
private $url;
/**
* @var string
*/
private $severity;
/**
* @var array
*/
private $envelope = [];
/**
* @var array
*/
private $deliveryStatus;
/**
* @var array|string[]
*/
private $campaigns = [];
/**
* @var string
*/
private $ip;
/**
* @var array
*/
private $clientInfo = [];
/**
* @var string
*/
private $reason;
/**
* @var array
*/
private $userVariables = [];
/**
* @var array key=>bool
*/
private $flags = [];
/**
* @var array multi dimensions
*/
private $routes = [];
/**
* @var array multi dimensions
*/
private $message = [];
/**
* @var string
*/
private $recipient;
/**
* @var array
*/
private $geolocation = [];
/**
* @var array
*/
private $storage = [];
/**
* @var string
*/
private $method;
/**
* @param string $event
* @param string $id
* @param float $timestamp
*/
public function __construct($event, $id, $timestamp)
{
$this->event = $event;
$this->id = $id;
$this->timestamp = $timestamp;
$this->eventDate = new \DateTime();
$this->eventDate->setTimestamp((int) $timestamp);
}
/**
* @param array $data
*
* @return Event
*/
public static function create(array $data)
{
$event = new self($data['event'], $data['id'], $data['timestamp']);
if (isset($data['tags'])) {
$event->setTags($data['tags']);
}
if (isset($data['envelope'])) {
$event->setEnvelope($data['envelope']);
}
if (isset($data['campaigns'])) {
$event->setCampaigns($data['campaigns']);
}
if (isset($data['user-variables'])) {
$event->setUserVariables($data['user-variables']);
}
if (isset($data['flags'])) {
$event->setFlags($data['flags']);
}
if (isset($data['routes'])) {
$event->setRoutes($data['routes']);
}
if (isset($data['message'])) {
$event->setMessage($data['message']);
}
if (isset($data['recipient'])) {
$event->setRecipient($data['recipient']);
}
if (isset($data['method'])) {
$event->setMethod($data['method']);
}
if (isset($data['delivery-status'])) {
$event->setDeliveryStatus($data['delivery-status']);
}
if (isset($data['severity'])) {
$event->setSeverity($data['severity']);
}
if (isset($data['reason'])) {
$event->setReason($data['reason']);
}
if (isset($data['geolocation'])) {
$event->setGeolocation($data['geolocation']);
}
if (isset($data['ip'])) {
$event->setIp($data['ip']);
}
if (isset($data['client-info'])) {
$event->setClientInfo($data['client-info']);
}
if (isset($data['url'])) {
$event->setUrl($data['url']);
}
if (isset($data['storage'])) {
$event->setStorage($data['storage']);
}
return $event;
}
/**
* @return string
*/
public function getEvent()
{
return $this->event;
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @return float
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* @return \DateTime
*/
public function getEventDate()
{
return $this->eventDate;
}
/**
* @return array|\string[]
*/
public function getTags()
{
return $this->tags;
}
/**
* @param array|\string[] $tags
*/
private function setTags($tags)
{
$this->tags = $tags;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
*/
private function setUrl($url)
{
$this->url = $url;
}
/**
* @return array
*/
public function getEnvelope()
{
return $this->envelope;
}
/**
* @param array $envelope
*/
private function setEnvelope($envelope)
{
$this->envelope = $envelope;
}
/**
* @return array
*/
public function getDeliveryStatus()
{
return $this->deliveryStatus;
}
/**
* @param array $deliveryStatus
*/
private function setDeliveryStatus($deliveryStatus)
{
$this->deliveryStatus = $deliveryStatus;
}
/**
* @return array|\string[]
*/
public function getCampaigns()
{
return $this->campaigns;
}
/**
* @param array|\string[] $campaigns
*/
private function setCampaigns($campaigns)
{
$this->campaigns = $campaigns;
}
/**
* @return string
*/
public function getIp()
{
return $this->ip;
}
/**
* @param string $ip
*/
private function setIp($ip)
{
$this->ip = $ip;
}
/**
* @return array
*/
public function getClientInfo()
{
return $this->clientInfo;
}
/**
* @param array $clientInfo
*/
private function setClientInfo($clientInfo)
{
$this->clientInfo = $clientInfo;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
*/
private function setReason($reason)
{
$this->reason = $reason;
}
/**
* @return array
*/
public function getUserVariables()
{
return $this->userVariables;
}
/**
* @param array $userVariables
*/
private function setUserVariables($userVariables)
{
$this->userVariables = $userVariables;
}
/**
* @return array
*/
public function getFlags()
{
return $this->flags;
}
/**
* @param array $flags
*/
private function setFlags($flags)
{
$this->flags = $flags;
}
/**
* @return array
*/
public function getRoutes()
{
return $this->routes;
}
/**
* @param array $routes
*/
private function setRoutes($routes)
{
$this->routes = $routes;
}
/**
* @return array
*/
public function getMessage()
{
return $this->message;
}
/**
* @param array $message
*/
private function setMessage($message)
{
$this->message = $message;
}
/**
* @return string
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* @param string $recipient
*/
private function setRecipient($recipient)
{
$this->recipient = $recipient;
}
/**
* @return array
*/
public function getGeolocation()
{
return $this->geolocation;
}
/**
* @param array $geolocation
*/
private function setGeolocation($geolocation)
{
$this->geolocation = $geolocation;
}
/**
* @return array
*/
public function getStorage()
{
return $this->storage;
}
/**
* @param array $storage
*/
private function setStorage($storage)
{
$this->storage = $storage;
}
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* @param string $method
*/
private function setMethod($method)
{
$this->method = $method;
}
/**
* @return string
*/
public function getSeverity()
{
return $this->severity;
}
/**
* @param string $severity
*/
private function setSeverity($severity)
{
$this->severity = $severity;
}
}

View file

@ -1,74 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Message;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class SendResponse implements ApiResponse
{
/**
* @var string
*/
private $id;
/**
* @var string
*/
private $message;
/**
* @param string $id
* @param string $message
*/
private function __construct($id, $message)
{
$this->id = $id;
$this->message = $message;
}
/**
* @param array $data
*
* @return SendResponse
*/
public static function create(array $data)
{
$id = '';
$message = '';
if (isset($data['id'])) {
$id = $data['id'];
}
if (isset($data['message'])) {
$message = $data['message'];
}
return new self($id, $message);
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
}

View file

@ -1,402 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Message;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ShowResponse implements ApiResponse
{
/**
* Only available with message/rfc2822.
*
* @var string
*/
private $recipient;
/**
* Only available with message/rfc2822.
*
* @var string
*/
private $bodyMime;
/**
* @var string
*/
private $recipients;
/**
* @var string
*/
private $sender;
/**
* @var string
*/
private $from;
/**
* @var string
*/
private $subject;
/**
* @var string
*/
private $bodyPlain;
/**
* @var string
*/
private $strippedText;
/**
* @var string
*/
private $strippedSignature;
/**
* @var string
*/
private $bodyHtml;
/**
* @var string
*/
private $strippedHtml;
/**
* @var array
*/
private $attachments;
/**
* @var string
*/
private $messageUrl;
/**
* @var string
*/
private $contentIdMap;
/**
* @var array
*/
private $messageHeaders;
/**
* Do not let this object be creted without the ::create.
*/
private function __construct()
{
}
/**
* @param array $data
*
* @return SendResponse
*/
public static function create(array $data)
{
$response = new self();
if (isset($data['recipients'])) {
$response->setRecipients($data['recipients']);
}
if (isset($data['sender'])) {
$response->setSender($data['sender']);
}
if (isset($data['from'])) {
$response->setFrom($data['from']);
}
if (isset($data['subject'])) {
$response->setSubject($data['subject']);
}
if (isset($data['body-plain'])) {
$response->setBodyPlain($data['body-plain']);
}
if (isset($data['stripped-text'])) {
$response->setStrippedText($data['stripped-text']);
}
if (isset($data['stripped-signature'])) {
$response->setStrippedSignature($data['stripped-signature']);
}
if (isset($data['body-html'])) {
$response->setBodyHtml($data['body-html']);
}
if (isset($data['stripped-html'])) {
$response->setStrippedHtml($data['stripped-html']);
}
if (isset($data['message-url'])) {
$response->setMessageUrl($data['message-url']);
}
if (isset($data['message-headers'])) {
$response->setMessageHeaders($data['message-headers']);
}
if (isset($data['recipient'])) {
$response->setRecipient($data['recipient']);
}
if (isset($data['body-mime'])) {
$response->setBodyMime($data['body-mime']);
}
if (isset($data['attachments'])) {
$response->setAttachments($data['attachments']);
}
if (isset($data['content-id-map'])) {
$response->setContentIdMap($data['content-id-map']);
}
return $response;
}
/**
* @return string
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* @param string $recipient
*/
private function setRecipient($recipient)
{
$this->recipient = $recipient;
}
/**
* @return string
*/
public function getBodyMime()
{
return $this->bodyMime;
}
/**
* @param string $bodyMime
*/
private function setBodyMime($bodyMime)
{
$this->bodyMime = $bodyMime;
}
/**
* @return string
*/
public function getRecipients()
{
return $this->recipients;
}
/**
* @param string $recipients
*/
private function setRecipients($recipients)
{
$this->recipients = $recipients;
}
/**
* @return string
*/
public function getSender()
{
return $this->sender;
}
/**
* @param string $sender
*/
private function setSender($sender)
{
$this->sender = $sender;
}
/**
* @return string
*/
public function getFrom()
{
return $this->from;
}
/**
* @param string $from
*/
private function setFrom($from)
{
$this->from = $from;
}
/**
* @return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* @param string $subject
*/
private function setSubject($subject)
{
$this->subject = $subject;
}
/**
* @return string
*/
public function getBodyPlain()
{
return $this->bodyPlain;
}
/**
* @param string $bodyPlain
*/
private function setBodyPlain($bodyPlain)
{
$this->bodyPlain = $bodyPlain;
}
/**
* @return string
*/
public function getStrippedText()
{
return $this->strippedText;
}
/**
* @param string $strippedText
*/
private function setStrippedText($strippedText)
{
$this->strippedText = $strippedText;
}
/**
* @return string
*/
public function getStrippedSignature()
{
return $this->strippedSignature;
}
/**
* @param string $strippedSignature
*/
private function setStrippedSignature($strippedSignature)
{
$this->strippedSignature = $strippedSignature;
}
/**
* @return string
*/
public function getBodyHtml()
{
return $this->bodyHtml;
}
/**
* @param string $bodyHtml
*/
private function setBodyHtml($bodyHtml)
{
$this->bodyHtml = $bodyHtml;
}
/**
* @return string
*/
public function getStrippedHtml()
{
return $this->strippedHtml;
}
/**
* @param string $strippedHtml
*/
private function setStrippedHtml($strippedHtml)
{
$this->strippedHtml = $strippedHtml;
}
/**
* @return array
*/
public function getAttachments()
{
return $this->attachments;
}
/**
* @param array $attachments
*/
private function setAttachments($attachments)
{
$this->attachments = $attachments;
}
/**
* @return string
*/
public function getMessageUrl()
{
return $this->messageUrl;
}
/**
* @param string $messageUrl
*/
private function setMessageUrl($messageUrl)
{
$this->messageUrl = $messageUrl;
}
/**
* @return string
*/
public function getContentIdMap()
{
return $this->contentIdMap;
}
/**
* @param string $contentIdMap
*/
public function setContentIdMap($contentIdMap)
{
$this->contentIdMap = $contentIdMap;
}
/**
* @return array
*/
public function getMessageHeaders()
{
return $this->messageHeaders;
}
/**
* @param array $messageHeaders
*/
private function setMessageHeaders(array $messageHeaders)
{
$this->messageHeaders = $messageHeaders;
}
}

View file

@ -1,69 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
trait PaginationResponse
{
/**
* @var array
*/
protected $paging;
/**
* @return string
*/
public function getNextUrl()
{
if (!isset($this->paging['next'])) {
return;
}
return $this->paging['next'];
}
/**
* @return string
*/
public function getPreviousUrl()
{
if (!isset($this->paging['previous'])) {
return;
}
return $this->paging['previous'];
}
/**
* @return string
*/
public function getFirstUrl()
{
if (!isset($this->paging['first'])) {
return;
}
return $this->paging['first'];
}
/**
* @return string
*/
public function getLastUrl()
{
if (!isset($this->paging['last'])) {
return;
}
return $this->paging['last'];
}
}

View file

@ -1,68 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route\Response;
use Mailgun\Model\Route\Route;
use Mailgun\Model\ApiResponse;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class CreateResponse implements ApiResponse
{
/**
* @var string
*/
private $message;
/**
* @var Route
*/
private $route;
/**
* {@inheritdoc}
*/
public static function create(array $data)
{
$message = isset($data['message']) ? $data['message'] : null;
$route = isset($data['route']) ? Route::create($data['route']) : null;
return new self($message, $route);
}
/**
* CreateResponse Private Constructor.
*
* @param string|null $message
* @param Route|null $route
*/
private function __construct($message = null, Route $route = null)
{
$this->message = $message;
$this->route = $route;
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return Route
*/
public function getRoute()
{
return $this->route;
}
}

View file

@ -1,67 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route\Response;
use Mailgun\Model\ApiResponse;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class DeleteResponse implements ApiResponse
{
/**
* @var string
*/
private $message;
/**
* @var string
*/
private $error;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['message']) ? $data['message'] : null,
isset($data['error']) ? $data['error'] : null
);
}
/**
* @param string $message
* @param string $error
*/
private function __construct($message, $error)
{
$this->message = $message;
$this->error = $error;
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
}

View file

@ -1,77 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route\Response;
use Mailgun\Model\Route\Route;
use Mailgun\Model\ApiResponse;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class IndexResponse implements ApiResponse
{
/**
* @var int
*/
private $totalCount;
/**
* @var Route[]
*/
private $items;
/**
* {@inheritdoc}
*/
public static function create(array $data)
{
$items = [];
if (isset($data['items'])) {
foreach ($data['items'] as $item) {
$items[] = Route::create($item);
}
}
if (isset($data['total_count'])) {
$count = $data['total_count'];
} else {
$count = count($items);
}
return new self($count, $items);
}
/**
* @param int $totalCount
* @param Route[] $items
*/
private function __construct($totalCount, array $items)
{
$this->totalCount = $totalCount;
$this->items = $items;
}
/**
* @return int
*/
public function getTotalCount()
{
return $this->totalCount;
}
/**
* @return Route[]
*/
public function getRoutes()
{
return $this->items;
}
}

View file

@ -1,54 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route\Response;
use Mailgun\Model\Route\Route;
use Mailgun\Model\ApiResponse;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class ShowResponse implements ApiResponse
{
/**
* @var Route|null
*/
private $route;
/**
* {@inheritdoc}
*/
public static function create(array $data)
{
if (isset($data['route'])) {
return new self(Route::create($data['route']));
}
return new self();
}
/**
* ShowResponse constructor.
*
* @param Route|null $route
*/
private function __construct(Route $route = null)
{
$this->route = $route;
}
/**
* @return Route|null
*/
public function getRoute()
{
return $this->route;
}
}

View file

@ -1,68 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route\Response;
use Mailgun\Model\ApiResponse;
use Mailgun\Model\Route\Route;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class UpdateResponse implements ApiResponse
{
/**
* @var string|null
*/
private $message;
/**
* @var Route|null
*/
private $route;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
$message = isset($data['message']) ? $data['message'] : null;
$route = isset($data['id']) ? Route::create($data) : null;
return new self($message, $route);
}
/**
* @param string|null $message
* @param Route|null $route
*/
private function __construct($message = null, Route $route = null)
{
$this->message = $message;
$this->route = $route;
}
/**
* @return string|null
*/
public function getMessage()
{
return $this->message;
}
/**
* @return Route|null
*/
public function getRoute()
{
return $this->route;
}
}

View file

@ -1,133 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Route;
/**
* @author David Garcia <me@davidgarcia.cat>
*/
final class Route
{
/**
* @var string
*/
private $id;
/**
* @var int
*/
private $priority;
/**
* @var string
*/
private $filter;
/**
* @var Action[]
*/
private $actions;
/**
* @var string
*/
private $description;
/**
* @var \DateTime
*/
private $createdAt;
/**
* Route Named Constructor.
*
* @param array $data
*
* @return Route
*/
public static function create(array $data)
{
return new self(
isset($data['id']) ? $data['id'] : null,
isset($data['priority']) ? $data['priority'] : null,
isset($data['expression']) ? $data['expression'] : null,
isset($data['actions']) ? $data['actions'] : [],
isset($data['description']) ? $data['description'] : null,
isset($data['created_at']) ? new \DateTime($data['created_at']) : null
);
}
/**
* Route Private Constructor.
*
* @param string $id
* @param int $priority
* @param string $expression
* @param array $actions
* @param string $description
* @param \DateTime $createdAt
*/
private function __construct($id, $priority, $expression, $actions, $description, \DateTime $createdAt = null)
{
$this->id = $id;
$this->priority = $priority;
$this->filter = $expression;
$this->actions = Action::createMultiple($actions);
$this->description = $description;
$this->createdAt = $createdAt;
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @return Action[]
*/
public function getActions()
{
return $this->actions;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @return string
*/
public function getFilter()
{
return $this->filter;
}
/**
* @return int
*/
public function getPriority()
{
return $this->priority;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}

View file

@ -1,113 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Stats;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class AllResponseItem
{
/**
* @var string
*/
private $id;
/**
* @var string
*/
private $event;
/**
* @var string
*/
private $totalCount;
/**
* @var string[]
*/
private $tags;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['id']) ? $data['id'] : null,
isset($data['event']) ? $data['event'] : null,
isset($data['total_count']) ? $data['total_count'] : null,
isset($data['tags']) ? $data['tags'] : null,
isset($data['created_at']) ? new \DateTime($data['created_at']) : null
);
}
/**
* @param string $id
* @param string $event
* @param string $totalCount
* @param \string[] $tags
* @param \DateTime $createdAt
*/
private function __construct($id, $event, $totalCount, array $tags, \DateTime $createdAt)
{
$this->id = $id;
$this->event = $event;
$this->totalCount = $totalCount;
$this->tags = $tags;
$this->createdAt = $createdAt;
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getEvent()
{
return $this->event;
}
/**
* @return string
*/
public function getTotalCount()
{
return $this->totalCount;
}
/**
* @return string[]
*/
public function getTags()
{
return $this->tags;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}

View file

@ -1,105 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Stats;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class TotalResponse implements ApiResponse
{
/**
* @var \DateTime
*/
private $start;
/**
* @var \DateTime
*/
private $end;
/**
* @var string
*/
private $resolution;
/**
* @var TotalResponseItem[]
*/
private $stats;
/**
* @param \DateTime $start
* @param \DateTime $end
* @param string $resolution
* @param TotalResponseItem[] $stats
*/
private function __construct(\DateTime $start, \DateTime $end, $resolution, array $stats)
{
$this->start = $start;
$this->end = $end;
$this->resolution = $resolution;
$this->stats = $stats;
}
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
$stats = [];
if (isset($data['stats'])) {
foreach ($data['stats'] as $s) {
$stats[] = TotalResponseItem::create($s);
}
}
$start = isset($data['start']) ? new \DateTime($data['start']) : null;
$end = isset($data['end']) ? new \DateTime($data['end']) : null;
$resolution = isset($data['resolution']) ? $data['resolution'] : null;
return new self($start, $end, $resolution, $stats);
}
/**
* @return \DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* @return \DateTime
*/
public function getEnd()
{
return $this->end;
}
/**
* @return string
*/
public function getResolution()
{
return $this->resolution;
}
/**
* @return TotalResponseItem[]
*/
public function getStats()
{
return $this->stats;
}
}

View file

@ -1,97 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Stats;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class TotalResponseItem
{
/**
* @var \DateTime
*/
private $time;
/**
* @var array
*/
private $accepted;
/**
* @var array
*/
private $delivered;
/**
* @var array
*/
private $failed;
/**
* @param array $data
*
* @return self
*/
public static function create(array $data)
{
return new self(
isset($data['time']) ? new \DateTime($data['time']) : null,
isset($data['accepted']) ? $data['accepted'] : [],
isset($data['delivered']) ? $data['delivered'] : [],
isset($data['failed']) ? $data['failed'] : []
);
}
/**
* @param \DateTime $time
* @param array $accepted
* @param array $delivered
* @param array $failed
*/
private function __construct(\DateTime $time, array $accepted, array $delivered, array $failed)
{
$this->time = $time;
$this->accepted = $accepted;
$this->delivered = $delivered;
$this->failed = $failed;
}
/**
* @return \DateTime
*/
public function getTime()
{
return $this->time;
}
/**
* @return array
*/
public function getAccepted()
{
return $this->accepted;
}
/**
* @return array
*/
public function getDelivered()
{
return $this->delivered;
}
/**
* @return array
*/
public function getFailed()
{
return $this->failed;
}
}

View file

@ -1,69 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Suppression;
use Mailgun\Model\ApiResponse;
/**
* Serves only as an abstract base for Suppression API code.
*
* @author Sean Johnson <sean@mailgun.com>
*/
abstract class BaseResponse implements ApiResponse
{
/**
* @var string
*/
private $address;
/**
* @var string
*/
private $message;
/**
* @param string $address
* @param string $message
*/
private function __construct($address, $message)
{
$this->address = $address;
$this->message = $message;
}
/**
* @param array $data
*
* @return BaseResponse
*/
public static function create(array $data)
{
$address = isset($data['address']) ? $data['address'] : '';
$message = isset($data['message']) ? $data['message'] : '';
return new static($address, $message);
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
}

View file

@ -1,123 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Suppression\Bounce;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
class Bounce
{
/**
* @var string
*/
private $address;
/**
* @var string
*/
private $code;
/**
* @var string
*/
private $error;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @param string $address
*/
private function __construct($address)
{
$this->address = $address;
$this->createdAt = new \DateTime();
}
/**
* @param array $data
*
* @return Bounce
*/
public static function create(array $data)
{
$bounce = new self($data['address']);
if (isset($data['code'])) {
$bounce->setCode($data['code']);
}
if (isset($data['error'])) {
$bounce->setError($data['error']);
}
if (isset($data['created_at'])) {
$bounce->setCreatedAt(new \DateTime($data['created_at']));
}
return $bounce;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* @param string $code
*/
private function setCode($code)
{
$this->code = $code;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @param string $error
*/
private function setError($error)
{
$this->error = $error;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
private function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
}

View file

@ -1,75 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Suppression\Complaint;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
class Complaint
{
/**
* @var string
*/
private $address;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @param string $address
*/
private function __construct($address)
{
$this->address = $address;
$this->createdAt = new \DateTime();
}
/**
* @param array $data
*
* @return Complaint
*/
public static function create(array $data)
{
$complaint = new self($data['address']);
if (isset($data['created_at'])) {
$complaint->setCreatedAt(new \DateTime($data['created_at']));
}
return $complaint;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
private function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
}

View file

@ -1,99 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Suppression\Unsubscribe;
/**
* @author Sean Johnson <sean@mailgun.com>
*/
class Unsubscribe
{
/**
* @var string
*/
private $address;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var array
*/
private $tags = [];
/**
* @param string $address
*/
private function __construct($address)
{
$this->address = $address;
$this->createdAt = new \DateTime();
}
/**
* @param array $data
*
* @return Unsubscribe
*/
public static function create(array $data)
{
$unsubscribe = new self($data['address']);
if (isset($data['tags'])) {
$unsubscribe->setTags($data['tags']);
}
if (isset($data['created_at'])) {
$unsubscribe->setCreatedAt(new \DateTime($data['created_at']));
}
return $unsubscribe;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
private function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @param array $tags
*/
private function setTags($tags)
{
$this->tags = $tags;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
}

View file

@ -1,131 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Tag;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class StatisticsResponse implements ApiResponse
{
/**
* @var string
*/
private $tag;
/**
* @var string
*/
private $description;
/**
* @var string
*/
private $resolution;
/**
* @var \DateTime
*/
private $start;
/**
* @var \DateTime
*/
private $end;
/**
* @var array
*/
private $stats;
/**
* @param string $tag
* @param string $description
* @param \DateTime $start
* @param \DateTime $end
* @param string $resolution
* @param array $stats
*/
private function __construct($tag, $description, \DateTime $start, \DateTime $end, $resolution, array $stats)
{
$this->tag = $tag;
$this->description = $description;
$this->resolution = $resolution;
$this->start = $start;
$this->end = $end;
$this->stats = $stats;
}
/**
* @param array $data
*
* @return StatisticsResponse
*/
public static function create(array $data)
{
return new self(
$data['tag'],
$data['description'],
new \DateTime($data['start']),
new \DateTime($data['end']),
$data['resolution'],
$data['stats']
);
}
/**
* @return string
*/
public function getTag()
{
return $this->tag;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @return string
*/
public function getResolution()
{
return $this->resolution;
}
/**
* @return \DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* @return \DateTime
*/
public function getEnd()
{
return $this->end;
}
/**
* @return array
*/
public function getStats()
{
return $this->stats;
}
}

View file

@ -1,73 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Tag;
class Tag
{
/**
* @var string
*/
private $tag;
/**
* @var string
*/
private $description;
/**
* @var \DateTime
*/
private $firstSeen;
/**
* @var \DateTime
*/
private $lastSeen;
/**
* @param string $tag
* @param string $description
* @param \DateTime $firstSeen
* @param \DateTime $lastSeen
*/
public function __construct($tag, $description, \DateTime $firstSeen, \DateTime $lastSeen)
{
$this->tag = $tag;
$this->description = $description;
$this->firstSeen = $firstSeen;
$this->lastSeen = $lastSeen;
}
/**
* @param array $data
*
* @return Tag
*/
public static function create(array $data)
{
return new self($data['tag'], $data['description'], $data['first-seen'], $data['last-seen']);
}
/**
* @return string
*/
public function getTag()
{
return $this->tag;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
}

View file

@ -1,78 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Webhook;
use Mailgun\Model\ApiResponse;
/**
* This is only mean to be the base response for Webhook API.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
abstract class BaseResponse implements ApiResponse
{
/**
* @var array
*/
private $webhook = [];
/**
* @var string
*/
private $message;
/**
* @param array $webhook
* @param string $message
*/
public function __construct(array $webhook, $message)
{
$this->webhook = $webhook;
$this->message = $message;
}
/**
* @param array $data
*
* @return static
*/
public static function create(array $data)
{
$webhook = [];
$message = '';
if (isset($data['webhook'])) {
$webhook = $data['webhook'];
}
if (isset($data['message'])) {
$message = $data['message'];
}
return new static($webhook, $message);
}
/**
* @return string|null
*/
public function getWebhookUrl()
{
if (isset($this->webhook['url'])) {
return $this->webhook['url'];
}
}
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
}

View file

@ -1,220 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Webhook;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class IndexResponse implements ApiResponse
{
/**
* @var array
*/
private $bounce = [];
/**
* @var array
*/
private $deliver = [];
/**
* @var array
*/
private $drop = [];
/**
* @var array
*/
private $spam = [];
/**
* @var array
*/
private $unsubscribe = [];
/**
* @var array
*/
private $click = [];
/**
* @var array
*/
private $open = [];
/**
* Do not let this object be creted without the ::create.
*/
private function __construct()
{
}
/**
* @param array $data
*
* @return IndexResponse
*/
public static function create(array $data)
{
$self = new self();
$data = isset($data['webhooks']) ? $data['webhooks'] : $data;
if (isset($data['bounce'])) {
$self->setBounce($data['bounce']);
}
if (isset($data['deliver'])) {
$self->setDeliver($data['deliver']);
}
if (isset($data['drop'])) {
$self->setDrop($data['drop']);
}
if (isset($data['spam'])) {
$self->setSpam($data['spam']);
}
if (isset($data['unsubscribe'])) {
$self->setUnsubscribe($data['unsubscribe']);
}
if (isset($data['click'])) {
$self->setClick($data['click']);
}
if (isset($data['open'])) {
$self->setOpen($data['open']);
}
return $self;
}
/**
* @return string|null
*/
public function getBounceUrl()
{
if (isset($this->bounce['url'])) {
return $this->bounce['url'];
}
}
/**
* @param array $bounce
*/
private function setBounce($bounce)
{
$this->bounce = $bounce;
}
/**
* @return string|null
*/
public function getDeliverUrl()
{
if (isset($this->deliver['url'])) {
return $this->deliver['url'];
}
}
/**
* @param array $deliver
*/
private function setDeliver($deliver)
{
$this->deliver = $deliver;
}
/**
* @return string|null
*/
public function getDropUrl()
{
if (isset($this->drop['url'])) {
return $this->drop['url'];
}
}
/**
* @param array $drop
*/
private function setDrop($drop)
{
$this->drop = $drop;
}
/**
* @return string|null
*/
public function getSpamUrl()
{
if (isset($this->spam['url'])) {
return $this->spam['url'];
}
}
/**
* @param array $spam
*/
private function setSpam($spam)
{
$this->spam = $spam;
}
/**
* @return string|null
*/
public function getUnsubscribeUrl()
{
if (isset($this->unsubscribe['url'])) {
return $this->unsubscribe['url'];
}
}
/**
* @param array $unsubscribe
*/
private function setUnsubscribe($unsubscribe)
{
$this->unsubscribe = $unsubscribe;
}
/**
* @return string|null
*/
public function getClickUrl()
{
if (isset($this->click['url'])) {
return $this->click['url'];
}
}
/**
* @param array $click
*/
private function setClick($click)
{
$this->click = $click;
}
/**
* @return string|null
*/
public function getOpenUrl()
{
if (isset($this->open['url'])) {
return $this->open['url'];
}
}
/**
* @param array $open
*/
private function setOpen($open)
{
$this->open = $open;
}
}

View file

@ -1,56 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Model\Webhook;
use Mailgun\Model\ApiResponse;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ShowResponse implements ApiResponse
{
/**
* @var array
*/
private $webhook = [];
/**
* @param array $webhook
*/
public function __construct(array $webhook)
{
$this->webhook = $webhook;
}
/**
* @param array $data
*
* @return ShowResponse
*/
public static function create(array $data)
{
$webhook = [];
if (isset($data['webhook'])) {
$webhook = $data['webhook'];
}
return new self($webhook);
}
/**
* @return string|null
*/
public function getWebhookUrl()
{
if (isset($this->webhook['url'])) {
return $this->webhook['url'];
}
}
}

View file

@ -1,121 +0,0 @@
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Http\Message\RequestFactory;
use Psr\Http\Message\RequestInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class RequestBuilder
{
/**
* @var RequestFactory
*/
private $requestFactory;
/**
* @var MultipartStreamBuilder
*/
private $multipartStreamBuilder;
/**
* Creates a new PSR-7 request.
*
* @param string $method
* @param string $uri
* @param array $headers
* @param array|string|null $body Request body. If body is an array we will send a as multipart stream request.
* If array, each array *item* MUST look like:
* array (
* 'content' => string|resource|StreamInterface,
* 'name' => string,
* 'filename'=> string (optional)
* 'headers' => array (optinal) ['header-name' => 'header-value']
* )
*
* @return RequestInterface
*/
public function create($method, $uri, array $headers = [], $body = null)
{
if (!is_array($body)) {
return $this->getRequestFactory()->createRequest($method, $uri, $headers, $body);
}
$builder = $this->getMultipartStreamBuilder();
foreach ($body as $item) {
$name = $item['name'];
$content = $item['content'];
unset($item['name']);
unset($item['content']);
$builder->addResource($name, $content, $item);
}
$multipartStream = $builder->build();
$boundary = $builder->getBoundary();
$builder->reset();
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$boundary.'"';
return $this->getRequestFactory()->createRequest($method, $uri, $headers, $multipartStream);
}
/**
* @return RequestFactory
*/
private function getRequestFactory()
{
if (null === $this->requestFactory) {
$this->requestFactory = MessageFactoryDiscovery::find();
}
return $this->requestFactory;
}
/**
* @param RequestFactory $requestFactory
*
* @return RequestBuilder
*/
public function setRequestFactory($requestFactory)
{
$this->requestFactory = $requestFactory;
return $this;
}
/**
* @return MultipartStreamBuilder
*/
private function getMultipartStreamBuilder()
{
if (null === $this->multipartStreamBuilder) {
$this->multipartStreamBuilder = new MultipartStreamBuilder();
}
return $this->multipartStreamBuilder;
}
/**
* @param MultipartStreamBuilder $multipartStreamBuilder
*
* @return RequestBuilder
*/
public function setMultipartStreamBuilder($multipartStreamBuilder)
{
$this->multipartStreamBuilder = $multipartStreamBuilder;
return $this;
}
}

View file

@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Message;
use Mailgun\Api\Message;
use Mailgun\Message\Exceptions\MissingRequiredParameter;
use Mailgun\Message\Exceptions\RuntimeException;
use Mailgun\Message\Exceptions\TooManyRecipients;
/**
* This class is used for batch sending. See the official documentation (link below)
* for usage instructions.
*
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Message/README.md
*/
class BatchMessage extends MessageBuilder
{
/**
* @var array
*/
private $batchRecipientAttributes = [];
/**
* @var bool
*/
private $autoSend;
/**
* @var array
*/
private $messageIds = [];
/**
* @var string
*/
private $domain;
/**
* @var Message
*/
private $api;
public function __construct(Message $messageApi, string $domain, bool $autoSend)
{
$this->api = $messageApi;
$this->domain = $domain;
$this->autoSend = $autoSend;
}
/**
* @param array $variables {
*
* @var string $id
* @var string $full_name
* @var string $first
* @var string $last
* }
*
* @throws MissingRequiredParameter
* @throws TooManyRecipients
*/
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]) {
if (false === $this->autoSend) {
throw TooManyRecipients::whenAutoSendDisabled();
}
$this->finalize();
}
}
parent::addRecipient($headerName, $address, $variables);
if (array_key_exists($headerName, $this->counters['recipients']) && !array_key_exists('id', $variables)) {
$variables['id'] = $headerName.'_'.$this->counters['recipients'][$headerName];
}
$this->batchRecipientAttributes[$address] = $variables;
return $this;
}
/**
* @throws RuntimeException
* @throws MissingRequiredParameter
*/
public function finalize(): void
{
$message = $this->message;
if (empty($this->domain)) {
throw new RuntimeException('You must call BatchMessage::setDomain before sending messages.');
}
if (empty($message['from'])) {
throw MissingRequiredParameter::create('from');
}
if (empty($message['to'])) {
throw MissingRequiredParameter::create('to');
}
if (empty($message['subject'])) {
throw MissingRequiredParameter::create('subject');
}
if (empty($message['text']) && empty($message['html'])) {
throw MissingRequiredParameter::create('text" or "html');
}
$message['recipient-variables'] = json_encode($this->batchRecipientAttributes);
$response = $this->api->send($this->domain, $message);
$this->batchRecipientAttributes = [];
$this->counters['recipients']['to'] = 0;
$this->counters['recipients']['cc'] = 0;
$this->counters['recipients']['bcc'] = 0;
unset($this->message['to']);
$this->messageIds[] = $response->getId();
}
/**
* @return string[]
*/
public function getMessageIds(): array
{
return $this->messageIds;
}
}

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Message\Exceptions;
use Mailgun\Exception;
class LimitExceeded extends \Exception implements Exception
{
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

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Message\Exceptions;
use Mailgun\Exception;
class MissingRequiredParameter extends \Exception implements Exception
{
public static function create(string $parameter, string $message = null)
{
if (null === $message) {
$message = 'The parameters passed to the API were invalid. Please specify "%s".';
}
return new self(sprintf($message, $parameter));
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
@ -7,10 +9,10 @@
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Messages\Exceptions;
namespace Mailgun\Message\Exceptions;
use Mailgun\Exception;
class MissingRequiredMIMEParameters extends \Exception implements Exception
class RuntimeException extends \RuntimeException implements Exception
{
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Message\Exceptions;
use Mailgun\Exception;
use Mailgun\Message\MessageBuilder;
class TooManyRecipients extends LimitExceeded implements Exception
{
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(int $limit = MessageBuilder::RECIPIENT_COUNT_LIMIT)
{
return new self(sprintf('You\'ve exceeded the maximum recipient count (%s) with autosend disabled.', $limit));
}
}

View file

@ -0,0 +1,410 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Message;
use Mailgun\Message\Exceptions\LimitExceeded;
use Mailgun\Message\Exceptions\TooManyRecipients;
/**
* This class is used for composing a properly formed
* message object. Dealing with arrays can be cumbersome,
* this class makes the process easier. See the official
* documentation (link below) for usage instructions.
*
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Message/README.md
*/
class MessageBuilder
{
const RECIPIENT_COUNT_LIMIT = 1000;
const CAMPAIGN_ID_LIMIT = 3;
const TAG_LIMIT = 3;
/**
* @var array
*/
protected $message = [];
/**
* @var array
*/
protected $variables = [];
/**
* @var array
*/
protected $counters = [
'recipients' => [
'to' => 0,
'cc' => 0,
'bcc' => 0,
],
'attributes' => [
'attachment' => 0,
'campaign_id' => 0,
'custom_option' => 0,
'tag' => 0,
],
];
private function get(array $params, string $key, $default)
{
if (array_key_exists($key, $params)) {
return $params[$key];
}
return $default;
}
/**
* @param array $params {
*
* @var string $full_name
* @var string $first
* @var string $last
* }
*/
private function getFullName(array $params): string
{
if (isset($params['full_name'])) {
return $this->get($params, 'full_name', '');
}
return trim(sprintf('%s %s', $this->get($params, 'first', ''), $this->get($params, 'last', '')));
}
/**
* @var string
* @var string $first
* @var string $last
* }
*/
protected function parseAddress(string $address, array $variables): string
{
$fullName = $this->getFullName($variables);
if (!empty($fullName)) {
return sprintf('"%s" <%s>', $fullName, $address);
}
return $address;
}
/**
* @param array $variables {
*
* @var string $full_name
* @var string $first
* @var string $last
* }
*/
protected function addRecipient(string $headerName, string $address, array $variables): self
{
$compiledAddress = $this->parseAddress($address, $variables);
if ('h:reply-to' === $headerName) {
$this->message[$headerName] = $compiledAddress;
} elseif (isset($this->message[$headerName])) {
$this->message[$headerName][] = $compiledAddress;
} else {
$this->message[$headerName] = [$compiledAddress];
}
if (array_key_exists($headerName, $this->counters['recipients'])) {
++$this->counters['recipients'][$headerName];
}
return $this;
}
/**
* @param array $variables {
*
* @var string $id If used with BatchMessage
* @var string $full_name
* @var string $first
* @var string $last
* }
*
* @throws TooManyRecipients
*/
public function addToRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['to'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('to');
}
$this->addRecipient('to', $address, $variables);
return $this;
}
/**
* @param array $variables {
*
* @var string $id If used with BatchMessage
* @var string $full_name
* @var string $first
* @var string $last
* }
*
* @throws TooManyRecipients
*/
public function addCcRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['cc'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('cc');
}
$this->addRecipient('cc', $address, $variables);
return $this;
}
/**
* @param array $variables {
*
* @var string $id If used with BatchMessage
* @var string $full_name
* @var string $first
* @var string $last
* }
*
* @throws TooManyRecipients
*/
public function addBccRecipient(string $address, array $variables = []): self
{
if ($this->counters['recipients']['bcc'] > self::RECIPIENT_COUNT_LIMIT) {
throw TooManyRecipients::create('bcc');
}
$this->addRecipient('bcc', $address, $variables);
return $this;
}
/**
* @param array $variables {
*
* @var string $id If used with BatchMessage
* @var string $full_name
* @var string $first
* @var string $last
* }
*/
public function setFromAddress(string $address, array $variables = []): self
{
$this->addRecipient('from', $address, $variables);
return $this;
}
/**
* @param array $variables {
*
* @var string $id If used with BatchMessage
* @var string $full_name
* @var string $first
* @var string $last
* }
*/
public function setReplyToAddress(string $address, array $variables = []): self
{
$this->addRecipient('h:reply-to', $address, $variables);
return $this;
}
public function setSubject(string $subject): self
{
$this->message['subject'] = $subject;
return $this;
}
public function addCustomHeader(string $headerName, $headerData): self
{
if (!preg_match('/^h:/i', $headerName)) {
$headerName = 'h:'.$headerName;
}
if (!array_key_exists($headerName, $this->message)) {
$this->message[$headerName] = $headerData;
} else {
if (is_array($this->message[$headerName])) {
$this->message[$headerName][] = $headerData;
} else {
$this->message[$headerName] = [$this->message[$headerName], $headerData];
}
}
return $this;
}
public function setTextBody(string $textBody): self
{
$this->message['text'] = $textBody;
return $this;
}
public function setHtmlBody(string $htmlBody): self
{
$this->message['html'] = $htmlBody;
return $this;
}
public function addAttachment(string $attachmentPath, string $attachmentName = null): self
{
if (!isset($this->message['attachment'])) {
$this->message['attachment'] = [];
}
$this->message['attachment'][] = [
'filePath' => $attachmentPath,
'filename' => $attachmentName,
];
return $this;
}
public function addInlineImage(string $inlineImagePath, string $inlineImageName = null): self
{
if (!isset($this->message['inline'])) {
$this->message['inline'] = [];
}
$this->message['inline'][] = [
'filePath' => $inlineImagePath,
'filename' => $inlineImageName,
];
return $this;
}
public function setTestMode(bool $enabled): self
{
$this->message['o:testmode'] = $enabled ? 'yes' : 'no';
return $this;
}
/**
* @throws LimitExceeded
*/
public function addCampaignId(string $campaignId): self
{
if ($this->counters['attributes']['campaign_id'] >= self::CAMPAIGN_ID_LIMIT) {
throw LimitExceeded::create('campaigns', self::CAMPAIGN_ID_LIMIT);
}
if (isset($this->message['o:campaign'])) {
array_push($this->message['o:campaign'], $campaignId);
} else {
$this->message['o:campaign'] = [$campaignId];
}
++$this->counters['attributes']['campaign_id'];
return $this;
}
/**
* @throws LimitExceeded
*/
public function addTag(string $tag): self
{
if ($this->counters['attributes']['tag'] >= self::TAG_LIMIT) {
throw LimitExceeded::create('tags', self::TAG_LIMIT);
}
if (isset($this->message['o:tag'])) {
array_push($this->message['o:tag'], $tag);
} else {
$this->message['o:tag'] = [$tag];
}
++$this->counters['attributes']['tag'];
return $this;
}
public function setDkim(bool $enabled): self
{
$this->message['o:dkim'] = $enabled ? 'yes' : 'no';
return $this;
}
public function setOpenTracking(bool $enabled): self
{
$this->message['o:tracking-opens'] = $enabled ? 'yes' : 'no';
return $this;
}
public function setClickTracking(bool $enabled, bool $htmlOnly = false): self
{
$value = 'no';
if ($enabled) {
$value = 'yes';
if ($htmlOnly) {
$value = 'htmlonly';
}
}
$this->message['o:tracking-clicks'] = $value;
return $this;
}
public function setDeliveryTime(string $timeDate, string $timeZone = null): self
{
if (null !== $timeZone) {
$timeZoneObj = new \DateTimeZone($timeZone);
} else {
$timeZoneObj = new \DateTimeZone('UTC');
}
$dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
$formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
$this->message['o:deliverytime'] = $formattedTimeDate;
return $this;
}
public function addCustomData(string $customName, $data): self
{
$this->message['v:'.$customName] = json_encode($data);
return $this;
}
public function addCustomParameter(string $parameterName, $data): self
{
if (isset($this->message[$parameterName])) {
$this->message[$parameterName][] = $data;
} else {
$this->message[$parameterName] = [$data];
}
return $this;
}
public function setMessage(array $message): self
{
$this->message = $message;
return $this;
}
public function getMessage(): array
{
return $this->message;
}
}

84
src/Message/README.md Normal file
View file

@ -0,0 +1,84 @@
Mailgun - Messages
==================
This is the Mailgun PHP *Message* utilities.
The below assumes you've already installed the Mailgun PHP SDK in to your
project. If not, go back to the master README for instructions.
There are two utilities included, `MessageBuilder` and `BatchMessage`.
* `MessageBuilder`: Allows you to build a message object by calling methods for
each MIME attribute.
* `BatchMessage`: Extends `MessageBuilder` and allows you to iterate through
recipients from a list. Messages will fire after the 1,000th recipient has been
added.
Usage - Message Builder
-----------------------
Here's how to use Message Builder to build your Message.
```php
# Next, instantiate a Message Builder object from the SDK.
$builder = new MessageBuilder();
# Define the from address.
$builder->setFromAddress("me@example.com", array("first"=>"PHP", "last" => "SDK"));
# Define a to recipient.
$builder->addToRecipient("john.doe@example.com", array("first" => "John", "last" => "Doe"));
# Define a cc recipient.
$builder->addCcRecipient("sally.doe@example.com", array("full_name" => "Sally Doe"));
# Define the subject.
$builder->setSubject("A message from the PHP SDK using Message Builder!");
# Define the body of the message.
$builder->setTextBody("This is the text body of the message!");
# Other Optional Parameters.
$builder->addCampaignId("My-Awesome-Campaign");
$builder->addCustomHeader("Customer-Id", "12345");
$builder->addAttachment("@/tron.jpg");
$builder->setDeliveryTime("tomorrow 8:00AM", "PST");
$builder->setClickTracking(true);
# Finally, send the message.
$mg = Mailgun::create('key-example');
$domain = ;
$mg->messages()->send("example.com", $builder->getMessage());
```
Usage - Batch Message
---------------------
Here's how to use Batch Message to easily handle batch sending jobs.
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
# Next, instantiate a Message Builder object from the SDK, pass in your sending domain.
$batchMessage = $mg->messages()->getBatchMessage("example.com");
# Define the from address.
$batchMessage->setFromAddress("me@example.com", array("first"=>"PHP", "last" => "SDK"));
# Define the subject.
$batchMessage->setSubject("A Batch Message from the PHP SDK!");
# Define the body of the message.
$batchMessage->setTextBody("This is the text body of the message!");
# Next, let's add a few recipients to the batch job.
$batchMessage->addToRecipient("john.doe@example.com", array("first" => "John", "last" => "Doe"));
$batchMessage->addToRecipient("sally.doe@example.com", array("first" => "Sally", "last" => "Doe"));
$batchMessage->addToRecipient("mike.jones@example.com", array("first" => "Mike", "last" => "Jones"));
...
// After 1,000 recipients, Batch Message will automatically post your message to the messages endpoint.
// Call finalize() to send any remaining recipients still in the buffer.
$batchMessage->finalize();
$messageIds = $batchMessage->getMessageIds();
```
More Documentation
------------------
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
for more information.

Some files were not shown because too many files have changed in this diff Show more