Skip to content

Conversation

@gaalferov
Copy link
Contributor

@gaalferov gaalferov commented Dec 23, 2025

This PR fixes all PHP code examples across OpenAPI specification files to match the actual mailtrap-php SDK implementation. The examples were outdated and didn't reflect the correct SDK usage, which could confuse developers using the API documentation.

Motivation

The PHP code examples in the OpenAPI specs (specs/*.openapi.yml) were inconsistent with the official PHP SDK examples found in the mailtrap-php repository. This caused:

  • Incorrect SDK usage patterns in documentation
  • Missing imports and helper classes
  • Wrong method signatures and client initialization
  • Inconsistent response handling

Key Improvements:

  1. Added Missing Imports
    use Mailtrap\Helper\ResponseHelper;
    use Mailtrap\MailtrapClient;
    use Mailtrap\MailtrapGeneralClient;
    use Mailtrap\Config;
    use Mailtrap\Mime\MailtrapEmail;
    use Symfony\Component\Mime\Address;
    // + DTOs for requests

  2. Fixed Client Initialization

  • Transactional: MailtrapClient::initSendingEmails(apiKey: $_ENV['MAILTRAP_API_KEY'])
  • Bulk: MailtrapClient::initSendingEmails(apiKey: ..., isBulk: true)
  • Sandbox: MailtrapClient::initSendingEmails(apiKey: ..., isSandbox: true, inboxId: $inboxId)
  • General: new MailtrapGeneralClient(new Config('YOUR_API_TOKEN'))
  1. Fixed Response Handling
    // Before (missing)
    $response = $mailtrap->send($email);

// After (with proper response handling)
$response = $mailtrap->send($email);
var_dump(ResponseHelper::toArray($response));

  1. Used Correct DTO Classes
    // Before (plain arrays)
    $client->create(['email' => 'test@example.com', 'fields' => [...]])

// After (proper DTOs)
$contacts->createContact(
CreateContact::init(
'test@example.com',
['first_name' => 'John'],
[1, 2, 3]
)
);

  1. Fixed Method Names to Match SDK
  • ✅ getContactById() / getContactByEmail() instead of get()
  • ✅ getAllContactLists() instead of lists()->getAll()
  • ✅ getAllContactFields() instead of fields()->getAll()
  • ✅ And many more...

Testing

All examples were verified against the reference implementations in:

  • /examples/contacts/all.php
  • /examples/sending/minimal.php
  • /examples/bulk/bulk.php
  • /examples/testing/messages.php
  • /examples/general/*.php
  • And other reference files

Reference

Based on the official mailtrap-php SDK examples:

Impact

✅ Documentation examples now match actual SDK usage
✅ Developers can copy-paste examples and they will work correctly
✅ Consistent code style across all PHP examples
✅ Proper error handling and response processing demonstrated


Note: This PR only updates PHP code examples in OpenAPI specs. No API functionality or SDK code was changed.

Summary by CodeRabbit

  • New Features

    • Expanded Contacts capabilities: full CRUD for contacts, lists, custom fields, imports/exports and contact events; account-scoped operations exposed.
    • Batch/transactional email samples now include sender and recipient display names.
  • Documentation

    • All PHP samples use environment-driven configuration instead of hard-coded values.
    • Samples now emit standardized, diagnostic response output and include consistent error/response handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 23, 2025

Walkthrough

Refactors PHP OpenAPI samples to use environment-driven configuration, introduces DTO-based request payloads and a MailtrapGeneralClient::contacts(accountId) account-scoped entrypoint, adds ResponseHelper for standardized response output, and updates many sample flows across contacts, email, general, and sandbox specs.

Changes

Cohort / File(s) Change Summary
Contacts API
specs/contacts.openapi.yml
Adds DTOs for contacts/exports/imports/events (e.g., CreateContact, UpdateContact, ImportContact, ContactExportFilter, CreateContactEvent), adds Mailtrap\MailtrapGeneralClient::contacts(string $accountId) and refactors PHP samples to use Config($_ENV['MAILTRAP_API_KEY']), account-scoped ->contacts($accountId) calls, DTO payloads, and ResponseHelper::toArray(...) with try/catch.
Email APIs
specs/email-api.openapi.yml, specs/email-batch.openapi.yml, specs/email-sending-bulk.openapi.yml, specs/email-sending-transactional.openapi.yml
Replace hard-coded IDs with $_ENV vars, add ResponseHelper imports and diagnostic var_dump(ResponseHelper::toArray($response)), include display names in Address(...) constructors, and standardize response formatting and imports across PHP samples.
General API
specs/general.openapi.yml
Switches PHP samples to Config($_ENV['MAILTRAP_API_KEY']), prefer MailtrapGeneralClient account-scoped patterns (e.g., ->accounts(), ->users($accountId), ->billing($accountId), ->permissions($accountId)), import DTOs where used, and use ResponseHelper for output.
Sandbox API
specs/sandbox.openapi.yml
Replace literal tokens/IDs with $_ENV variables, instantiate MailtrapSandboxClient via Config, refactor to account/project/inbox scoped calls (e.g., ->projects($accountId), ->inboxes($accountId)), adopt MailtrapEmail/sandbox sending patterns, and use ResponseHelper::toArray(...) / toString(...) for outputs.

Sequence Diagram(s)

mermaid
sequenceDiagram
autonumber
participant Dev as Developer (PHP sample)
participant Client as MailtrapGeneralClient
participant Resource as Contacts Resource
participant API as Mailtrap API
participant Helper as ResponseHelper

Dev->>Client: new MailtrapGeneralClient(Config($_ENV['MAILTRAP_API_KEY']))
Client->>Resource: contacts($accountId)
Dev->>Resource: createContact(CreateContact DTO)
Resource->>API: HTTP POST /accounts/{id}/contacts (payload)
API-->>Resource: 201 Created (response)
Resource-->>Dev: Response object
Dev->>Helper: ResponseHelper::toArray($response)
Helper-->>Dev: array (dumped)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing PHP code examples in OpenAPI specifications to match SDK implementation patterns.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c300913 and 3640428.

📒 Files selected for processing (1)
  • specs/sandbox.openapi.yml
🔇 Additional comments (5)
specs/sandbox.openapi.yml (5)

135-147: LGTM! Environment-driven configuration properly implemented.

The PHP example correctly uses environment variables for API keys and account IDs, and follows the SDK pattern with MailtrapSandboxClient and ResponseHelper::toArray() for standardized output.


2013-2034: LGTM! Sandbox email sending example correctly implemented.

The example uses the proper initSendingEmails factory method with isSandbox: true and constructs emails using MailtrapEmail with Symfony's Address component, matching the SDK's email sending pattern.


3148-3161: LGTM! Past review feedback addressed.

The getList() method now correctly uses ResponseHelper::toArray($response) to display the actual message list instead of just the status code.


3797-3811: LGTM! Consistent response handling for string content.

The body retrieval methods (getText, getRaw, getHtml, getEml) correctly use ResponseHelper::toString() for string content output, distinguishing from toArray() used for structured data responses.


4083-4092: LGTM! Environment variable naming now consistent.

The example now correctly uses MAILTRAP_MESSAGE_ID, aligning with all other message-related examples in the specification.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7238ef and c300913.

📒 Files selected for processing (7)
  • specs/contacts.openapi.yml
  • specs/email-api.openapi.yml
  • specs/email-batch.openapi.yml
  • specs/email-sending-bulk.openapi.yml
  • specs/email-sending-transactional.openapi.yml
  • specs/general.openapi.yml
  • specs/sandbox.openapi.yml
🔇 Additional comments (44)
specs/email-sending-bulk.openapi.yml (2)

78-78: LGTM! ResponseHelper import added correctly.

The import follows PHP conventions and aligns with the PR objective to standardize response handling across PHP examples.


97-97: LGTM! Standardized response output added.

Using ResponseHelper::toArray() provides consistent diagnostic output across all PHP examples.

specs/email-sending-transactional.openapi.yml (2)

77-77: LGTM! ResponseHelper import added correctly.

Consistent with the standardization across PHP examples in this PR.


94-94: LGTM! Response formatting consistent with PR pattern.

specs/email-batch.openapi.yml (3)

96-96: LGTM! ResponseHelper import added.


107-114: LGTM! Enhanced Address usage with display names.

Adding display names to the Address objects makes the example more complete and demonstrates proper usage of the Symfony Address class constructor.


117-118: LGTM! Standardized response output.

specs/general.openapi.yml (6)

115-124: LGTM! Environment-driven configuration with general client pattern.

The refactored example correctly:

  • Uses environment variables for API key
  • Initializes MailtrapGeneralClient for account operations
  • Uses ResponseHelper for standardized output

240-250: LGTM! Account-scoped user management with environment variables.

The example properly demonstrates:

  • Account ID from environment
  • Account-scoped users() method
  • Standardized response formatting

344-354: LGTM! Delete operation with appropriate status code output.

The example correctly:

  • Uses environment variables for resource IDs
  • Performs delete operation via users client
  • Outputs status code (appropriate for delete operations)

432-461: LGTM! Excellent DTO-based permissions management.

This is a significant improvement that demonstrates:

  • Proper DTO usage (CreateOrUpdatePermission, DestroyPermission, Permissions)
  • Type-safe permission constants from PermissionInterface
  • Environment-driven resource IDs
  • Clear separation between create/update and destroy operations

The example now provides a much better reference for SDK users.


584-594: LGTM! Consistent resource listing pattern.


696-706: LGTM! Billing API usage follows established pattern.

specs/email-api.openapi.yml (12)

78-90: LGTM! Environment-driven sending domain creation.


224-236: LGTM! Sending domains listing with environment configuration.


341-354: LGTM! Domain retrieval by ID with environment variables.


463-471: LGTM! Delete operation with status code output.


583-596: LGTM! Setup instructions sending with environment variables.


750-767: LGTM! Suppressions listing with optional search parameter.

The example demonstrates both usage patterns:

  • Getting all suppressions
  • Filtering by specific email

911-919: LGTM! Suppression deletion with status code output.


1017-1030: LGTM! Email templates listing via general client.

Correctly uses MailtrapGeneralClient for account-level email template operations.


1100-1122: LGTM! Excellent DTO usage for email template creation.

The example demonstrates proper DTO pattern with EmailTemplate::init(), which is much clearer and more type-safe than plain arrays. This provides:

  • Clear parameter names and order
  • Type safety
  • Better IDE support

1226-1242: LGTM! Template retrieval with environment-driven ID.


1274-1300: LGTM! Template update with DTO pattern.

Correctly demonstrates using EmailTemplate::init() for update operations with all template fields.


1346-1361: LGTM! Template deletion with status code output.

specs/contacts.openapi.yml (19)

127-145: LGTM!

The PHP code sample correctly demonstrates the updated SDK patterns: environment-based configuration, DTO-based payload via CreateContact::init(), and proper response handling with ResponseHelper::toArray().


319-334: LGTM!

The sample correctly demonstrates both getContactById and getContactByEmail methods, providing clear examples for both retrieval patterns.


458-488: LGTM!

Comprehensive example showing both updateContactById and updateContactByEmail with the full UpdateContact::init() signature including list management and unsubscribe flag.


586-597: LGTM!

Appropriately uses $response->getStatusCode() for the delete operation instead of ResponseHelper::toArray(), since DELETE returns 204 No Content with no body.


667-687: LGTM!

The sample demonstrates CreateContactEvent::init() with a variety of parameter types (integer, string, boolean, null), which aligns with the schema definition.


779-794: LGTM!

Clear demonstration of ContactExportFilter::init() with multiple filter types for export operations.


885-894: LGTM!

Consistent pattern using environment variable for the export ID.


984-1007: LGTM!

The sample uses PHP 8+ named arguments syntax for ImportContact, which improves readability. The example demonstrates importing multiple contacts with fields and list management.


1107-1116: LGTM!

Consistent pattern for retrieving import status.


1195-1207: LGTM!

Good addition of try-catch block demonstrating error handling. The getAllContactLists() method name aligns with the SDK conventions mentioned in the PR.


1278-1290: LGTM!

Consistent pattern with try-catch error handling for list creation.


1369-1378: LGTM!

Consistent pattern for retrieving a specific contact list.


1442-1451: LGTM!

Consistent pattern for updating a contact list.


1529-1536: LGTM!

Appropriately uses status code output for the delete operation, consistent with other delete samples.


1601-1608: LGTM!

Consistent pattern for retrieving all contact fields.


1689-1696: LGTM!

Correctly demonstrates createContactField with name, data_type, and merge_tag parameters.


1807-1815: LGTM!

Consistent pattern for retrieving a specific contact field.


1883-1891: LGTM!

Correctly demonstrates updateContactField with name and merge_tag parameters (data_type is not updatable per the API specification).


1991-1998: LGTM!

Consistent pattern with other delete operations, using status code output.

@yanchuk yanchuk merged commit 09e18d5 into mailtrap:main Dec 23, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants