Skip to content

Commit 76e1cc1

Browse files
committed
validate input for importContacts method and add corresponding tests
1 parent e4cab76 commit 76e1cc1

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/Api/General/Contact.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Mailtrap\DTO\Request\Contact\CreateContact;
1010
use Mailtrap\DTO\Request\Contact\ImportContact;
1111
use Mailtrap\DTO\Request\Contact\UpdateContact;
12+
use Mailtrap\Exception\InvalidArgumentException;
1213
use Psr\Http\Message\ResponseInterface;
1314

1415
/**
@@ -255,10 +256,23 @@ public function deleteContactField(int $fieldId): ResponseInterface
255256
*/
256257
public function importContacts(array $contacts): ResponseInterface
257258
{
259+
258260
return $this->handleResponse(
259261
$this->httpPost(
260262
path: $this->getBasePath() . '/imports',
261-
body: ['contacts' => array_map(fn(ImportContact $contact) => $contact->toArray(), $contacts)]
263+
body: [
264+
'contacts' => array_map(
265+
function ($contact): array {
266+
if (!$contact instanceof ImportContact) {
267+
throw new InvalidArgumentException(
268+
'Each contact must be an instance of ImportContact.'
269+
);
270+
}
271+
return $contact->toArray();
272+
},
273+
$contacts
274+
)
275+
]
262276
)
263277
);
264278
}

tests/Api/General/ContactTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Mailtrap\DTO\Request\Contact\UpdateContact;
99
use Mailtrap\DTO\Request\Contact\ImportContact;
1010
use Mailtrap\Exception\HttpClientException;
11+
use Mailtrap\Exception\InvalidArgumentException;
1112
use Mailtrap\Tests\MailtrapTestCase;
1213
use Nyholm\Psr7\Response;
1314
use Mailtrap\Helper\ResponseHelper;
@@ -626,6 +627,32 @@ public function testImportContactsValidationError(): void
626627
$this->contact->importContacts($contacts);
627628
}
628629

630+
public function testImportContactsThrowsExceptionForInvalidInput(): void
631+
{
632+
$contacts = [
633+
new ImportContact(
634+
635+
fields: ['first_name' => 'John'],
636+
listIdsIncluded: [1],
637+
listIdsExcluded: []
638+
),
639+
// Invalid input
640+
new UpdateContact(
641+
642+
fields: ['first_name' => 'John'],
643+
listIdsIncluded: [1],
644+
listIdsExcluded: []
645+
),
646+
];
647+
648+
$this->contact->expects($this->never())->method('httpPost');
649+
650+
$this->expectException(InvalidArgumentException::class);
651+
$this->expectExceptionMessage('Each contact must be an instance of ImportContact.');
652+
653+
$this->contact->importContacts($contacts);
654+
}
655+
629656
private function getExpectedContactFields(): array
630657
{
631658
return [

0 commit comments

Comments
 (0)