Skip to content

Instantly share code, notes, and snippets.

@texdc
Last active August 29, 2015 13:56
Show Gist options
  • Save texdc/8831520 to your computer and use it in GitHub Desktop.
Save texdc/8831520 to your computer and use it in GitHub Desktop.
Mailtrap, Zend Framework 2, and PhpUnit test case
<?php
use InvalidArgumentException;
use PHPUnit_Framework_TestCase as TestCase;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
/**
* A base testcase for mail transactions with Mailtrap.
*
* The following constants must be specified in the phpunit.xml config file:
* - MAILTRAP_TOKEN
* - MAILTRAP_INBOX_NAME
* - MAILTRAP_INBOX_PASSWORD
*
* @see http://mailtrap.io
*/
abstract class MailtrapTestCase extends TestCase
{
const MAILTRAP_API_URL = 'http://mailtrap.io/api/v1/inboxes';
const MAILTRAP_AUTH = 'plain';
const MAILTRAP_HOST = 'mailtrap.io';
const MAILTRAP_PORT = 2525;
protected static $smtpOptions = [
'host' => self::MAILTRAP_HOST,
'port' => self::MAILTRAP_PORT,
'connection_class' => self::MAILTRAP_AUTH,
'connection_config' => [
// from phpunit.xml
'username' => MAILTRAP_INBOX_NAME,
'password' => MAILTRAP_INBOX_PASSWORD,
]
];
protected function getMailTransport()
{
return new SmtpTransport(new SmtpOptions(static::$smtpOptions));
}
protected function getInboxesEndpoint()
{
return $this->buildApiEndpoint();
}
protected function getMessagesEndpoint($page = 1, $inbox = MAILTRAP_INBOX_NAME)
{
$this->assertString($inbox, "Inbox must be a string");
return $this->buildApiEndpoint("/$inbox/messages?page=$page");
}
protected function getMessageEndpoint($messageId, $inbox = MAILTRAP_INBOX_NAME)
{
$this->assertString($inbox, "Inbox must be a string");
$this->assertString($messageId, "Message id must be a string");
return $this->buildApiEndpoint("/$inbox/messages/$messageId");
}
private function buildApiEndpoint($path = '')
{
if (strpos($path, '?') === false) {
$path .= '?';
} else {
$path .= '&';
}
return static::MAILTRAP_API_URL . "{$path}token=" . MAILTRAP_TOKEN;
}
private function assertString($string, $message = null)
{
if (!is_string($string)) {
throw new InvalidArgumentException($message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment