From 9fb0cb9f26cb6a95c297b4a3ba53e73b2d839c83 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:59:02 +0100 Subject: [PATCH 1/6] Add Subscription Topics and topic fields Adds subscriptionTopics() (list and get) on the general client, and the topic fields on campaigns, contacts, contact imports, suppressions, email log events and webhooks. Decisions: - Topics are token-scoped like marketing stats, so the client takes no account id - Contact topic entries are a ContactSubscriptionTopic DTO with all three keys, since the API requires domain_id on writes - subscription_topics and subscription_topic_id are sent only when set: the API rejects a null topic, and validates the key whenever it is present - include_topic_unsubscriptions goes out as the string "true", since http_build_query sends 1, which the API ignores - A campaigns webhook needs event_types and takes no sending stream, as the API validates - A 5xx JSON body's errors join the HttpServerException message, so a contact saved without its topics names the contact to update Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + examples/README.md | 1 + examples/contacts/all.php | 79 ++++- examples/email-campaigns/all.php | 31 +- examples/sending/email-logs.php | 10 + examples/sending/suppressions.php | 9 + examples/subscription-topics/all.php | 65 ++++ examples/webhooks/all.php | 25 ++ src/Api/AbstractApi.php | 5 +- src/Api/General/Contact.php | 6 + src/Api/General/SubscriptionTopic.php | 67 ++++ src/Api/Sending/EmailLogs.php | 5 +- src/Api/Sending/Suppression.php | 2 + .../Contact/ContactSubscriptionTopic.php | 81 +++++ src/DTO/Request/Contact/CreateContact.php | 39 +- src/DTO/Request/Contact/ImportContact.php | 37 +- src/DTO/Request/Contact/UpdateContact.php | 32 +- .../EmailCampaign/CreateEmailCampaign.php | 4 + .../EmailCampaign/UpdateEmailCampaign.php | 6 + .../Request/Suppression/CreateSuppression.php | 3 +- src/DTO/Request/Suppression/Suppression.php | 5 + .../Suppression/SuppressionsFilter.php | 10 + src/DTO/Request/Webhook/CreateWebhook.php | 18 +- src/DTO/Request/Webhook/Webhook.php | 6 + src/Exception/HttpServerException.php | 42 +++ src/MailtrapGeneralClient.php | 24 +- tests/Api/AbstractApiTest.php | 54 +++ tests/Api/General/ContactTest.php | 332 +++++++++++++++++- tests/Api/General/EmailCampaignTest.php | 53 ++- tests/Api/General/SubscriptionTopicTest.php | 208 +++++++++++ tests/Api/Sending/EmailLogsTest.php | 37 ++ tests/Api/Sending/SuppressionTest.php | 59 +++- tests/Api/Sending/WebhookTest.php | 86 ++++- 33 files changed, 1399 insertions(+), 43 deletions(-) create mode 100644 examples/subscription-topics/all.php create mode 100644 src/Api/General/SubscriptionTopic.php create mode 100644 src/DTO/Request/Contact/ContactSubscriptionTopic.php create mode 100644 tests/Api/General/SubscriptionTopicTest.php diff --git a/README.md b/README.md index 091195d..c5ddd6c 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,7 @@ Contact management: Email marketing: - Email campaigns CRUD, listing, lifecycle & stats – [`email-campaigns/all.php`](examples/email-campaigns/all.php) - Email marketing stats (campaigns & automations) – [`marketing-stats/all.php`](examples/marketing-stats/all.php) +- Subscription topics (list & get) – [`subscription-topics/all.php`](examples/subscription-topics/all.php) General API: - Templates CRUD, paginated (experimental) – [`templates/templates.php`](examples/templates/templates.php) diff --git a/examples/README.md b/examples/README.md index cbb6817..f4d6553 100644 --- a/examples/README.md +++ b/examples/README.md @@ -61,6 +61,7 @@ Central index of runnable example scripts demonstrating Mailtrap PHP SDK feature | Custom fields CRUD | [`contact-fields/all.php`](contact-fields/all.php) | | Email campaigns CRUD + list + lifecycle + stats | [`email-campaigns/all.php`](email-campaigns/all.php) | | Email marketing stats (campaigns + automations) | [`marketing-stats/all.php`](marketing-stats/all.php) | +| Subscription topics list + get | [`subscription-topics/all.php`](subscription-topics/all.php) | ### Templates & Domains diff --git a/examples/contacts/all.php b/examples/contacts/all.php index 178d302..b4b58ea 100644 --- a/examples/contacts/all.php +++ b/examples/contacts/all.php @@ -1,22 +1,50 @@ contacts($accountId); +$generalClient = new MailtrapGeneralClient($config); +$contacts = $generalClient->contacts($accountId); + +/** + * A contact's subscription topic status is set per topic and domain: take the account's first + * topic, and the domain it covers (the first domain when the topic covers all of them). + * Accounts without Subscription Topics get 403 here, and the examples below leave topics out. + * + * GET https://mailtrap.io/api/subscription_topics + * GET https://mailtrap.io/api/accounts/{account_id}/domains + */ +$subscriptionTopicId = null; +$subscriptionTopicDomainId = null; +try { + $topic = ResponseHelper::toArray($generalClient->subscriptionTopics()->getSubscriptionTopics())['data'][0] ?? null; + + if ($topic !== null) { + $subscriptionTopicId = $topic['id']; + $subscriptionTopicDomainId = $topic['domain_id'] ?? ResponseHelper::toArray( + (new MailtrapSendingClient($config))->domains($accountId)->getDomains() + )['data'][0]['id']; + } +} catch (Exception $e) { + echo 'Subscription topics are left out: ', $e->getMessage(), PHP_EOL; +} /** * Get contact + * With Subscription Topics, `data.subscription_topics` lists the contact's status per topic and + * domain; it is null when the statuses can't be read right now, and absent without topics. * * GET https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email} */ @@ -44,7 +72,14 @@ CreateContact::init( 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith'], // Fields - [1, 2] // List IDs to which the contact will be added + [1, 2], // List IDs to which the contact will be added + $subscriptionTopicId === null ? null : [ // Subscription topic statuses (null leaves them out) + ContactSubscriptionTopic::init( + $subscriptionTopicId, + $subscriptionTopicDomainId, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] ) ); @@ -92,6 +127,37 @@ } +/** + * Update only a contact's subscription topic statuses: the topic and domain pairs left out keep + * their status. A 503 means the contact was saved but its topic statuses were not; the exception + * message names the contact to send them again to. + * + * PATCH https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email} + */ +try { + if ($subscriptionTopicId !== null) { + $response = $contacts->updateContactByEmail( + 'john.smith@example.com', + UpdateContact::init( + email: 'john.smith@example.com', + subscriptionTopics: [ + ContactSubscriptionTopic::init( + $subscriptionTopicId, + $subscriptionTopicDomainId, + ContactSubscriptionTopic::STATUS_SUBSCRIBED // resubscribe + ), + ] + ) + ); + + // print the response body (array) + var_dump(ResponseHelper::toArray($response)); + } +} catch (Exception $e) { + echo 'Caught exception: ', $e->getMessage(), PHP_EOL; +} + + /** * Delete contact * @@ -125,7 +191,14 @@ email: 'customer1@example.com', fields: ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111], listIdsIncluded: [1, 2], - listIdsExcluded: [4, 5] + listIdsExcluded: [4, 5], + subscriptionTopics: $subscriptionTopicId === null ? null : [ + ContactSubscriptionTopic::init( + $subscriptionTopicId, + $subscriptionTopicDomainId, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] ), new ImportContact( email: 'customer2@example.com', diff --git a/examples/email-campaigns/all.php b/examples/email-campaigns/all.php index f89178d..05fc508 100644 --- a/examples/email-campaigns/all.php +++ b/examples/email-campaigns/all.php @@ -14,8 +14,10 @@ require __DIR__ . '/../../vendor/autoload.php'; $accountId = (int) $_ENV['MAILTRAP_ACCOUNT_ID']; +$domainId = (int) $_ENV['MAILTRAP_DOMAIN_ID']; // set this environment variable with your domain ID $config = new Config($_ENV['MAILTRAP_API_KEY']); // your API token from https://mailtrap.io/api-tokens -$emailCampaigns = (new MailtrapGeneralClient($config))->emailCampaigns($accountId); +$generalClient = new MailtrapGeneralClient($config); +$emailCampaigns = $generalClient->emailCampaigns($accountId); /** * Get a paginated list of email campaigns (newest first). @@ -33,16 +35,38 @@ echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } +/** + * Pick the subscription topic the campaign is sent for: the first one that covers the campaign's + * domain (a topic with no `domain_id` covers every domain). Accounts without Subscription Topics + * get 403 here, and the campaign below is created without a topic. + * + * GET https://mailtrap.io/api/subscription_topics + */ +$subscriptionTopicId = null; +try { + $topics = ResponseHelper::toArray($generalClient->subscriptionTopics()->getSubscriptionTopics()); + + foreach ($topics['data'] as $topic) { + if ($topic['domain_id'] === null || $topic['domain_id'] === $domainId) { + $subscriptionTopicId = $topic['id']; + break; + } + } +} catch (Exception $e) { + echo 'No subscription topic for the campaign: ', $e->getMessage(), PHP_EOL; +} + /** * Create a new email campaign in the `draft` state (wrapped in `data`). * `name`, `domain_id`, `from_local_part` and a template `subject` are required. + * `subscription_topic_id` is left out when null; the response returns it, null without a topic. * * POST https://mailtrap.io/api/email_campaigns */ try { $response = $emailCampaigns->createEmailCampaign(new CreateEmailCampaign( name: 'Spring Sale', - domainId: (int) $_ENV['MAILTRAP_DOMAIN_ID'], // set this environment variable with your domain ID + domainId: $domainId, fromLocalPart: 'news', templateAttributes: new TemplateAttributes(subject: 'Spring is here — 30% off'), fromDisplayName: 'Acme Marketing', @@ -51,6 +75,7 @@ localPart: 'support', domain: 'acme.com', ), + subscriptionTopicId: $subscriptionTopicId, )); $emailCampaign = ResponseHelper::toArray($response); @@ -221,7 +246,7 @@ try { $throwaway = ResponseHelper::toArray($emailCampaigns->createEmailCampaign(new CreateEmailCampaign( name: 'Draft to delete', - domainId: (int) $_ENV['MAILTRAP_DOMAIN_ID'], + domainId: $domainId, fromLocalPart: 'news', templateAttributes: new TemplateAttributes(subject: 'Draft to delete') ))); diff --git a/examples/sending/email-logs.php b/examples/sending/email-logs.php index 78e1269..9e88dc9 100644 --- a/examples/sending/email-logs.php +++ b/examples/sending/email-logs.php @@ -73,6 +73,16 @@ echo "Status: " . $message['status'] . PHP_EOL; echo "Subject: " . ($message['subject'] ?? '') . PHP_EOL; echo "Events: " . count($message['events'] ?? []) . PHP_EOL; + + // Each event's `details` depend on its `event_type`; the API may add types, so don't fail on + // one you don't know. The subscription topic events carry the topic's ID. + foreach ($message['events'] ?? [] as $event) { + $line = " - " . $event['event_type'] . " at " . $event['created_at']; + if (in_array($event['event_type'], ['topic_unsubscribe', 'topic_resubscribe'], true)) { + $line .= " (subscription topic " . ($event['details']['subscription_topic_id'] ?? 'unknown') . ")"; + } + echo $line . PHP_EOL; + } } else { echo "No messages in the list." . PHP_EOL; } diff --git a/examples/sending/suppressions.php b/examples/sending/suppressions.php index a75afbe..1a7e562 100644 --- a/examples/sending/suppressions.php +++ b/examples/sending/suppressions.php @@ -36,6 +36,13 @@ ) ); + // OR include contacts' subscription topic unsubscriptions: rows of type + // Suppression::TYPE_TOPIC_UNSUBSCRIPTION with their `subscription_topic_id`. + // Accounts without Subscription Topics have no such rows. + $response = $mailtrapSuppression->getSuppressions( + new SuppressionsFilter(includeTopicUnsubscriptions: true) + ); + // Print the response body (array) var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { @@ -68,6 +75,8 @@ /** * Delete Suppression by ID. + * Topic unsubscription rows can't be deleted (404): resubscribe the contact to the topic in a + * contact update instead (see contacts/all.php). * * DELETE https://mailtrap.io/api/accounts/{account_id}/suppressions/{suppression_id} */ diff --git a/examples/subscription-topics/all.php b/examples/subscription-topics/all.php new file mode 100644 index 0000000..383f685 --- /dev/null +++ b/examples/subscription-topics/all.php @@ -0,0 +1,65 @@ +subscriptionTopics(); + +/** + * Get a paginated list of subscription topics; deleted topics are left out. + * Optional: $perPage (max 100, default 50) and $token (page number). + * + * The response is wrapped in `{ data: [...], pagination }`. A topic's `domain_id` is null when + * it covers every domain of the account. + * + * GET https://mailtrap.io/api/subscription_topics + */ +try { + $topics = ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 50)); + + var_dump($topics); + + // pass `pagination.next_token` with the same $perPage to get the next page + $nextToken = $topics['pagination']['next_token'] ?? null; + if ($nextToken !== null) { + var_dump(ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 50, token: $nextToken))); + } +} catch (HttpClientException $e) { + echo $e->getCode() === 403 + ? 'Subscription Topics are not available for this account.' + : 'Caught exception: ' . $e->getMessage(); + echo PHP_EOL; + + exit(1); +} catch (Exception $e) { + echo 'Caught exception: ', $e->getMessage(), PHP_EOL; + + exit(1); +} + +/** + * Get a subscription topic by ID (wrapped in `data`). A deleted topic is returned too, with + * `deleted_at` set. + * + * GET https://mailtrap.io/api/subscription_topics/{subscription_topic_id} + */ +try { + $subscriptionTopicId = $topics['data'][0]['id'] ?? null; + + if ($subscriptionTopicId !== null) { + $response = $subscriptionTopics->getSubscriptionTopic($subscriptionTopicId); + + var_dump(ResponseHelper::toArray($response)); + } else { + echo 'No subscription topics yet: create one in Mailtrap first.', PHP_EOL; + } +} catch (Exception $e) { + echo 'Caught exception: ', $e->getMessage(), PHP_EOL; +} diff --git a/examples/webhooks/all.php b/examples/webhooks/all.php index 1cf618b..e23b048 100644 --- a/examples/webhooks/all.php +++ b/examples/webhooks/all.php @@ -65,6 +65,31 @@ echo 'Caught exception: ', $e->getMessage(), "\n"; } +/** + * Create a campaigns webhook that also reports subscription topic preference changes. + * Campaigns webhooks require `event_types` and take no sending stream. + * `subscription_preferences_update` is available on campaigns webhooks and Bulk stream + * email_sending webhooks only. + * + * POST https://mailtrap.io/api/accounts/{account_id}/webhooks + */ +try { + $response = $webhooks->createWebhook(new CreateWebhook( + url: 'https://example.com/mailtrap/campaign-webhooks', + webhookType: Webhook::TYPE_CAMPAIGNS, + eventTypes: [ + Webhook::EVENT_DELIVERY, + Webhook::EVENT_UNSUBSCRIBE, + Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE, + ], + payloadFormat: Webhook::PAYLOAD_FORMAT_JSON, + )); + + var_dump(ResponseHelper::toArray($response)); +} catch (Exception $e) { + echo 'Caught exception: ', $e->getMessage(), "\n"; +} + /** * Update an existing webhook. * Only `url`, `active`, `payload_format`, and `event_types` are mutable. diff --git a/src/Api/AbstractApi.php b/src/Api/AbstractApi.php index 893c1a7..53df6cb 100644 --- a/src/Api/AbstractApi.php +++ b/src/Api/AbstractApi.php @@ -95,10 +95,7 @@ protected function handleResponse(ResponseInterface $response): ResponseInterfac case $statusCode >= 400 && $statusCode < 500: throw HttpClientException::createFromResponse($response); case $statusCode >= 500: - throw new HttpServerException( - sprintf('Internal Server Error. HTTP response code ("%d") received from the API server. Retry later or contact support.', $statusCode), - $statusCode - ); + throw HttpServerException::createFromResponse($response); default: throw new HttpException( sprintf('An unexpected error occurred. HTTP response code ("%d") received.', $statusCode), diff --git a/src/Api/General/Contact.php b/src/Api/General/Contact.php index 30c9e9e..533beb5 100644 --- a/src/Api/General/Contact.php +++ b/src/Api/General/Contact.php @@ -16,6 +16,12 @@ /** * Class Contact + * + * With Subscription Topics, a contact's get, create and update responses carry + * `data.subscription_topics`: its status per topic and domain, null when the statuses can't be + * read (retry later), and absent for an account without topics. A create or update with + * subscription topics that fails with `503` saved the contact but not its topic statuses: the + * HttpServerException message names the contact to send them again to, in an update. */ class Contact extends AbstractApi implements GeneralInterface { diff --git a/src/Api/General/SubscriptionTopic.php b/src/Api/General/SubscriptionTopic.php new file mode 100644 index 0000000..7323e4b --- /dev/null +++ b/src/Api/General/SubscriptionTopic.php @@ -0,0 +1,67 @@ +handleResponse( + $this->httpGet($this->getBasePath(), $parameters) + ); + } + + /** + * Get a subscription topic by ID, wrapped in `data`. A deleted topic is returned too, + * with `deleted_at` set. + * + * @param int $subscriptionTopicId + * @return ResponseInterface + */ + public function getSubscriptionTopic(int $subscriptionTopicId): ResponseInterface + { + return $this->handleResponse( + $this->httpGet($this->getBasePath() . '/' . $subscriptionTopicId) + ); + } + + private function getBasePath(): string + { + return sprintf('%s/api/subscription_topics', $this->getHost()); + } +} diff --git a/src/Api/Sending/EmailLogs.php b/src/Api/Sending/EmailLogs.php index b323e36..40b1771 100644 --- a/src/Api/Sending/EmailLogs.php +++ b/src/Api/Sending/EmailLogs.php @@ -59,7 +59,10 @@ public function getList(array|EmailLogsListFilters $filters = [], ?string $searc * Get a single email log message by ID. * * Returns message details including events. Message must belong to the account and a domain - * the token can access. + * the token can access. Each event is `{ event_type, created_at, details }`, and `details` + * depends on `event_type`: the subscription topic events `topic_unsubscribe` and + * `topic_resubscribe` carry `{ web_ip_address, subscription_topic_id }`. The API may add event + * types, so don't fail on one you don't know. * * @param string $sendingMessageId Message UUID (sending_message_id). * @return ResponseInterface 200 with SendingMessage body (message_id, status, subject, from, to, sent_at, events, etc.) diff --git a/src/Api/Sending/Suppression.php b/src/Api/Sending/Suppression.php index 221586e..4626c6f 100644 --- a/src/Api/Sending/Suppression.php +++ b/src/Api/Sending/Suppression.php @@ -60,6 +60,8 @@ public function createSuppression(CreateSuppression $suppression): ResponseInter /** * Delete a suppression by ID (UUID). * Mailtrap will no longer prevent sending to this email unless it's recorded in suppressions again. + * A topic unsubscription row can't be deleted (`404`): resubscribe the contact to the topic in a + * contact update instead. * * @param string $suppressionId * @return ResponseInterface diff --git a/src/DTO/Request/Contact/ContactSubscriptionTopic.php b/src/DTO/Request/Contact/ContactSubscriptionTopic.php new file mode 100644 index 0000000..9e3fb4b --- /dev/null +++ b/src/DTO/Request/Contact/ContactSubscriptionTopic.php @@ -0,0 +1,81 @@ +> + */ + public static function listToArray(array $subscriptionTopics): array + { + return array_map( + static function ($subscriptionTopic): array { + if (!$subscriptionTopic instanceof self) { + throw new InvalidArgumentException( + 'Each subscription topic must be an instance of ContactSubscriptionTopic.' + ); + } + + return $subscriptionTopic->toArray(); + }, + array_values($subscriptionTopics) + ); + } + + public function getSubscriptionTopicId(): int + { + return $this->subscriptionTopicId; + } + + public function getDomainId(): int + { + return $this->domainId; + } + + public function getStatus(): string + { + return $this->status; + } + + public function toArray(): array + { + return [ + 'subscription_topic_id' => $this->getSubscriptionTopicId(), + 'domain_id' => $this->getDomainId(), + 'status' => $this->getStatus(), + ]; + } +} diff --git a/src/DTO/Request/Contact/CreateContact.php b/src/DTO/Request/Contact/CreateContact.php index 7b69fb4..4e1cd2c 100644 --- a/src/DTO/Request/Contact/CreateContact.php +++ b/src/DTO/Request/Contact/CreateContact.php @@ -9,16 +9,31 @@ */ final class CreateContact implements ContactInterface { + /** + * @param string $email + * @param array $fields + * @param int[] $listIds + * @param ContactSubscriptionTopic[]|null $subscriptionTopics Topic statuses per domain; null leaves them out + * of the request. Accounts without topics reject them + */ public function __construct( private string $email, private array $fields = [], - private array $listIds = [] + private array $listIds = [], + private ?array $subscriptionTopics = null ) { } - public static function init(string $email, array $fields = [], array $listIds = []): self - { - return new self($email, $fields, $listIds); + /** + * @param ContactSubscriptionTopic[]|null $subscriptionTopics + */ + public static function init( + string $email, + array $fields = [], + array $listIds = [], + ?array $subscriptionTopics = null + ): self { + return new self($email, $fields, $listIds, $subscriptionTopics); } public function getEmail(): string @@ -36,12 +51,26 @@ public function getListIds(): array return $this->listIds; } + /** + * @return ContactSubscriptionTopic[]|null + */ + public function getSubscriptionTopics(): ?array + { + return $this->subscriptionTopics; + } + public function toArray(): array { - return [ + $payload = [ 'email' => $this->getEmail(), 'fields' => $this->getFields(), 'list_ids' => $this->getListIds(), ]; + + if ($this->getSubscriptionTopics() !== null) { + $payload['subscription_topics'] = ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()); + } + + return $payload; } } diff --git a/src/DTO/Request/Contact/ImportContact.php b/src/DTO/Request/Contact/ImportContact.php index 3122886..35ab870 100644 --- a/src/DTO/Request/Contact/ImportContact.php +++ b/src/DTO/Request/Contact/ImportContact.php @@ -9,21 +9,36 @@ */ final class ImportContact implements ContactInterface { + /** + * @param string $email + * @param array $fields + * @param int[] $listIdsIncluded + * @param int[] $listIdsExcluded + * @param ContactSubscriptionTopic[]|null $subscriptionTopics Topic statuses per domain; the topic and domain + * pairs left out keep their status, and null leaves + * them all out. Accounts without topics reject the + * whole import + */ public function __construct( private string $email, private array $fields = [], private array $listIdsIncluded = [], - private array $listIdsExcluded = [] + private array $listIdsExcluded = [], + private ?array $subscriptionTopics = null ) { } + /** + * @param ContactSubscriptionTopic[]|null $subscriptionTopics + */ public static function init( string $email, array $fields = [], array $listIdsIncluded = [], - array $listIdsExcluded = [] + array $listIdsExcluded = [], + ?array $subscriptionTopics = null ): self { - return new self($email, $fields, $listIdsIncluded, $listIdsExcluded); + return new self($email, $fields, $listIdsIncluded, $listIdsExcluded, $subscriptionTopics); } public function getEmail(): string @@ -46,13 +61,27 @@ public function getListIdsExcluded(): array return $this->listIdsExcluded; } + /** + * @return ContactSubscriptionTopic[]|null + */ + public function getSubscriptionTopics(): ?array + { + return $this->subscriptionTopics; + } + public function toArray(): array { - return [ + $payload = [ 'email' => $this->getEmail(), 'fields' => $this->getFields(), 'list_ids_included' => $this->getListIdsIncluded(), 'list_ids_excluded' => $this->getListIdsExcluded(), ]; + + if ($this->getSubscriptionTopics() !== null) { + $payload['subscription_topics'] = ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()); + } + + return $payload; } } diff --git a/src/DTO/Request/Contact/UpdateContact.php b/src/DTO/Request/Contact/UpdateContact.php index 0272502..f7c2225 100644 --- a/src/DTO/Request/Contact/UpdateContact.php +++ b/src/DTO/Request/Contact/UpdateContact.php @@ -9,23 +9,38 @@ */ final class UpdateContact implements ContactInterface { + /** + * @param string $email + * @param array $fields + * @param int[] $listIdsIncluded + * @param int[] $listIdsExcluded + * @param bool|null $unsubscribed + * @param ContactSubscriptionTopic[]|null $subscriptionTopics Topic statuses per domain; the topic and domain + * pairs left out keep their status, and null leaves + * them all out. Accounts without topics reject them + */ public function __construct( private string $email, private array $fields = [], private array $listIdsIncluded = [], private array $listIdsExcluded = [], - private ?bool $unsubscribed = null + private ?bool $unsubscribed = null, + private ?array $subscriptionTopics = null ) { } + /** + * @param ContactSubscriptionTopic[]|null $subscriptionTopics + */ public static function init( string $email, array $fields = [], array $listIdsIncluded = [], array $listIdsExcluded = [], - ?bool $unsubscribed = null + ?bool $unsubscribed = null, + ?array $subscriptionTopics = null ): self { - return new self($email, $fields, $listIdsIncluded, $listIdsExcluded, $unsubscribed); + return new self($email, $fields, $listIdsIncluded, $listIdsExcluded, $unsubscribed, $subscriptionTopics); } public function getEmail(): string @@ -53,6 +68,14 @@ public function getUnsubscribed(): ?bool return $this->unsubscribed; } + /** + * @return ContactSubscriptionTopic[]|null + */ + public function getSubscriptionTopics(): ?array + { + return $this->subscriptionTopics; + } + public function toArray(): array { return array_filter( @@ -62,6 +85,9 @@ public function toArray(): array 'list_ids_included' => $this->getListIdsIncluded(), 'list_ids_excluded' => $this->getListIdsExcluded(), 'unsubscribed' => $this->getUnsubscribed(), + 'subscription_topics' => $this->getSubscriptionTopics() === null + ? null + : ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()), ], fn($value) => $value !== null ); diff --git a/src/DTO/Request/EmailCampaign/CreateEmailCampaign.php b/src/DTO/Request/EmailCampaign/CreateEmailCampaign.php index fabe192..e4116af 100644 --- a/src/DTO/Request/EmailCampaign/CreateEmailCampaign.php +++ b/src/DTO/Request/EmailCampaign/CreateEmailCampaign.php @@ -24,6 +24,8 @@ final class CreateEmailCampaign implements EmailCampaignInterface * @param array|null $deliveryOptions Delivery throttling options (`emails_per_hour`), applies to `gradual` mode * @param int[]|null $contactListIds IDs of contact lists to send to (the full set — `[]` clears it) * @param int[]|null $contactSegmentIds IDs of contact segments to send to (the full set — `[]` clears it) + * @param int|null $subscriptionTopicId ID of the subscription topic the campaign is sent for, as returned + * by the Subscription Topics API. Accounts without topics ignore it */ public function __construct( private string $name, @@ -36,6 +38,7 @@ public function __construct( private ?array $deliveryOptions = null, private ?array $contactListIds = null, private ?array $contactSegmentIds = null, + private ?int $subscriptionTopicId = null, ) { } @@ -53,6 +56,7 @@ public function toArray(): array 'delivery_options' => $this->deliveryOptions, 'contact_list_ids' => $this->contactListIds, 'contact_segment_ids' => $this->contactSegmentIds, + 'subscription_topic_id' => $this->subscriptionTopicId, ], fn ($value) => $value !== null ); diff --git a/src/DTO/Request/EmailCampaign/UpdateEmailCampaign.php b/src/DTO/Request/EmailCampaign/UpdateEmailCampaign.php index 5d42f3c..fb583b4 100644 --- a/src/DTO/Request/EmailCampaign/UpdateEmailCampaign.php +++ b/src/DTO/Request/EmailCampaign/UpdateEmailCampaign.php @@ -25,6 +25,10 @@ final class UpdateEmailCampaign implements EmailCampaignInterface * @param TemplateAttributes|null $templateAttributes Template attributes; edited in place, partial * @param int[]|null $contactListIds IDs of contact lists to send to (the full set — `[]` clears it) * @param int[]|null $contactSegmentIds IDs of contact segments to send to (the full set — `[]` clears it) + * @param int|null $subscriptionTopicId ID of the subscription topic the campaign is sent for, as + * returned by the Subscription Topics API. A campaign can + * change its topic but not drop it. Accounts without topics + * ignore it */ public function __construct( private ?string $name = null, @@ -37,6 +41,7 @@ public function __construct( private ?TemplateAttributes $templateAttributes = null, private ?array $contactListIds = null, private ?array $contactSegmentIds = null, + private ?int $subscriptionTopicId = null, ) { } @@ -54,6 +59,7 @@ public function toArray(): array 'template_attributes' => $this->templateAttributes?->toArray(), 'contact_list_ids' => $this->contactListIds, 'contact_segment_ids' => $this->contactSegmentIds, + 'subscription_topic_id' => $this->subscriptionTopicId, ], fn ($value) => $value !== null ); diff --git a/src/DTO/Request/Suppression/CreateSuppression.php b/src/DTO/Request/Suppression/CreateSuppression.php index 3a367e5..db5c58f 100644 --- a/src/DTO/Request/Suppression/CreateSuppression.php +++ b/src/DTO/Request/Suppression/CreateSuppression.php @@ -15,7 +15,8 @@ final class CreateSuppression implements SuppressionInterface * @param string $email Email address to suppress * @param int $domainId ID of the domain to suppress this email for * @param string $sendingStream One of Suppression::SENDING_STREAM_* - * @param string|null $type One of Suppression::TYPE_*. The API defaults to + * @param string|null $type One of Suppression::TYPE_* except TYPE_TOPIC_UNSUBSCRIPTION, + * which the API doesn't create. The API defaults to * "manual import" when omitted. */ public function __construct( diff --git a/src/DTO/Request/Suppression/Suppression.php b/src/DTO/Request/Suppression/Suppression.php index adae240..20a48d3 100644 --- a/src/DTO/Request/Suppression/Suppression.php +++ b/src/DTO/Request/Suppression/Suppression.php @@ -16,6 +16,11 @@ final class Suppression public const TYPE_UNSUBSCRIPTION = 'unsubscription'; public const TYPE_SPAM_COMPLAINT = 'spam complaint'; public const TYPE_MANUAL_IMPORT = 'manual import'; + /** + * A contact's unsubscription from a subscription topic. Returned only by the suppressions list, + * with SuppressionsFilter::$includeTopicUnsubscriptions; it can't be created or deleted here. + */ + public const TYPE_TOPIC_UNSUBSCRIPTION = 'topic unsubscription'; private function __construct() { diff --git a/src/DTO/Request/Suppression/SuppressionsFilter.php b/src/DTO/Request/Suppression/SuppressionsFilter.php index 270b5ff..5bb2ef0 100644 --- a/src/DTO/Request/Suppression/SuppressionsFilter.php +++ b/src/DTO/Request/Suppression/SuppressionsFilter.php @@ -16,12 +16,17 @@ final class SuppressionsFilter implements SuppressionInterface * @param string|null $startTime Only suppressions created at or after this ISO 8601 timestamp * @param string|null $endTime Only suppressions created at or before this ISO 8601 timestamp * @param string|null $lastId Cursor: returns suppressions after this UUID + * @param bool|null $includeTopicUnsubscriptions Also return contacts' subscription topic + * unsubscriptions, as Suppression::TYPE_TOPIC_UNSUBSCRIPTION rows + * with their `subscription_topic_id`. Needs a token that can read + * contacts; accounts without topics have no such rows */ public function __construct( private ?string $email = null, private ?string $startTime = null, private ?string $endTime = null, private ?string $lastId = null, + private ?bool $includeTopicUnsubscriptions = null, ) { } @@ -45,6 +50,11 @@ public function toArray(): array $payload['last_id'] = $this->lastId; } + if ($this->includeTopicUnsubscriptions === true) { + // http_build_query would send 1; the API opts in only on the string "true" + $payload['include_topic_unsubscriptions'] = 'true'; + } + return $payload; } } diff --git a/src/DTO/Request/Webhook/CreateWebhook.php b/src/DTO/Request/Webhook/CreateWebhook.php index f24f322..0b6ca8a 100644 --- a/src/DTO/Request/Webhook/CreateWebhook.php +++ b/src/DTO/Request/Webhook/CreateWebhook.php @@ -14,9 +14,10 @@ final class CreateWebhook implements WebhookInterface /** * @param string $url Webhook destination URL * @param string $webhookType One of Webhook::TYPE_* - * @param string[] $eventTypes Subset of Webhook::EVENT_* (required for email_sending) + * @param string[] $eventTypes Subset of Webhook::EVENT_* (required for email_sending and campaigns) * @param string|null $payloadFormat One of Webhook::PAYLOAD_FORMAT_* - * @param string|null $sendingStream One of Webhook::SENDING_STREAM_* (required for email_sending) + * @param string|null $sendingStream One of Webhook::SENDING_STREAM_* (required for email_sending, + * not allowed for campaigns) * @param int|null $domainId Scope to a specific domain id (null = all account domains) * @param bool|null $active Defaults to true on the server side * @param int|null $inboundInboxId Scope an inbound_receiving webhook to a specific @@ -36,13 +37,15 @@ public function __construct( Webhook::TYPE_EMAIL_SENDING, Webhook::TYPE_AUDIT_LOG, Webhook::TYPE_INBOUND_RECEIVING, + Webhook::TYPE_CAMPAIGNS, ]; if (!in_array($webhookType, $allowedTypes, true)) { throw new InvalidArgumentException(sprintf( - '"webhookType" must be one of "%s", "%s", or "%s", "%s" given', + '"webhookType" must be one of "%s", "%s", "%s", or "%s", "%s" given', Webhook::TYPE_EMAIL_SENDING, Webhook::TYPE_AUDIT_LOG, Webhook::TYPE_INBOUND_RECEIVING, + Webhook::TYPE_CAMPAIGNS, $webhookType )); } @@ -55,6 +58,15 @@ public function __construct( throw new InvalidArgumentException('"sendingStream" is required for email_sending webhooks'); } } + + if ($webhookType === Webhook::TYPE_CAMPAIGNS) { + if ($eventTypes === []) { + throw new InvalidArgumentException('"eventTypes" is required for campaigns webhooks'); + } + if ($sendingStream !== null) { + throw new InvalidArgumentException('"sendingStream" is not allowed for campaigns webhooks'); + } + } } public function toArray(): array diff --git a/src/DTO/Request/Webhook/Webhook.php b/src/DTO/Request/Webhook/Webhook.php index ee06807..56804bd 100644 --- a/src/DTO/Request/Webhook/Webhook.php +++ b/src/DTO/Request/Webhook/Webhook.php @@ -12,6 +12,7 @@ final class Webhook public const TYPE_EMAIL_SENDING = 'email_sending'; public const TYPE_AUDIT_LOG = 'audit_log'; public const TYPE_INBOUND_RECEIVING = 'inbound_receiving'; + public const TYPE_CAMPAIGNS = 'campaigns'; public const PAYLOAD_FORMAT_JSON = 'json'; public const PAYLOAD_FORMAT_JSONLINES = 'jsonlines'; @@ -28,6 +29,11 @@ final class Webhook public const EVENT_SPAM_COMPLAINT = 'spam_complaint'; public const EVENT_CLICK = 'click'; public const EVENT_REJECT = 'reject'; + /** + * A recipient changed their subscription topic preferences. Only for Bulk stream + * email_sending webhooks and campaigns webhooks; the API rejects it on others. + */ + public const EVENT_SUBSCRIPTION_PREFERENCES_UPDATE = 'subscription_preferences_update'; private function __construct() { diff --git a/src/Exception/HttpServerException.php b/src/Exception/HttpServerException.php index 915934e..7c1c401 100644 --- a/src/Exception/HttpServerException.php +++ b/src/Exception/HttpServerException.php @@ -4,9 +4,51 @@ namespace Mailtrap\Exception; +use JsonException; +use Psr\Http\Message\ResponseInterface; + /** * Class HttpServerException */ class HttpServerException extends HttpException { + /** + * Appends the `errors` of a JSON body, such as the contact named by a contact create or update + * that saved the contact but not its subscription topics, to the generic server error message. + */ + public static function createFromResponse(ResponseInterface $response): HttpServerException + { + $statusCode = $response->getStatusCode(); + $errorMsg = sprintf( + 'Internal Server Error. HTTP response code ("%d") received from the API server. Retry later or contact support.', + $statusCode + ); + + $errors = self::getResponseErrors($response); + if ($errors !== '') { + $errorMsg .= ' Errors: ' . $errors; + } + + return new self($errorMsg, $statusCode); + } + + /** + * The body's `errors` as text, or '' when the body isn't JSON or has none (a proxy's HTML page, say). + */ + private static function getResponseErrors(ResponseInterface $response): string + { + try { + $body = json_decode($response->getBody()->__toString(), true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return ''; + } + + $errors = is_array($body) ? $body['errors'] ?? null : null; + + return match (true) { + is_string($errors) => trim($errors), + is_array($errors) => trim(HttpClientException::getErrorMsg($errors)), + default => '', + }; + } } diff --git a/src/MailtrapGeneralClient.php b/src/MailtrapGeneralClient.php index 27ea45d..522d34d 100644 --- a/src/MailtrapGeneralClient.php +++ b/src/MailtrapGeneralClient.php @@ -5,17 +5,18 @@ namespace Mailtrap; /** - * @method Api\General\Account accounts() - * @method Api\General\User users(int $accountId) - * @method Api\General\Permission permissions(int $accountId) - * @method Api\General\Contact contacts(int $accountId) - * @method Api\General\EmailTemplate emailTemplates(int $accountId) - * @method Api\General\Template templates(int $accountId) - * @method Api\General\Billing billing(int $accountId) - * @method Api\General\ApiToken apiTokens(int $accountId) - * @method Api\General\Organization organization(int $organizationId) - * @method Api\General\EmailCampaign emailCampaigns(int $accountId) - * @method Api\General\MarketingStats marketingStats() + * @method Api\General\Account accounts() + * @method Api\General\User users(int $accountId) + * @method Api\General\Permission permissions(int $accountId) + * @method Api\General\Contact contacts(int $accountId) + * @method Api\General\EmailTemplate emailTemplates(int $accountId) + * @method Api\General\Template templates(int $accountId) + * @method Api\General\Billing billing(int $accountId) + * @method Api\General\ApiToken apiTokens(int $accountId) + * @method Api\General\Organization organization(int $organizationId) + * @method Api\General\EmailCampaign emailCampaigns(int $accountId) + * @method Api\General\MarketingStats marketingStats() + * @method Api\General\SubscriptionTopic subscriptionTopics() * * Class MailtrapGeneralClient */ @@ -33,5 +34,6 @@ final class MailtrapGeneralClient extends AbstractMailtrapClient 'organization' => Api\General\Organization::class, 'emailCampaigns' => Api\General\EmailCampaign::class, 'marketingStats' => Api\General\MarketingStats::class, + 'subscriptionTopics' => Api\General\SubscriptionTopic::class, ]; } diff --git a/tests/Api/AbstractApiTest.php b/tests/Api/AbstractApiTest.php index 374abbc..e97175e 100644 --- a/tests/Api/AbstractApiTest.php +++ b/tests/Api/AbstractApiTest.php @@ -6,7 +6,9 @@ use Mailtrap\Api\AbstractApi; use Mailtrap\Api\Sending\EmailLogs; +use Mailtrap\Exception\HttpServerException; use Mailtrap\Tests\MailtrapTestCase; +use Nyholm\Psr7\Response; use ReflectionClass; /** @@ -56,6 +58,58 @@ public function testNormalizeArrayParamsUsesBracketNotationForListParams(): void ); } + /** + * A server error's JSON `errors` reaches the exception message; any other body leaves the generic message as is. + * + * @dataProvider serverErrorProvider + */ + public function testHandleResponseAddsServerErrorBodyToMessage(Response $response, string $expectedMessage): void + { + try { + $this->handleResponse($response); + $this->fail('HttpServerException expected'); + } catch (HttpServerException $e) { + $this->assertSame($expectedMessage, $e->getMessage()); + $this->assertSame($response->getStatusCode(), $e->getCode()); + } + } + + public function serverErrorProvider(): iterable + { + $genericMessage = 'Internal Server Error. HTTP response code ("%d") received from the API server. ' + . 'Retry later or contact support.'; + $json = ['Content-Type' => 'application/json']; + + yield 'string errors' => [ + new Response(503, $json, json_encode(['errors' => 'Send them again in an update of contact 42.'])), + sprintf($genericMessage, 503) . ' Errors: Send them again in an update of contact 42.', + ]; + yield 'array errors' => [ + new Response(500, $json, json_encode(['errors' => ['base' => ['something broke']]])), + sprintf($genericMessage, 500) . ' Errors: base -> something broke.', + ]; + yield 'html body' => [ + new Response(502, ['Content-Type' => 'text/html'], 'Bad Gateway'), + sprintf($genericMessage, 502), + ]; + yield 'empty body' => [new Response(504), sprintf($genericMessage, 504)]; + yield 'json without errors' => [ + new Response(500, $json, json_encode(['error' => 'x'])), + sprintf($genericMessage, 500), + ]; + yield 'json scalar' => [new Response(500, $json, json_encode('oops')), sprintf($genericMessage, 500)]; + } + + private function handleResponse(Response $response): void + { + $method = (new ReflectionClass(AbstractApi::class))->getMethod('handleResponse'); + if (PHP_VERSION_ID < 80100) { + $method->setAccessible(true); + } + + $method->invoke(new EmailLogs($this->getConfigMock(), self::FAKE_ACCOUNT_ID), $response); + } + private function normalizeArrayParams(array $params): string { $method = (new ReflectionClass(AbstractApi::class))->getMethod('normalizeArrayParams'); diff --git a/tests/Api/General/ContactTest.php b/tests/Api/General/ContactTest.php index 5c3e38b..b87d08c 100644 --- a/tests/Api/General/ContactTest.php +++ b/tests/Api/General/ContactTest.php @@ -7,9 +7,11 @@ use Mailtrap\DTO\Request\Contact\CreateContact; use Mailtrap\DTO\Request\Contact\CreateContactEvent; use Mailtrap\DTO\Request\Contact\ContactExportFilter; +use Mailtrap\DTO\Request\Contact\ContactSubscriptionTopic; use Mailtrap\DTO\Request\Contact\UpdateContact; use Mailtrap\DTO\Request\Contact\ImportContact; use Mailtrap\Exception\HttpClientException; +use Mailtrap\Exception\HttpServerException; use Mailtrap\Exception\InvalidArgumentException; use Mailtrap\Tests\MailtrapTestCase; use Nyholm\Psr7\Response; @@ -22,6 +24,9 @@ */ class ContactTest extends MailtrapTestCase { + private const FAKE_SUBSCRIPTION_TOPIC_ID = 17; + private const FAKE_DOMAIN_ID = 3938; + /** * @var Contact|null */ @@ -205,6 +210,56 @@ public function testGetContactById(): void $this->assertInstanceOf(Response::class, $response); $this->assertArrayHasKey('email', $responseData); $this->assertEquals('test@example.com', $responseData['email']); + $this->assertEquals( + [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => ContactSubscriptionTopic::STATUS_SUBSCRIBED, + ], + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => 3939, + 'status' => ContactSubscriptionTopic::STATUS_UNSUBSCRIBED, + ], + ], + $responseData['subscription_topics'] + ); + } + + public function testGetContactWithUnreadableSubscriptionTopics(): void + { + $contactId = '019706a8-9612-77be-8586-4f26816b467a'; + $contactData = $this->getExpectedContactData(); + // null when the topic statuses can't be read: retry rather than take them as subscribed + $contactData['data']['subscription_topics'] = null; + + $this->contact->expects($this->once()) + ->method('httpGet') + ->with(AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/contacts/' . $contactId) + ->willReturn(new Response(200, ['Content-Type' => 'application/json'], json_encode($contactData))); + + $responseData = ResponseHelper::toArray($this->contact->getContactById($contactId))['data']; + + $this->assertArrayHasKey('subscription_topics', $responseData); + $this->assertNull($responseData['subscription_topics']); + } + + public function testGetContactForAccountWithoutSubscriptionTopics(): void + { + $contactId = '019706a8-9612-77be-8586-4f26816b467a'; + $contactData = $this->getExpectedContactData(); + unset($contactData['data']['subscription_topics']); + + $this->contact->expects($this->once()) + ->method('httpGet') + ->with(AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/contacts/' . $contactId) + ->willReturn(new Response(200, ['Content-Type' => 'application/json'], json_encode($contactData))); + + $responseData = ResponseHelper::toArray($this->contact->getContactById($contactId))['data']; + + $this->assertEquals('test@example.com', $responseData['email']); + $this->assertArrayNotHasKey('subscription_topics', $responseData); } public function testGetContactByEmail(): void @@ -250,6 +305,144 @@ public function testCreateContact(): void $this->assertEquals($fakeEmail, $responseData['email']); } + public function testCreateContactWithSubscriptionTopics(): void + { + $contactDTO = CreateContact::init( + 'test@example.com', + ['first_name' => 'John'], + [1, 2], + [ + ContactSubscriptionTopic::init( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] + ); + + $this->contact->expects($this->once()) + ->method('httpPost') + ->with( + AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/contacts', + [], + [ + 'contact' => [ + 'email' => 'test@example.com', + 'fields' => ['first_name' => 'John'], + 'list_ids' => [1, 2], + 'subscription_topics' => [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => 'unsubscribed', + ], + ], + ], + ] + ) + ->willReturn( + new Response(201, ['Content-Type' => 'application/json'], json_encode($this->getExpectedContactData())) + ); + + $responseData = ResponseHelper::toArray($this->contact->createContact($contactDTO))['data']; + + $this->assertCount(2, $responseData['subscription_topics']); + } + + public function testCreateContactExcludesUnsetSubscriptionTopics(): void + { + $payload = (new CreateContact('test@example.com', ['first_name' => 'John'], [1, 2]))->toArray(); + + $this->assertArrayNotHasKey('subscription_topics', $payload); + } + + public function testCreateContactSendsSubscriptionTopicsAsList(): void + { + $subscriptionTopic = new ContactSubscriptionTopic( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_SUBSCRIBED + ); + + // keyed entries would otherwise encode as a JSON object, which the API ignores + $payload = (new CreateContact( + email: 'test@example.com', + subscriptionTopics: ['newsletter' => $subscriptionTopic] + ))->toArray(); + + $this->assertSame( + '[{"subscription_topic_id":17,"domain_id":3938,"status":"subscribed"}]', + json_encode($payload['subscription_topics']) + ); + } + + public function testCreateContactRejectsInvalidSubscriptionTopic(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Each subscription topic must be an instance of ContactSubscriptionTopic.'); + + (new CreateContact( + email: 'test@example.com', + subscriptionTopics: [['subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID]] + ))->toArray(); + } + + public function testCreateContactWithSubscriptionTopicsFailsForAccountWithoutTopics(): void + { + $contactDTO = new CreateContact( + email: 'test@example.com', + subscriptionTopics: [ + new ContactSubscriptionTopic( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_SUBSCRIBED + ), + ] + ); + + $this->contact->expects($this->once()) + ->method('httpPost') + ->willReturn( + new Response( + 422, + ['Content-Type' => 'application/json'], + json_encode(['errors' => ['subscription_topics' => ['are not available for this account']]]) + ) + ); + + $this->expectException(HttpClientException::class); + $this->expectExceptionMessage('Errors: subscription_topics -> are not available for this account.'); + + $this->contact->createContact($contactDTO); + } + + public function testCreateContactReportsUnsavedSubscriptionTopics(): void + { + $contactId = '019706a8-9612-77be-8586-4f26816b467a'; + $message = 'The contact was saved, but its subscription topic preferences were not. ' + . 'Send them again in an update of contact ' . $contactId . '.'; + + $this->contact->expects($this->once()) + ->method('httpPost') + ->willReturn(new Response(503, ['Content-Type' => 'application/json'], json_encode(['errors' => $message]))); + + $this->expectException(HttpServerException::class); + $this->expectExceptionCode(503); + $this->expectExceptionMessage('Internal Server Error. HTTP response code ("503") received from the API server. ' + . 'Retry later or contact support. Errors: ' . $message); + + $this->contact->createContact(new CreateContact( + email: 'test@example.com', + subscriptionTopics: [ + new ContactSubscriptionTopic( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] + )); + } + public function testUpdateContactById(): void { $contactId = '019706a8-9612-77be-8586-4f26816b467a'; @@ -330,6 +523,92 @@ public function testUpdateContactExcludesNullUnsubscribed(): void $this->assertEquals('unsubscribed', $responseData['status']); } + public function testUpdateContactExcludesUnsetSubscriptionTopics(): void + { + $payload = (new UpdateContact('test@example.com', ['last_name' => 'Smith'], [3], [1, 2], true))->toArray(); + + $this->assertArrayNotHasKey('subscription_topics', $payload); + } + + public function testUpdateContactWithSubscriptionTopicsOnly(): void + { + $contactId = '019706a8-9612-77be-8586-4f26816b467a'; + // the topic and domain pairs left out keep their status + $contactDTO = UpdateContact::init( + email: 'test@example.com', + subscriptionTopics: [ + ContactSubscriptionTopic::init( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_SUBSCRIBED + ), + ] + ); + + $this->contact->expects($this->once()) + ->method('httpPatch') + ->with( + AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/contacts/' . $contactId, + [], + [ + 'contact' => [ + 'email' => 'test@example.com', + 'fields' => [], + 'list_ids_included' => [], + 'list_ids_excluded' => [], + 'subscription_topics' => [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => 'subscribed', + ], + ], + ], + ] + ) + ->willReturn( + new Response(200, ['Content-Type' => 'application/json'], json_encode($this->getExpectedUpdateContactData())) + ); + + $responseData = ResponseHelper::toArray($this->contact->updateContactById($contactId, $contactDTO))['data']; + + $this->assertEquals( + [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => ContactSubscriptionTopic::STATUS_SUBSCRIBED, + ], + ], + $responseData['subscription_topics'] + ); + } + + public function testUpdateContactReportsUnsavedSubscriptionTopics(): void + { + $contactId = '019706a8-9612-77be-8586-4f26816b467a'; + $message = 'The contact was saved, but its subscription topic preferences were not. ' + . 'Send them again in an update of contact ' . $contactId . '.'; + + $this->contact->expects($this->once()) + ->method('httpPatch') + ->willReturn(new Response(503, ['Content-Type' => 'application/json'], json_encode(['errors' => $message]))); + + $this->expectException(HttpServerException::class); + $this->expectExceptionMessage('Errors: ' . $message); + + $this->contact->updateContactById($contactId, new UpdateContact( + email: 'test@example.com', + subscriptionTopics: [ + new ContactSubscriptionTopic( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] + )); + } + public function testDeleteContactById(): void { $contactId = '019706a8-9612-77be-8586-4f26816b467a'; @@ -507,7 +786,14 @@ public function testImportContacts(): void email: 'customer1@example.com', fields: ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111], listIdsIncluded: [1, 2, 3], - listIdsExcluded: [4, 5, 6] + listIdsExcluded: [4, 5, 6], + subscriptionTopics: [ + new ContactSubscriptionTopic( + self::FAKE_SUBSCRIPTION_TOPIC_ID, + self::FAKE_DOMAIN_ID, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ), + ] ), new ImportContact( email: 'customer2@example.com', @@ -527,7 +813,30 @@ public function testImportContacts(): void ->with( AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/contacts/imports', [], - ['contacts' => array_map(fn(ImportContact $contact) => $contact->toArray(), $contacts)] + [ + 'contacts' => [ + [ + 'email' => 'customer1@example.com', + 'fields' => ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111], + 'list_ids_included' => [1, 2, 3], + 'list_ids_excluded' => [4, 5, 6], + 'subscription_topics' => [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => 'unsubscribed', + ], + ], + ], + // a contact without topics sends no subscription_topics + [ + 'email' => 'customer2@example.com', + 'fields' => ['first_name' => 'Joe', 'last_name' => 'Doe', 'zip_code' => 22222], + 'list_ids_included' => [1], + 'list_ids_excluded' => [4], + ], + ], + ] ) ->willReturn(new Response(201, ['Content-Type' => 'application/json'], json_encode($expectedResponse))); @@ -1109,6 +1418,18 @@ private function getExpectedContactData(): array 'first_name' => 'John', 'last_name' => null, ], + 'subscription_topics' => [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => 'subscribed', + ], + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => 3939, + 'status' => 'unsubscribed', + ], + ], ], ]; } @@ -1127,6 +1448,13 @@ private function getExpectedUpdateContactData(): array 'first_name' => 'John', 'last_name' => 'Smith', ], + 'subscription_topics' => [ + [ + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, + 'domain_id' => self::FAKE_DOMAIN_ID, + 'status' => 'subscribed', + ], + ], ], 'action' => 'updated', ]; diff --git a/tests/Api/General/EmailCampaignTest.php b/tests/Api/General/EmailCampaignTest.php index 4f1941e..ee68207 100644 --- a/tests/Api/General/EmailCampaignTest.php +++ b/tests/Api/General/EmailCampaignTest.php @@ -26,6 +26,7 @@ class EmailCampaignTest extends MailtrapTestCase { private const BASE_PATH = AbstractApi::DEFAULT_HOST . '/api/email_campaigns'; private const FAKE_DOMAIN_ID = 4321; + private const FAKE_SUBSCRIPTION_TOPIC_ID = 17; private ?EmailCampaign $emailCampaign; @@ -129,6 +130,30 @@ public function testGetEmailCampaign(): void $this->assertEquals(self::FAKE_DOMAIN_ID, $responseData['data']['domain_id']); $this->assertEquals([55, 56], $responseData['data']['contact_list_ids']); $this->assertEquals([12], $responseData['data']['contact_segment_ids']); + $this->assertEquals(self::FAKE_SUBSCRIPTION_TOPIC_ID, $responseData['data']['subscription_topic_id']); + } + + public function testGetEmailCampaignWithoutSubscriptionTopic(): void + { + $emailCampaignId = 4567; + + $this->emailCampaign->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH . '/' . $emailCampaignId) + ->willReturn( + new Response( + 200, + ['Content-Type' => 'application/json'], + json_encode(['data' => $this->getExpectedEmailCampaignResponse(subscriptionTopicId: null)]) + ) + ); + + $response = $this->emailCampaign->getEmailCampaign($emailCampaignId); + $responseData = ResponseHelper::toArray($response); + + // campaigns without a topic, and every campaign of an account without topics, return null + $this->assertArrayHasKey('subscription_topic_id', $responseData['data']); + $this->assertNull($responseData['data']['subscription_topic_id']); } public function testGetEmailCampaignFailsWithNotFoundError(): void @@ -201,6 +226,20 @@ public function testCreateEmailCampaignSerializesFlatBody(): void $this->assertEquals(['emails_per_hour' => 1000], $payload['delivery_options']); $this->assertEquals([55, 56], $payload['contact_list_ids']); $this->assertEquals([12], $payload['contact_segment_ids']); + $this->assertEquals(self::FAKE_SUBSCRIPTION_TOPIC_ID, $payload['subscription_topic_id']); + } + + public function testCreateEmailCampaignOmitsUnsetSubscriptionTopic(): void + { + // the API rejects a null topic, so an unset one is left out of the body + $payload = (new CreateEmailCampaign( + name: 'Spring Sale', + domainId: self::FAKE_DOMAIN_ID, + fromLocalPart: 'news', + templateAttributes: new TemplateAttributes(subject: 'Spring is here'), + ))->toArray(); + + $this->assertArrayNotHasKey('subscription_topic_id', $payload); } public function testCreateEmailCampaignFailsWithValidationErrors(): void @@ -272,11 +311,19 @@ public function testUpdateEmailCampaignSerializesProvidedAttributesOnly(): void 'delivery_options' => ['emails_per_hour' => 1000], 'template_attributes' => ['subject' => 'New subject'], 'contact_list_ids' => [55], + 'subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID, ], $payload ); } + public function testUpdateEmailCampaignWithSubscriptionTopicOnly(): void + { + $payload = (new UpdateEmailCampaign(subscriptionTopicId: self::FAKE_SUBSCRIPTION_TOPIC_ID))->toArray(); + + $this->assertEquals(['subscription_topic_id' => self::FAKE_SUBSCRIPTION_TOPIC_ID], $payload); + } + public function testUpdateEmailCampaignKeepsEmptyAudienceArrays(): void { // `[]` must survive serialization — it clears the audience, unlike an omitted field @@ -543,6 +590,7 @@ private function getCreateEmailCampaignDTO(): CreateEmailCampaign deliveryOptions: ['emails_per_hour' => 1000], contactListIds: [55, 56], contactSegmentIds: [12], + subscriptionTopicId: self::FAKE_SUBSCRIPTION_TOPIC_ID, ); } @@ -554,11 +602,13 @@ private function getUpdateEmailCampaignDTO(): UpdateEmailCampaign deliveryOptions: ['emails_per_hour' => 1000], templateAttributes: new TemplateAttributes(subject: 'New subject'), contactListIds: [55], + subscriptionTopicId: self::FAKE_SUBSCRIPTION_TOPIC_ID, ); } private function getExpectedEmailCampaignResponse( - string $currentState = EmailCampaignInterface::STATE_DRAFT + string $currentState = EmailCampaignInterface::STATE_DRAFT, + ?int $subscriptionTopicId = self::FAKE_SUBSCRIPTION_TOPIC_ID ): array { return [ 'id' => 4567, @@ -580,6 +630,7 @@ private function getExpectedEmailCampaignResponse( 'contact_segment_ids' => [12], 'delivery_mode' => 'rapid', 'delivery_options' => ['emails_per_hour' => null], + 'subscription_topic_id' => $subscriptionTopicId, 'template' => [ 'id' => 789, 'subject' => 'Spring is here — 30% off', diff --git a/tests/Api/General/SubscriptionTopicTest.php b/tests/Api/General/SubscriptionTopicTest.php new file mode 100644 index 0000000..a26ff16 --- /dev/null +++ b/tests/Api/General/SubscriptionTopicTest.php @@ -0,0 +1,208 @@ +subscriptionTopic = $this->getMockBuilder(SubscriptionTopic::class) + ->onlyMethods(['httpGet']) + ->setConstructorArgs([$this->getConfigMock()]) + ->getMock(); + } + + protected function tearDown(): void + { + $this->subscriptionTopic = null; + parent::tearDown(); + } + + public function testGetSubscriptionTopics(): void + { + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH, []) + ->willReturn( + new Response( + 200, + ['Content-Type' => 'application/json'], + json_encode([ + 'data' => [ + $this->getExpectedSubscriptionTopicResponse(), + $this->getExpectedSubscriptionTopicResponse(id: 13, name: 'Product updates', domainId: 3938), + ], + 'pagination' => $this->getExpectedPagination(), + ]) + ) + ); + + $response = $this->subscriptionTopic->getSubscriptionTopics(); + $responseData = ResponseHelper::toArray($response); + + $this->assertArrayHasKey('data', $responseData); + $this->assertArrayHasKey('pagination', $responseData); + $this->assertCount(2, $responseData['data']); + $this->assertSame(12, $responseData['data'][0]['id']); + // a topic without a domain covers every domain of the account + $this->assertNull($responseData['data'][0]['domain_id']); + $this->assertSame(3938, $responseData['data'][1]['domain_id']); + $this->assertSame(1, $responseData['pagination']['token']); + $this->assertSame(2, $responseData['pagination']['next_token']); + } + + public function testGetSubscriptionTopicsWithPagination(): void + { + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH, ['per_page' => 25, 'token' => 2]) + ->willReturn( + new Response( + 200, + ['Content-Type' => 'application/json'], + json_encode([ + 'data' => [$this->getExpectedSubscriptionTopicResponse()], + 'pagination' => $this->getExpectedPagination(), + ]) + ) + ); + + $response = $this->subscriptionTopic->getSubscriptionTopics(perPage: 25, token: 2); + $responseData = ResponseHelper::toArray($response); + + $this->assertCount(1, $responseData['data']); + } + + public function testGetSubscriptionTopicsFailsForAccountWithoutTopics(): void + { + // without Subscription Topics the API answers 403 with an empty body + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH, []) + ->willReturn(new Response(403)); + + $this->expectException(HttpClientException::class); + $this->expectExceptionCode(403); + $this->expectExceptionMessage('Forbidden.'); + + $this->subscriptionTopic->getSubscriptionTopics(); + } + + public function testGetSubscriptionTopic(): void + { + $subscriptionTopicId = 12; + + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH . '/' . $subscriptionTopicId) + ->willReturn( + new Response( + 200, + ['Content-Type' => 'application/json'], + json_encode(['data' => $this->getExpectedSubscriptionTopicResponse()]) + ) + ); + + $response = $this->subscriptionTopic->getSubscriptionTopic($subscriptionTopicId); + $responseData = ResponseHelper::toArray($response); + + $this->assertArrayHasKey('data', $responseData); + $this->assertSame($subscriptionTopicId, $responseData['data']['id']); + $this->assertSame('Newsletter', $responseData['data']['name']); + $this->assertNull($responseData['data']['deleted_at']); + } + + public function testGetDeletedSubscriptionTopic(): void + { + $subscriptionTopicId = 14; + + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH . '/' . $subscriptionTopicId) + ->willReturn( + new Response( + 200, + ['Content-Type' => 'application/json'], + json_encode([ + 'data' => $this->getExpectedSubscriptionTopicResponse( + id: $subscriptionTopicId, + name: 'Old offers', + deletedAt: '2026-06-01T12:00:00.000Z' + ), + ]) + ) + ); + + $response = $this->subscriptionTopic->getSubscriptionTopic($subscriptionTopicId); + $responseData = ResponseHelper::toArray($response); + + $this->assertSame($subscriptionTopicId, $responseData['data']['id']); + $this->assertSame('2026-06-01T12:00:00.000Z', $responseData['data']['deleted_at']); + } + + public function testGetSubscriptionTopicFailsWithNotFoundError(): void + { + $subscriptionTopicId = 999; + + $this->subscriptionTopic->expects($this->once()) + ->method('httpGet') + ->with(self::BASE_PATH . '/' . $subscriptionTopicId) + ->willReturn( + new Response(404, ['Content-Type' => 'application/json'], json_encode(['error' => 'Not Found'])) + ); + + $this->expectException(HttpClientException::class); + $this->expectExceptionMessage('The requested entity has not been found. Errors: Not Found.'); + + $this->subscriptionTopic->getSubscriptionTopic($subscriptionTopicId); + } + + private function getExpectedSubscriptionTopicResponse( + int $id = 12, + string $name = 'Newsletter', + ?int $domainId = null, + ?string $deletedAt = null + ): array { + return [ + 'id' => $id, + 'name' => $name, + 'description' => 'Monthly news and offers', + 'domain_id' => $domainId, + 'deleted_at' => $deletedAt, + 'created_at' => '2026-05-01T10:15:00.000Z', + 'updated_at' => '2026-05-02T09:00:00.000Z', + ]; + } + + private function getExpectedPagination(): array + { + return [ + 'token' => 1, + 'prev_token' => null, + 'next_token' => 2, + 'first_url' => 'https://mailtrap.io/api/subscription_topics?per_page=50&token=1', + 'prev_url' => null, + 'current_url' => 'https://mailtrap.io/api/subscription_topics?per_page=50&token=1', + 'next_url' => 'https://mailtrap.io/api/subscription_topics?per_page=50&token=2', + ]; + } +} diff --git a/tests/Api/Sending/EmailLogsTest.php b/tests/Api/Sending/EmailLogsTest.php index 5f25e2c..b620f35 100644 --- a/tests/Api/Sending/EmailLogsTest.php +++ b/tests/Api/Sending/EmailLogsTest.php @@ -167,6 +167,43 @@ public function testGetMessage(): void $this->assertArrayHasKey('events', $data); } + public function testGetMessageWithSubscriptionTopicAndUnknownEvents(): void + { + $messageId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'; + $body = $this->getMessageResponseBody(); + $body['events'] = [ + [ + 'event_type' => 'topic_unsubscribe', + 'created_at' => '2025-01-15T10:40:00Z', + 'details' => ['web_ip_address' => '198.51.100.50', 'subscription_topic_id' => 17], + ], + [ + 'event_type' => 'topic_resubscribe', + 'created_at' => '2025-01-15T10:45:00Z', + 'details' => ['web_ip_address' => null, 'subscription_topic_id' => 17], + ], + // an event type the SDK doesn't know yet comes back as is + [ + 'event_type' => 'future_event', + 'created_at' => '2025-01-15T10:50:00Z', + 'details' => ['anything' => ['nested' => true]], + ], + ]; + + $this->emailLogs->expects($this->once()) + ->method('httpGet') + ->with(AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/email_logs/' . $messageId, []) + ->willReturn(new Response(200, ['Content-Type' => 'application/json'], json_encode($body))); + + $events = ResponseHelper::toArray($this->emailLogs->getMessage($messageId))['events']; + + $this->assertSame('topic_unsubscribe', $events[0]['event_type']); + $this->assertSame(['web_ip_address' => '198.51.100.50', 'subscription_topic_id' => 17], $events[0]['details']); + $this->assertSame('topic_resubscribe', $events[1]['event_type']); + $this->assertSame(17, $events[1]['details']['subscription_topic_id']); + $this->assertSame(['anything' => ['nested' => true]], $events[2]['details']); + } + public function testGetMessageThrowsWhenSendingMessageIdIsEmpty(): void { $emailLogs = new EmailLogs($this->getConfigMock(), self::FAKE_ACCOUNT_ID); diff --git a/tests/Api/Sending/SuppressionTest.php b/tests/Api/Sending/SuppressionTest.php index 53f85be..f49cf3b 100644 --- a/tests/Api/Sending/SuppressionTest.php +++ b/tests/Api/Sending/SuppressionTest.php @@ -119,6 +119,7 @@ public function testGetSuppressionsWithFilter(): void 'start_time' => '2025-01-01T00:00:00Z', 'end_time' => '2025-12-31T23:59:59Z', 'last_id' => '25594eef-87e0-49c7-a647-cc316f9fdb42', + 'include_topic_unsubscriptions' => 'true', ] ) ->willReturn( @@ -130,13 +131,45 @@ public function testGetSuppressionsWithFilter(): void email: 'john@example.com', startTime: '2025-01-01T00:00:00Z', endTime: '2025-12-31T23:59:59Z', - lastId: '25594eef-87e0-49c7-a647-cc316f9fdb42' + lastId: '25594eef-87e0-49c7-a647-cc316f9fdb42', + includeTopicUnsubscriptions: true ) ); $this->assertSame(200, $response->getStatusCode()); } + public function testGetSuppressionsWithTopicUnsubscriptions(): void + { + $filter = new SuppressionsFilter(includeTopicUnsubscriptions: true); + + // the API opts in only on the literal string "true", not on 1 + $this->assertSame('include_topic_unsubscriptions=true', http_build_query($filter->toArray())); + + $this->suppression->expects($this->once()) + ->method('httpGet') + ->with( + AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/suppressions', + ['include_topic_unsubscriptions' => 'true'] + ) + ->willReturn( + new Response(200, ['Content-Type' => 'application/json'], $this->getExpectedTopicUnsubscriptionResponse()) + ); + + $responseData = ResponseHelper::toArray($this->suppression->getSuppressions($filter)); + + $this->assertSame(SuppressionDto::TYPE_TOPIC_UNSUBSCRIPTION, $responseData[1]['type']); + $this->assertSame(17, $responseData[1]['subscription_topic_id']); + $this->assertSame('example.com', $responseData[1]['domain_name']); + $this->assertNull($responseData[0]['subscription_topic_id']); + } + + public function testGetSuppressionsWithoutTopicUnsubscriptionsSendsNothing(): void + { + $this->assertSame([], (new SuppressionsFilter())->toArray()); + $this->assertSame([], (new SuppressionsFilter(includeTopicUnsubscriptions: false))->toArray()); + } + public function testGetSuppressionsWithFilterOmitsUnsetFields(): void { $this->suppression->expects($this->once()) @@ -229,6 +262,30 @@ private function getExpectedCreateResponse(): string ]); } + private function getExpectedTopicUnsubscriptionResponse(): string + { + return json_encode([ + [ + 'id' => '25594eef-87e0-49c7-a647-cc316f9fdb42', + 'type' => 'unsubscription', + 'created_at' => '2025-05-25T10:07:49Z', + 'email' => 'john@example.com', + 'sending_stream' => 'bulk', + 'domain_name' => 'example.com', + 'subscription_topic_id' => null, + ], + [ + 'id' => '7a1b4f0e-2c3d-4e5f-8a9b-0c1d2e3f4a5b', + 'type' => 'topic unsubscription', + 'created_at' => '2026-06-01T12:00:00Z', + 'email' => 'jane@example.com', + 'sending_stream' => 'bulk', + 'domain_name' => 'example.com', + 'subscription_topic_id' => 17, + ], + ]); + } + private function getExpectedResponse(string $email): string { return json_encode([ diff --git a/tests/Api/Sending/WebhookTest.php b/tests/Api/Sending/WebhookTest.php index b2788cb..ee3cc9f 100644 --- a/tests/Api/Sending/WebhookTest.php +++ b/tests/Api/Sending/WebhookTest.php @@ -196,7 +196,9 @@ public function testCreateWebhookFailsWithValidationError(): void public function testCreateWebhookRejectsUnknownWebhookType(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('"webhookType" must be one of "email_sending", "audit_log", or "inbound_receiving", "spam" given'); + $this->expectExceptionMessage( + '"webhookType" must be one of "email_sending", "audit_log", "inbound_receiving", or "campaigns", "spam" given' + ); new CreateWebhook( url: 'https://example.com/mailtrap/webhooks', @@ -228,6 +230,88 @@ public function testCreateWebhookRejectsEmailSendingWithoutSendingStream(): void ); } + public function testCreateCampaignsWebhook(): void + { + $createDto = new CreateWebhook( + url: 'https://example.com/mailtrap/webhooks', + webhookType: Webhook::TYPE_CAMPAIGNS, + eventTypes: [Webhook::EVENT_DELIVERY, Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE], + payloadFormat: Webhook::PAYLOAD_FORMAT_JSON, + domainId: 435, + ); + + $this->assertSame( + [ + 'url' => 'https://example.com/mailtrap/webhooks', + 'webhook_type' => 'campaigns', + 'event_types' => ['delivery', 'subscription_preferences_update'], + 'payload_format' => 'json', + 'domain_id' => 435, + ], + $createDto->toArray() + ); + } + + public function testCreateWebhookWithSubscriptionPreferencesUpdate(): void + { + $createDto = new CreateWebhook( + url: 'https://example.com/mailtrap/webhooks', + webhookType: Webhook::TYPE_EMAIL_SENDING, + eventTypes: [Webhook::EVENT_UNSUBSCRIBE, Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE], + sendingStream: Webhook::SENDING_STREAM_BULK, + ); + $webhookResponse = [ + 'sending_stream' => Webhook::SENDING_STREAM_BULK, + 'event_types' => [Webhook::EVENT_UNSUBSCRIBE, Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE], + ] + $this->getExpectedWebhookResponse(); + + $this->webhook->expects($this->once()) + ->method('httpPost') + ->with( + AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID . '/webhooks', + [], + [ + 'webhook' => [ + 'url' => 'https://example.com/mailtrap/webhooks', + 'webhook_type' => 'email_sending', + 'event_types' => ['unsubscribe', 'subscription_preferences_update'], + 'sending_stream' => 'bulk', + ], + ] + ) + ->willReturn( + new Response(200, ['Content-Type' => 'application/json'], json_encode(['data' => $webhookResponse])) + ); + + $responseData = ResponseHelper::toArray($this->webhook->createWebhook($createDto)); + + $this->assertContains(Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE, $responseData['data']['event_types']); + } + + public function testCreateCampaignsWebhookRejectsMissingEventTypes(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"eventTypes" is required for campaigns webhooks'); + + new CreateWebhook( + url: 'https://example.com/mailtrap/webhooks', + webhookType: Webhook::TYPE_CAMPAIGNS, + ); + } + + public function testCreateCampaignsWebhookRejectsSendingStream(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"sendingStream" is not allowed for campaigns webhooks'); + + new CreateWebhook( + url: 'https://example.com/mailtrap/webhooks', + webhookType: Webhook::TYPE_CAMPAIGNS, + eventTypes: [Webhook::EVENT_DELIVERY], + sendingStream: Webhook::SENDING_STREAM_BULK, + ); + } + public function testUpdateWebhook(): void { $webhookId = 1; From a220451645a88aeda05e6adba0fc1aa3e00ace48 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 06:19:48 +0100 Subject: [PATCH 2/6] Keep non-string values in server errors from crashing getErrorMsg accepts only strings and arrays, so a 5xx body with a number, boolean or null inside errors threw a TypeError instead of HttpServerException. They are now written out as JSON text first. Co-Authored-By: Claude Opus 5.5 --- src/Exception/HttpServerException.php | 9 +++++++++ tests/Api/AbstractApiTest.php | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/src/Exception/HttpServerException.php b/src/Exception/HttpServerException.php index 7c1c401..5a438fa 100644 --- a/src/Exception/HttpServerException.php +++ b/src/Exception/HttpServerException.php @@ -45,6 +45,15 @@ private static function getResponseErrors(ResponseInterface $response): string $errors = is_array($body) ? $body['errors'] ?? null : null; + if (is_array($errors)) { + // getErrorMsg takes only strings and arrays, so a number, boolean or null inside would be a TypeError + array_walk_recursive($errors, static function (mixed &$value): void { + if (!is_string($value)) { + $value = json_encode($value); + } + }); + } + return match (true) { is_string($errors) => trim($errors), is_array($errors) => trim(HttpClientException::getErrorMsg($errors)), diff --git a/tests/Api/AbstractApiTest.php b/tests/Api/AbstractApiTest.php index e97175e..6aa0e8b 100644 --- a/tests/Api/AbstractApiTest.php +++ b/tests/Api/AbstractApiTest.php @@ -88,6 +88,10 @@ public function serverErrorProvider(): iterable new Response(500, $json, json_encode(['errors' => ['base' => ['something broke']]])), sprintf($genericMessage, 500) . ' Errors: base -> something broke.', ]; + yield 'non-string values in errors' => [ + new Response(500, $json, json_encode(['errors' => ['contact_id' => 123, 'base' => null, 'flags' => [true]]])), + sprintf($genericMessage, 500) . ' Errors: contact_id -> 123. base -> null. flags -> true.', + ]; yield 'html body' => [ new Response(502, ['Content-Type' => 'text/html'], 'Bad Gateway'), sprintf($genericMessage, 502), From f02004b4e8be1e115f12fae66f9c389e66eae5df Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 06:23:46 +0100 Subject: [PATCH 3/6] Format non-string error values in getErrorMsg itself Moves the fix for numbers, booleans and nulls inside errors from HttpServerException into getErrorMsg, so 4xx bodies with them no longer throw a TypeError either. Its signature is unchanged. The server error cases are tested on the factory directly, the campaigns webhook checks share one eventTypes check, and the contacts example builds its topic entry once. Co-Authored-By: Claude Opus 5.5 --- examples/contacts/all.php | 26 ++++----- src/DTO/Request/Webhook/CreateWebhook.php | 22 +++----- src/Exception/HttpClientException.php | 3 +- src/Exception/HttpServerException.php | 9 ---- tests/Api/AbstractApiTest.php | 58 -------------------- tests/Exception/HttpServerExceptionTest.php | 60 +++++++++++++++++++++ 6 files changed, 80 insertions(+), 98 deletions(-) create mode 100644 tests/Exception/HttpServerExceptionTest.php diff --git a/examples/contacts/all.php b/examples/contacts/all.php index b4b58ea..580477d 100644 --- a/examples/contacts/all.php +++ b/examples/contacts/all.php @@ -28,14 +28,22 @@ */ $subscriptionTopicId = null; $subscriptionTopicDomainId = null; +$topicUnsubscription = null; // the contact unsubscribed from that topic on that domain try { - $topic = ResponseHelper::toArray($generalClient->subscriptionTopics()->getSubscriptionTopics())['data'][0] ?? null; + $topic = ResponseHelper::toArray( + $generalClient->subscriptionTopics()->getSubscriptionTopics(perPage: 1) + )['data'][0] ?? null; if ($topic !== null) { $subscriptionTopicId = $topic['id']; $subscriptionTopicDomainId = $topic['domain_id'] ?? ResponseHelper::toArray( (new MailtrapSendingClient($config))->domains($accountId)->getDomains() )['data'][0]['id']; + $topicUnsubscription = ContactSubscriptionTopic::init( + $subscriptionTopicId, + $subscriptionTopicDomainId, + ContactSubscriptionTopic::STATUS_UNSUBSCRIBED + ); } } catch (Exception $e) { echo 'Subscription topics are left out: ', $e->getMessage(), PHP_EOL; @@ -73,13 +81,7 @@ 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith'], // Fields [1, 2], // List IDs to which the contact will be added - $subscriptionTopicId === null ? null : [ // Subscription topic statuses (null leaves them out) - ContactSubscriptionTopic::init( - $subscriptionTopicId, - $subscriptionTopicDomainId, - ContactSubscriptionTopic::STATUS_UNSUBSCRIBED - ), - ] + $topicUnsubscription === null ? null : [$topicUnsubscription] // Subscription topic statuses (null leaves them out) ) ); @@ -192,13 +194,7 @@ fields: ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111], listIdsIncluded: [1, 2], listIdsExcluded: [4, 5], - subscriptionTopics: $subscriptionTopicId === null ? null : [ - ContactSubscriptionTopic::init( - $subscriptionTopicId, - $subscriptionTopicDomainId, - ContactSubscriptionTopic::STATUS_UNSUBSCRIBED - ), - ] + subscriptionTopics: $topicUnsubscription === null ? null : [$topicUnsubscription] ), new ImportContact( email: 'customer2@example.com', diff --git a/src/DTO/Request/Webhook/CreateWebhook.php b/src/DTO/Request/Webhook/CreateWebhook.php index 0b6ca8a..d55c0dc 100644 --- a/src/DTO/Request/Webhook/CreateWebhook.php +++ b/src/DTO/Request/Webhook/CreateWebhook.php @@ -50,22 +50,14 @@ public function __construct( )); } - if ($webhookType === Webhook::TYPE_EMAIL_SENDING) { - if ($eventTypes === []) { - throw new InvalidArgumentException('"eventTypes" is required for email_sending webhooks'); - } - if ($sendingStream === null) { - throw new InvalidArgumentException('"sendingStream" is required for email_sending webhooks'); - } + if ($eventTypes === [] && in_array($webhookType, [Webhook::TYPE_EMAIL_SENDING, Webhook::TYPE_CAMPAIGNS], true)) { + throw new InvalidArgumentException(sprintf('"eventTypes" is required for %s webhooks', $webhookType)); } - - if ($webhookType === Webhook::TYPE_CAMPAIGNS) { - if ($eventTypes === []) { - throw new InvalidArgumentException('"eventTypes" is required for campaigns webhooks'); - } - if ($sendingStream !== null) { - throw new InvalidArgumentException('"sendingStream" is not allowed for campaigns webhooks'); - } + if ($webhookType === Webhook::TYPE_EMAIL_SENDING && $sendingStream === null) { + throw new InvalidArgumentException('"sendingStream" is required for email_sending webhooks'); + } + if ($webhookType === Webhook::TYPE_CAMPAIGNS && $sendingStream !== null) { + throw new InvalidArgumentException('"sendingStream" is not allowed for campaigns webhooks'); } } diff --git a/src/Exception/HttpClientException.php b/src/Exception/HttpClientException.php index a4bf085..1bbc1c4 100644 --- a/src/Exception/HttpClientException.php +++ b/src/Exception/HttpClientException.php @@ -73,7 +73,8 @@ public static function getErrorMsg(array|string $errors): string $errorMsg .= $key . ' -> '; } - $errorMsg .= self::getErrorMsg($value); + // a number, boolean or null is written out as JSON + $errorMsg .= self::getErrorMsg(is_array($value) || is_string($value) ? $value : json_encode($value)); } } else { $errorMsg .= $errors . '. '; diff --git a/src/Exception/HttpServerException.php b/src/Exception/HttpServerException.php index 5a438fa..7c1c401 100644 --- a/src/Exception/HttpServerException.php +++ b/src/Exception/HttpServerException.php @@ -45,15 +45,6 @@ private static function getResponseErrors(ResponseInterface $response): string $errors = is_array($body) ? $body['errors'] ?? null : null; - if (is_array($errors)) { - // getErrorMsg takes only strings and arrays, so a number, boolean or null inside would be a TypeError - array_walk_recursive($errors, static function (mixed &$value): void { - if (!is_string($value)) { - $value = json_encode($value); - } - }); - } - return match (true) { is_string($errors) => trim($errors), is_array($errors) => trim(HttpClientException::getErrorMsg($errors)), diff --git a/tests/Api/AbstractApiTest.php b/tests/Api/AbstractApiTest.php index 6aa0e8b..374abbc 100644 --- a/tests/Api/AbstractApiTest.php +++ b/tests/Api/AbstractApiTest.php @@ -6,9 +6,7 @@ use Mailtrap\Api\AbstractApi; use Mailtrap\Api\Sending\EmailLogs; -use Mailtrap\Exception\HttpServerException; use Mailtrap\Tests\MailtrapTestCase; -use Nyholm\Psr7\Response; use ReflectionClass; /** @@ -58,62 +56,6 @@ public function testNormalizeArrayParamsUsesBracketNotationForListParams(): void ); } - /** - * A server error's JSON `errors` reaches the exception message; any other body leaves the generic message as is. - * - * @dataProvider serverErrorProvider - */ - public function testHandleResponseAddsServerErrorBodyToMessage(Response $response, string $expectedMessage): void - { - try { - $this->handleResponse($response); - $this->fail('HttpServerException expected'); - } catch (HttpServerException $e) { - $this->assertSame($expectedMessage, $e->getMessage()); - $this->assertSame($response->getStatusCode(), $e->getCode()); - } - } - - public function serverErrorProvider(): iterable - { - $genericMessage = 'Internal Server Error. HTTP response code ("%d") received from the API server. ' - . 'Retry later or contact support.'; - $json = ['Content-Type' => 'application/json']; - - yield 'string errors' => [ - new Response(503, $json, json_encode(['errors' => 'Send them again in an update of contact 42.'])), - sprintf($genericMessage, 503) . ' Errors: Send them again in an update of contact 42.', - ]; - yield 'array errors' => [ - new Response(500, $json, json_encode(['errors' => ['base' => ['something broke']]])), - sprintf($genericMessage, 500) . ' Errors: base -> something broke.', - ]; - yield 'non-string values in errors' => [ - new Response(500, $json, json_encode(['errors' => ['contact_id' => 123, 'base' => null, 'flags' => [true]]])), - sprintf($genericMessage, 500) . ' Errors: contact_id -> 123. base -> null. flags -> true.', - ]; - yield 'html body' => [ - new Response(502, ['Content-Type' => 'text/html'], 'Bad Gateway'), - sprintf($genericMessage, 502), - ]; - yield 'empty body' => [new Response(504), sprintf($genericMessage, 504)]; - yield 'json without errors' => [ - new Response(500, $json, json_encode(['error' => 'x'])), - sprintf($genericMessage, 500), - ]; - yield 'json scalar' => [new Response(500, $json, json_encode('oops')), sprintf($genericMessage, 500)]; - } - - private function handleResponse(Response $response): void - { - $method = (new ReflectionClass(AbstractApi::class))->getMethod('handleResponse'); - if (PHP_VERSION_ID < 80100) { - $method->setAccessible(true); - } - - $method->invoke(new EmailLogs($this->getConfigMock(), self::FAKE_ACCOUNT_ID), $response); - } - private function normalizeArrayParams(array $params): string { $method = (new ReflectionClass(AbstractApi::class))->getMethod('normalizeArrayParams'); diff --git a/tests/Exception/HttpServerExceptionTest.php b/tests/Exception/HttpServerExceptionTest.php new file mode 100644 index 0000000..4ca91d4 --- /dev/null +++ b/tests/Exception/HttpServerExceptionTest.php @@ -0,0 +1,60 @@ +assertSame($expectedMessage, $exception->getMessage()); + $this->assertSame($response->getStatusCode(), $exception->getCode()); + } + + public function serverErrorProvider(): iterable + { + $genericMessage = 'Internal Server Error. HTTP response code ("%d") received from the API server. ' + . 'Retry later or contact support.'; + $json = ['Content-Type' => 'application/json']; + + yield 'string errors' => [ + new Response(503, $json, json_encode(['errors' => 'Send them again in an update of contact 42.'])), + sprintf($genericMessage, 503) . ' Errors: Send them again in an update of contact 42.', + ]; + yield 'array errors' => [ + new Response(500, $json, json_encode(['errors' => ['base' => ['something broke']]])), + sprintf($genericMessage, 500) . ' Errors: base -> something broke.', + ]; + yield 'non-string values in errors' => [ + new Response(500, $json, json_encode(['errors' => ['contact_id' => 123, 'base' => null, 'flags' => [true]]])), + sprintf($genericMessage, 500) . ' Errors: contact_id -> 123. base -> null. flags -> true.', + ]; + yield 'html body' => [ + new Response(502, ['Content-Type' => 'text/html'], 'Bad Gateway'), + sprintf($genericMessage, 502), + ]; + yield 'empty body' => [new Response(504), sprintf($genericMessage, 504)]; + yield 'json without errors' => [ + new Response(500, $json, json_encode(['error' => 'x'])), + sprintf($genericMessage, 500), + ]; + yield 'json scalar' => [new Response(500, $json, json_encode('oops')), sprintf($genericMessage, 500)]; + } +} From 4edf10b345f627abd0961789fb27f94c1daba63a Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:38:17 +0100 Subject: [PATCH 4/6] Skip topic steps in examples when the lookup fails Decisions: - contacts: the resubscribe step checked only the topic id, so a failed domains lookup passed a null domain id and raised a TypeError that catch (Exception) misses; it now waits for the whole topic entry. - email campaigns: a topic for the campaign's domain may sit past the first page, so the lookup follows next_token until one matches. Co-Authored-By: Claude Opus 5.5 --- examples/contacts/all.php | 18 +++++++----------- examples/email-campaigns/all.php | 20 +++++++++++++------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/examples/contacts/all.php b/examples/contacts/all.php index 580477d..27d37ad 100644 --- a/examples/contacts/all.php +++ b/examples/contacts/all.php @@ -26,8 +26,6 @@ * GET https://mailtrap.io/api/subscription_topics * GET https://mailtrap.io/api/accounts/{account_id}/domains */ -$subscriptionTopicId = null; -$subscriptionTopicDomainId = null; $topicUnsubscription = null; // the contact unsubscribed from that topic on that domain try { $topic = ResponseHelper::toArray( @@ -35,13 +33,11 @@ )['data'][0] ?? null; if ($topic !== null) { - $subscriptionTopicId = $topic['id']; - $subscriptionTopicDomainId = $topic['domain_id'] ?? ResponseHelper::toArray( - (new MailtrapSendingClient($config))->domains($accountId)->getDomains() - )['data'][0]['id']; $topicUnsubscription = ContactSubscriptionTopic::init( - $subscriptionTopicId, - $subscriptionTopicDomainId, + $topic['id'], + $topic['domain_id'] ?? ResponseHelper::toArray( + (new MailtrapSendingClient($config))->domains($accountId)->getDomains() + )['data'][0]['id'], ContactSubscriptionTopic::STATUS_UNSUBSCRIBED ); } @@ -137,15 +133,15 @@ * PATCH https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email} */ try { - if ($subscriptionTopicId !== null) { + if ($topicUnsubscription !== null) { $response = $contacts->updateContactByEmail( 'john.smith@example.com', UpdateContact::init( email: 'john.smith@example.com', subscriptionTopics: [ ContactSubscriptionTopic::init( - $subscriptionTopicId, - $subscriptionTopicDomainId, + $topicUnsubscription->getSubscriptionTopicId(), + $topicUnsubscription->getDomainId(), ContactSubscriptionTopic::STATUS_SUBSCRIBED // resubscribe ), ] diff --git a/examples/email-campaigns/all.php b/examples/email-campaigns/all.php index 05fc508..48ec18c 100644 --- a/examples/email-campaigns/all.php +++ b/examples/email-campaigns/all.php @@ -44,14 +44,20 @@ */ $subscriptionTopicId = null; try { - $topics = ResponseHelper::toArray($generalClient->subscriptionTopics()->getSubscriptionTopics()); - - foreach ($topics['data'] as $topic) { - if ($topic['domain_id'] === null || $topic['domain_id'] === $domainId) { - $subscriptionTopicId = $topic['id']; - break; + $subscriptionTopics = $generalClient->subscriptionTopics(); + $token = null; + do { + $topics = ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 100, token: $token)); + + foreach ($topics['data'] as $topic) { + if ($topic['domain_id'] === null || $topic['domain_id'] === $domainId) { + $subscriptionTopicId = $topic['id']; + break; + } } - } + + $token = $topics['pagination']['next_token'] ?? null; // the next page, null after the last one + } while ($subscriptionTopicId === null && $token !== null); } catch (Exception $e) { echo 'No subscription topic for the campaign: ', $e->getMessage(), PHP_EOL; } From f84a226a310c736150ee5d2bf82355b5103c2ade Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:38:17 +0100 Subject: [PATCH 5/6] Share one null check for contact topics and list webhook types once Decisions: - ContactSubscriptionTopic::listToArray passes null through, so the three contact DTOs leave subscription_topics out the same way instead of in two hand-written shapes. - The webhook type error is built from the allowed list, as the inbound forward rule DTO does, so a new type needs one edit. - The subscription topics example needs one catch; the 403 check holds for any exception. Co-Authored-By: Claude Opus 5.5 --- examples/subscription-topics/all.php | 7 +----- .../Contact/ContactSubscriptionTopic.php | 11 +++++++--- src/DTO/Request/Contact/CreateContact.php | 20 ++++++++--------- src/DTO/Request/Contact/ImportContact.php | 22 +++++++++---------- src/DTO/Request/Contact/UpdateContact.php | 4 +--- src/DTO/Request/Webhook/CreateWebhook.php | 7 ++---- tests/Api/Sending/WebhookTest.php | 2 +- 7 files changed, 32 insertions(+), 41 deletions(-) diff --git a/examples/subscription-topics/all.php b/examples/subscription-topics/all.php index 383f685..295f926 100644 --- a/examples/subscription-topics/all.php +++ b/examples/subscription-topics/all.php @@ -3,7 +3,6 @@ declare(strict_types=1); use Mailtrap\Config; -use Mailtrap\Exception\HttpClientException; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; @@ -31,16 +30,12 @@ if ($nextToken !== null) { var_dump(ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 50, token: $nextToken))); } -} catch (HttpClientException $e) { +} catch (Exception $e) { echo $e->getCode() === 403 ? 'Subscription Topics are not available for this account.' : 'Caught exception: ' . $e->getMessage(); echo PHP_EOL; - exit(1); -} catch (Exception $e) { - echo 'Caught exception: ', $e->getMessage(), PHP_EOL; - exit(1); } diff --git a/src/DTO/Request/Contact/ContactSubscriptionTopic.php b/src/DTO/Request/Contact/ContactSubscriptionTopic.php index 9e3fb4b..936ed30 100644 --- a/src/DTO/Request/Contact/ContactSubscriptionTopic.php +++ b/src/DTO/Request/Contact/ContactSubscriptionTopic.php @@ -35,12 +35,17 @@ public static function init(int $subscriptionTopicId, int $domainId, string $sta /** * Serializes a contact's topic entries, so each DTO that carries them shares one check. + * Null stays null, for the DTOs to leave `subscription_topics` out of the request. * - * @param ContactSubscriptionTopic[] $subscriptionTopics - * @return array> + * @param ContactSubscriptionTopic[]|null $subscriptionTopics + * @return array>|null */ - public static function listToArray(array $subscriptionTopics): array + public static function listToArray(?array $subscriptionTopics): ?array { + if ($subscriptionTopics === null) { + return null; + } + return array_map( static function ($subscriptionTopic): array { if (!$subscriptionTopic instanceof self) { diff --git a/src/DTO/Request/Contact/CreateContact.php b/src/DTO/Request/Contact/CreateContact.php index 4e1cd2c..929c8bf 100644 --- a/src/DTO/Request/Contact/CreateContact.php +++ b/src/DTO/Request/Contact/CreateContact.php @@ -61,16 +61,14 @@ public function getSubscriptionTopics(): ?array public function toArray(): array { - $payload = [ - 'email' => $this->getEmail(), - 'fields' => $this->getFields(), - 'list_ids' => $this->getListIds(), - ]; - - if ($this->getSubscriptionTopics() !== null) { - $payload['subscription_topics'] = ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()); - } - - return $payload; + return array_filter( + [ + 'email' => $this->getEmail(), + 'fields' => $this->getFields(), + 'list_ids' => $this->getListIds(), + 'subscription_topics' => ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()), + ], + fn($value) => $value !== null + ); } } diff --git a/src/DTO/Request/Contact/ImportContact.php b/src/DTO/Request/Contact/ImportContact.php index 35ab870..264ebe0 100644 --- a/src/DTO/Request/Contact/ImportContact.php +++ b/src/DTO/Request/Contact/ImportContact.php @@ -71,17 +71,15 @@ public function getSubscriptionTopics(): ?array public function toArray(): array { - $payload = [ - 'email' => $this->getEmail(), - 'fields' => $this->getFields(), - 'list_ids_included' => $this->getListIdsIncluded(), - 'list_ids_excluded' => $this->getListIdsExcluded(), - ]; - - if ($this->getSubscriptionTopics() !== null) { - $payload['subscription_topics'] = ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()); - } - - return $payload; + return array_filter( + [ + 'email' => $this->getEmail(), + 'fields' => $this->getFields(), + 'list_ids_included' => $this->getListIdsIncluded(), + 'list_ids_excluded' => $this->getListIdsExcluded(), + 'subscription_topics' => ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()), + ], + fn($value) => $value !== null + ); } } diff --git a/src/DTO/Request/Contact/UpdateContact.php b/src/DTO/Request/Contact/UpdateContact.php index f7c2225..1d15ec7 100644 --- a/src/DTO/Request/Contact/UpdateContact.php +++ b/src/DTO/Request/Contact/UpdateContact.php @@ -85,9 +85,7 @@ public function toArray(): array 'list_ids_included' => $this->getListIdsIncluded(), 'list_ids_excluded' => $this->getListIdsExcluded(), 'unsubscribed' => $this->getUnsubscribed(), - 'subscription_topics' => $this->getSubscriptionTopics() === null - ? null - : ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()), + 'subscription_topics' => ContactSubscriptionTopic::listToArray($this->getSubscriptionTopics()), ], fn($value) => $value !== null ); diff --git a/src/DTO/Request/Webhook/CreateWebhook.php b/src/DTO/Request/Webhook/CreateWebhook.php index d55c0dc..0acbea5 100644 --- a/src/DTO/Request/Webhook/CreateWebhook.php +++ b/src/DTO/Request/Webhook/CreateWebhook.php @@ -41,11 +41,8 @@ public function __construct( ]; if (!in_array($webhookType, $allowedTypes, true)) { throw new InvalidArgumentException(sprintf( - '"webhookType" must be one of "%s", "%s", "%s", or "%s", "%s" given', - Webhook::TYPE_EMAIL_SENDING, - Webhook::TYPE_AUDIT_LOG, - Webhook::TYPE_INBOUND_RECEIVING, - Webhook::TYPE_CAMPAIGNS, + '"webhookType" must be one of "%s", "%s" given', + implode('", "', $allowedTypes), $webhookType )); } diff --git a/tests/Api/Sending/WebhookTest.php b/tests/Api/Sending/WebhookTest.php index ee3cc9f..6bf3645 100644 --- a/tests/Api/Sending/WebhookTest.php +++ b/tests/Api/Sending/WebhookTest.php @@ -197,7 +197,7 @@ public function testCreateWebhookRejectsUnknownWebhookType(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - '"webhookType" must be one of "email_sending", "audit_log", "inbound_receiving", or "campaigns", "spam" given' + '"webhookType" must be one of "email_sending", "audit_log", "inbound_receiving", "campaigns", "spam" given' ); new CreateWebhook( From 332cc756a3490117e9c8cadc992d986c154fbf33 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Wed, 25 Nov 2026 10:33:48 +0100 Subject: [PATCH 6/6] Drop the retry hint from server errors that say what went wrong Decisions: - A 5xx with JSON errors now gives the server's message without "Retry later": for a contact saved without its topics, retrying the create fails because the contact exists. Only a body without errors keeps the generic retry advice. - The contact docs name the 503 whose message names the contact; a 503 from a proxy or during a deploy comes without it and saved nothing. - The webhook type error separates the allowed list from the given value with a semicolon, so the given type no longer reads as one more allowed one. Co-Authored-By: Claude Opus 5.5 --- examples/contacts/all.php | 4 ++-- src/Api/General/Contact.php | 5 +++-- src/DTO/Request/Webhook/CreateWebhook.php | 2 +- src/Exception/HttpServerException.php | 17 +++++++---------- tests/Api/General/ContactTest.php | 5 +++-- tests/Api/Sending/WebhookTest.php | 2 +- tests/Exception/HttpServerExceptionTest.php | 10 ++++++---- 7 files changed, 23 insertions(+), 22 deletions(-) diff --git a/examples/contacts/all.php b/examples/contacts/all.php index 27d37ad..3ba7337 100644 --- a/examples/contacts/all.php +++ b/examples/contacts/all.php @@ -127,8 +127,8 @@ /** * Update only a contact's subscription topic statuses: the topic and domain pairs left out keep - * their status. A 503 means the contact was saved but its topic statuses were not; the exception - * message names the contact to send them again to. + * their status. A 503 whose exception message names the contact means the contact was saved but + * its topic statuses were not: send them again to that contact. A 503 without it saved nothing. * * PATCH https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email} */ diff --git a/src/Api/General/Contact.php b/src/Api/General/Contact.php index 533beb5..456f289 100644 --- a/src/Api/General/Contact.php +++ b/src/Api/General/Contact.php @@ -20,8 +20,9 @@ * With Subscription Topics, a contact's get, create and update responses carry * `data.subscription_topics`: its status per topic and domain, null when the statuses can't be * read (retry later), and absent for an account without topics. A create or update with - * subscription topics that fails with `503` saved the contact but not its topic statuses: the - * HttpServerException message names the contact to send them again to, in an update. + * subscription topics that fails with a `503` whose HttpServerException message names the contact + * saved the contact but not its topic statuses: send them again to that contact, in an update. A + * `503` without that message (from a proxy or during a deploy, say) saved nothing. */ class Contact extends AbstractApi implements GeneralInterface { diff --git a/src/DTO/Request/Webhook/CreateWebhook.php b/src/DTO/Request/Webhook/CreateWebhook.php index 0acbea5..5b1d8d7 100644 --- a/src/DTO/Request/Webhook/CreateWebhook.php +++ b/src/DTO/Request/Webhook/CreateWebhook.php @@ -41,7 +41,7 @@ public function __construct( ]; if (!in_array($webhookType, $allowedTypes, true)) { throw new InvalidArgumentException(sprintf( - '"webhookType" must be one of "%s", "%s" given', + '"webhookType" must be one of "%s"; "%s" given', implode('", "', $allowedTypes), $webhookType )); diff --git a/src/Exception/HttpServerException.php b/src/Exception/HttpServerException.php index 7c1c401..d4da7d6 100644 --- a/src/Exception/HttpServerException.php +++ b/src/Exception/HttpServerException.php @@ -13,21 +13,18 @@ class HttpServerException extends HttpException { /** - * Appends the `errors` of a JSON body, such as the contact named by a contact create or update - * that saved the contact but not its subscription topics, to the generic server error message. + * Says the `errors` of a JSON body, such as the contact named by a contact create or update that + * saved the contact but not its subscription topics. Only a body without them gets the generic + * "retry later" message: a retry is the wrong advice when the server says what to do instead. */ public static function createFromResponse(ResponseInterface $response): HttpServerException { $statusCode = $response->getStatusCode(); - $errorMsg = sprintf( - 'Internal Server Error. HTTP response code ("%d") received from the API server. Retry later or contact support.', - $statusCode - ); - $errors = self::getResponseErrors($response); - if ($errors !== '') { - $errorMsg .= ' Errors: ' . $errors; - } + $received = sprintf('HTTP response code ("%d") received from the API server.', $statusCode); + $errorMsg = $errors !== '' + ? sprintf('Server error. %s Errors: %s', $received, $errors) + : sprintf('Internal Server Error. %s Retry later or contact support.', $received); return new self($errorMsg, $statusCode); } diff --git a/tests/Api/General/ContactTest.php b/tests/Api/General/ContactTest.php index b87d08c..912b29e 100644 --- a/tests/Api/General/ContactTest.php +++ b/tests/Api/General/ContactTest.php @@ -428,8 +428,9 @@ public function testCreateContactReportsUnsavedSubscriptionTopics(): void $this->expectException(HttpServerException::class); $this->expectExceptionCode(503); - $this->expectExceptionMessage('Internal Server Error. HTTP response code ("503") received from the API server. ' - . 'Retry later or contact support. Errors: ' . $message); + $this->expectExceptionMessage( + 'Server error. HTTP response code ("503") received from the API server. Errors: ' . $message + ); $this->contact->createContact(new CreateContact( email: 'test@example.com', diff --git a/tests/Api/Sending/WebhookTest.php b/tests/Api/Sending/WebhookTest.php index 6bf3645..80e40a9 100644 --- a/tests/Api/Sending/WebhookTest.php +++ b/tests/Api/Sending/WebhookTest.php @@ -197,7 +197,7 @@ public function testCreateWebhookRejectsUnknownWebhookType(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - '"webhookType" must be one of "email_sending", "audit_log", "inbound_receiving", "campaigns", "spam" given' + '"webhookType" must be one of "email_sending", "audit_log", "inbound_receiving", "campaigns"; "spam" given' ); new CreateWebhook( diff --git a/tests/Exception/HttpServerExceptionTest.php b/tests/Exception/HttpServerExceptionTest.php index 4ca91d4..19c97c0 100644 --- a/tests/Exception/HttpServerExceptionTest.php +++ b/tests/Exception/HttpServerExceptionTest.php @@ -16,7 +16,8 @@ class HttpServerExceptionTest extends TestCase { /** - * A server error's JSON `errors` reaches the exception message; any other body leaves the generic message as is. + * A server error's JSON `errors` make the exception message, without the generic retry advice; any other body + * gets the generic message. * * @dataProvider serverErrorProvider */ @@ -32,19 +33,20 @@ public function serverErrorProvider(): iterable { $genericMessage = 'Internal Server Error. HTTP response code ("%d") received from the API server. ' . 'Retry later or contact support.'; + $errorsMessage = 'Server error. HTTP response code ("%d") received from the API server. Errors: '; $json = ['Content-Type' => 'application/json']; yield 'string errors' => [ new Response(503, $json, json_encode(['errors' => 'Send them again in an update of contact 42.'])), - sprintf($genericMessage, 503) . ' Errors: Send them again in an update of contact 42.', + sprintf($errorsMessage, 503) . 'Send them again in an update of contact 42.', ]; yield 'array errors' => [ new Response(500, $json, json_encode(['errors' => ['base' => ['something broke']]])), - sprintf($genericMessage, 500) . ' Errors: base -> something broke.', + sprintf($errorsMessage, 500) . 'base -> something broke.', ]; yield 'non-string values in errors' => [ new Response(500, $json, json_encode(['errors' => ['contact_id' => 123, 'base' => null, 'flags' => [true]]])), - sprintf($genericMessage, 500) . ' Errors: contact_id -> 123. base -> null. flags -> true.', + sprintf($errorsMessage, 500) . 'contact_id -> 123. base -> null. flags -> true.', ]; yield 'html body' => [ new Response(502, ['Content-Type' => 'text/html'], 'Bad Gateway'),