diff --git a/src/Api/Message.php b/src/Api/Message.php index 77e3b9f..d51553a 100644 --- a/src/Api/Message.php +++ b/src/Api/Message.php @@ -57,8 +57,11 @@ class Message extends HttpApi } $postDataMultipart = array_merge($this->prepareMultipartParameters($params), $postDataMultipart); - $response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart); - $this->closeResources($postDataMultipart); + try { + $response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart); + } finally { + $this->closeResources($postDataMultipart); + } return $this->hydrateResponse($response, SendResponse::class); } @@ -91,8 +94,11 @@ class Message extends HttpApi ]; } $postDataMultipart[] = $this->prepareFile('message', $fileData); - $response = $this->httpPostRaw(sprintf('/v3/%s/messages.mime', $domain), $postDataMultipart); - $this->closeResources($postDataMultipart); + try { + $response = $this->httpPostRaw(sprintf('/v3/%s/messages.mime', $domain), $postDataMultipart); + } finally { + $this->closeResources($postDataMultipart); + } return $this->hydrateResponse($response, SendResponse::class); } diff --git a/tests/Api/MessageTest.php b/tests/Api/MessageTest.php index b5f66d9..fac462c 100644 --- a/tests/Api/MessageTest.php +++ b/tests/Api/MessageTest.php @@ -124,6 +124,52 @@ class MessageTest extends TestCase $api->sendMime('foo', ['mailbox@myapp.com'], $message, []); } + public function testCloseResourcesOnSendRequestException() + { + $api = $this->getApiMock(); + + $api->expects($this->once()) + ->method('httpPostRaw') + ->willThrowException(new \Exception('Something went wrong')); + + $streamsCount = count(get_resources('stream')); + + try { + $api->send('example.com', [ + 'from' => 'bob@example.com', + 'to' => 'sally@example.com', + 'subject' => 'Test file path attachments', + 'text' => 'Test', + 'attachment' => [ + ['filePath' => __DIR__.'/../TestAssets/mailgun_icon1.png', 'filename' => 'mailgun_icon1.png'], + ], + ]); + } catch (\Exception $e) { + $this->assertEquals('Something went wrong', $e->getMessage()); + } + + $this->assertCount($streamsCount, get_resources('stream')); + } + + public function testCloseResourcesOnSendMimeRequestException() + { + $api = $this->getApiMock(); + + $api->expects($this->once()) + ->method('httpPostRaw') + ->willThrowException(new \Exception('Something went wrong')); + + $streamsCount = count(get_resources('stream')); + + try { + $api->sendMime('foo', ['mailbox@myapp.com'], 'mime message', ['o:Foo' => 'bar']); + } catch (\Exception $e) { + $this->assertEquals('Something went wrong', $e->getMessage()); + } + + $this->assertCount($streamsCount, get_resources('stream')); + } + /** * {@inheritdoc} */