Skip to content

Conversation

@gaalferov
Copy link
Collaborator

@gaalferov gaalferov commented Jul 12, 2025

Motivation

Support new functionality (Contacts Batch Import)
https://help.mailtrap.io/article/147-contacts

Changes

  • Add Contacts Batch API Import

How to test

composer test

OR run PHP code from the example

(new MailtrapGeneralClient($config))
    ->contacts($accountId)
    ->importContacts(
        [
            ImportContact::init(
                uniqid('john_') . '@example.com',
                ['first_name' => 'John'],
                [1,2],
                [3,4],
            ),
            ImportContact::init(
                uniqid('jane_') . '@example.com',
                ['first_name' => 'Jane'],
                [3,4],
                [1,2],
            )
        ]
    );

Summary by CodeRabbit

  • New Features

    • Introduced bulk contact import functionality, allowing users to import multiple contacts with support for custom fields and list management.
    • Added the ability to check the status and results of contact imports.
  • Documentation

    • Updated the README and changelog to reflect new contact import capabilities.
    • Added usage examples for importing contacts and retrieving import status.
  • Tests

    • Expanded test coverage to include scenarios for contact import, status retrieval, and error handling.

@coderabbitai
Copy link

coderabbitai bot commented Jul 12, 2025

Walkthrough

This update introduces bulk contact import functionality to the Contact API, including new DTOs, API methods, documentation, usage examples, and comprehensive test coverage for importing contacts and retrieving import status. The changelog and README are updated to reflect the new feature.

Changes

File(s) Change Summary
CHANGELOG.md, README.md Added changelog entry for v3.6.0 and updated README to document new contact import functionality.
examples/general/contacts.php Added usage examples for bulk contact import and retrieving import status, with error handling.
src/Api/General/Contact.php Added importContacts and getContactImport public methods; imported ImportContact DTO.
src/DTO/Request/Contact/ImportContact.php Introduced ImportContact DTO class with properties, getters, factory, and array conversion method.
tests/Api/General/ContactTest.php Added tests for successful import, status retrieval, not found, and validation error cases for import.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ContactAPI
    participant MailtrapAPI

    Client->>ContactAPI: importContacts(array of ImportContact)
    ContactAPI->>MailtrapAPI: POST /contacts/imports (bulk contacts data)
    MailtrapAPI-->>ContactAPI: Response (importId, status)
    ContactAPI-->>Client: Response (importId, status)

    Client->>ContactAPI: getContactImport(importId)
    ContactAPI->>MailtrapAPI: GET /contacts/imports/{importId}
    MailtrapAPI-->>ContactAPI: Response (import status/results)
    ContactAPI-->>Client: Response (import status/results)
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers

  • leonid-shevtsov
  • IgorDobryn
  • i7an
  • yanchuk
  • mklocek
  • VladimirTaytor

Poem

Hopping through code with a whisk and a wand,
Bulk contacts now import—of this, I'm quite fond!
With tests and docs, the features align,
Status checks ready, your imports will shine.
🐇✨
Import away, let your contacts abound—
In this patch, new features are found!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76e1cc1 and 7c44050.

📒 Files selected for processing (1)
  • src/DTO/Request/Contact/ImportContact.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/DTO/Request/Contact/ImportContact.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (actions)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gaalferov gaalferov linked an issue Jul 12, 2025 that may be closed by this pull request
@gaalferov gaalferov changed the title [3.6.0] Contact Imports [3.6.0] Contacts Batch API Import Jul 12, 2025
@gaalferov gaalferov marked this pull request as ready for review July 13, 2025 17:05
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: 1

🧹 Nitpick comments (3)
src/DTO/Request/Contact/ImportContact.php (3)

20-27: Consider removing the redundant static factory method.

The init method duplicates the functionality of the constructor without adding any value. This violates the DRY principle and creates unnecessary code duplication.

-    public static function init(
-        string $email,
-        array $fields = [],
-        array $listIdsIncluded = [],
-        array $listIdsExcluded = []
-    ): self {
-        return new self($email, $fields, $listIdsIncluded, $listIdsExcluded);
-    }

49-60: Optimize the array filtering logic.

The array_filter callback checking for !== null is unnecessary since none of the properties can be null based on the constructor (the string is required and arrays have default empty values).

    public function toArray(): array
    {
-        return array_filter(
-            [
-                'email'                => $this->getEmail(),
-                'fields'               => $this->getFields(),
-                'list_ids_included'    => $this->getListIdsIncluded(),
-                'list_ids_excluded'    => $this->getListIdsExcluded(),
-            ],
-            fn($value) => $value !== null
-        );
+        return [
+            'email'                => $this->getEmail(),
+            'fields'               => $this->getFields(),
+            'list_ids_included'    => $this->getListIdsIncluded(),
+            'list_ids_excluded'    => $this->getListIdsExcluded(),
+        ];
    }

12-16: Consider adding email validation.

The constructor accepts any string as email without validation. Consider adding basic email format validation to prevent invalid data from being processed.

    public function __construct(
        private string $email,
        private array $fields = [],
        private array $listIdsIncluded = [],
        private array $listIdsExcluded = []
    ) {
+        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
+            throw new \InvalidArgumentException('Invalid email format');
+        }
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fb9143 and e4cab76.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • README.md (1 hunks)
  • examples/general/contacts.php (2 hunks)
  • src/Api/General/Contact.php (2 hunks)
  • src/DTO/Request/Contact/ImportContact.php (1 hunks)
  • tests/Api/General/ContactTest.php (2 hunks)
🔇 Additional comments (14)
src/DTO/Request/Contact/ImportContact.php (1)

12-18: LGTM! Constructor parameters are well-structured.

The constructor properly initializes all required properties with sensible defaults for optional array parameters.

CHANGELOG.md (1)

1-3: LGTM! Changelog entry is properly formatted.

The new version entry correctly documents the Contact Imports API functionality addition and follows the established changelog format.

README.md (1)

36-36: LGTM! Documentation accurately reflects the new import feature.

The addition of "Import" to the contact management features list correctly documents the new bulk import functionality.

src/Api/General/Contact.php (2)

10-10: LGTM! Import statement is correctly added.

The ImportContact DTO is properly imported to support the new bulk import functionality.


266-277: LGTM! Import status retrieval method is well-implemented.

The getContactImport method follows the established patterns and correctly handles the GET request for import status retrieval.

examples/general/contacts.php (3)

5-5: LGTM! Import statement is correctly added.

The ImportContact DTO is properly imported to support the example usage.


277-306: Excellent example demonstrating bulk contact import.

The example is comprehensive, well-documented, and shows practical usage of the ImportContact DTO with various field types and list management options. The comment explaining the asynchronous nature and import limits is particularly helpful.


309-322: LGTM! Import status retrieval example is clear and complete.

The example properly demonstrates how to check import status and includes appropriate error handling.

tests/Api/General/ContactTest.php (6)

9-9: LGTM: Proper import addition

The import for ImportContact DTO is correctly added to support the new test methods.


480-518: Comprehensive test for bulk contact import

The test properly validates the importContacts() functionality with:

  • Correct HTTP POST method and endpoint
  • Proper payload structure with array mapping
  • Appropriate response assertions

The test data includes realistic scenarios with multiple contacts having different field combinations and list assignments.


520-540: Good coverage for in-progress import status

This test appropriately validates the getContactImport() method for imports that are still being processed, checking the correct endpoint and response structure.


542-568: Thorough validation of completed import status

The test comprehensively checks all fields returned when an import is finished, including the contact count metrics (created_contacts_count, updated_contacts_count, contacts_over_limit_count).


570-585: Proper error handling for non-existent imports

The test correctly validates the 404 error scenario with appropriate exception expectations and message verification.


587-627: Comprehensive validation error testing

This test thoroughly validates the complex nested error structure returned during validation failures. The expected error message on line 624 properly flattens the nested error structure for verification.

The test covers a realistic scenario with invalid email format and ensures proper exception handling.

@gaalferov gaalferov merged commit 29da863 into main Jul 14, 2025
20 checks passed
@gaalferov gaalferov deleted the feature/contact-imports branch July 14, 2025 14:38
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.

Contacts Batch API Import

4 participants