Skip to content

Commit

Permalink
Moved send test, fixed #27, #35 (#36)
Browse files Browse the repository at this point in the history
* changed from travis to git action
* used new env setting method
* fixed brackets
* updated dependencies
* updated unit tests
* updated MandrillTest.php added runtime directory creation
* fixed metadata class var, code style updates, 
added ext-fileinfo to composer.json
* tests with key from secrets

* tests with key from secrets 2

* tests with key from secrets 3

* fixed response and error handling

* fixed logging

* replaced sendRaw with send

* set global merge vars and template content independent from template language
fixed response handling

* fixed test

* fixed message test
  • Loading branch information
simialbi authored Jun 17, 2021
1 parent 5957864 commit e7282c3
Show file tree
Hide file tree
Showing 7 changed files with 210 additions and 149 deletions.
6 changes: 5 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,9 @@ jobs:
- name: Install dependencies
run: composer update $DEFAULT_COMPOSER_FLAGS
- name: Run unit tests
env:
MANDRILL_API_KEY: ${{ secrets.MANDRILL_API_KEY }}
MANDRILL_FROM_ADDRESS: ${{ secrets.MANDRILL_FROM_ADDRESS }}
MANDRILL_TO_ADDRESS: ${{ secrets.MANDRILL_TO_ADDRESS }}
run: vendor/bin/phpunit --verbose --colors=always
continue-on-error: true # if is fork
continue-on-error: true # if is fork
58 changes: 32 additions & 26 deletions src/Mailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
use MailchimpTransactional\ApiClient;
use MailchimpTransactional\Configuration;
use Yii;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\mail\BaseMailer;

/**
Expand All @@ -37,20 +40,13 @@ class Mailer extends BaseMailer

const LANGUAGE_MAILCHIMP = 'mailchimp';
const LANGUAGE_HANDLEBARS = 'handlebars';

/**
* @var string Mandrill API key
*/
private $_apikey;

/**
* Whether the mailer should use mandrill templates instead of Yii views.
*
* @var boolean use mandrill templates instead of Yii views.
* @since 1.2.0
*/
public $useMandrillTemplates = false;

/**
* Whether the mailer should use the template defaults when using mandrill
* templates.
Expand All @@ -59,7 +55,6 @@ class Mailer extends BaseMailer
* @since 1.4.0
*/
public $useTemplateDefaults = true;

/**
* What language is used in mandrill templates, either mailchimp or handlebars
* Mailchimp language allows to use mc:edit and *|VAR|*
Expand All @@ -69,12 +64,14 @@ class Mailer extends BaseMailer
* @since 1.5.0
*/
public $templateLanguage = self::LANGUAGE_MAILCHIMP;

/**
* @var string message default class name.
*/
public $messageClass = '\nickcv\mandrill\Message';

/**
* @var string Mandrill API key
*/
private $_apikey;
/**
* @var ApiClient the Mailchimp API instance
* @since 2.0.0
Expand Down Expand Up @@ -107,7 +104,7 @@ public function init()
try {
$this->_mailchimp = new ApiClient();
$this->_mailchimp->setApiKey($this->_apikey);
$this->_mailchimp->setDefaultOutputFormat('php');
$this->_mailchimp->setDefaultOutputFormat('json');
} catch (\Exception $exc) {
Yii::error($exc->getMessage());
throw new \Exception('an error occurred with your mailer. Please check the application logs.', 500);
Expand Down Expand Up @@ -217,7 +214,7 @@ protected function sendMessage($message): bool
);
} else {
return $this->wasMessageSentSuccessful(
$this->_mailchimp->messages->sendRaw([
$this->_mailchimp->messages->send([
'message' => $message->getMandrillMessageArray(),
'async' => $message->isAsync()
])
Expand All @@ -234,26 +231,35 @@ protected function sendMessage($message): bool
*/
private function wasMessageSentSuccessful($mandrillResponse): bool
{
if ($mandrillResponse instanceof RequestException) {
Yii::error(
'A mandrill error occurred: ' . Configuration::class . ' - ' . $mandrillResponse->getMessage(),
self::LOG_CATEGORY
);

return false;
}
$this->_mandrillResponse = $mandrillResponse;
if (is_string($mandrillResponse) || $mandrillResponse instanceof RequestException) {
if ($mandrillResponse instanceof RequestException) {
/** @var RequestException $mandrillResponse */
Yii::error(
'A mandrill error occurred: ' . Configuration::class . ' - ' . $mandrillResponse->getMessage(),
self::LOG_CATEGORY
);
} else {
/** @var string $mandrillResponse */
Yii::error(
'A mandrill error occurred: ' . Configuration::class . ' - ' . $mandrillResponse,
self::LOG_CATEGORY
);
if (is_string($this->_mandrillResponse)) {
/** @var string $mandrillResponse */
try {
list(, $body) = explode("\r\n\r\n", $this->_mandrillResponse);
$this->_mandrillResponse = Json::decode($body);
} catch (InvalidArgumentException $e) {
$this->_mandrillResponse = [];
}

Yii::error(
'A mandrill error occurred: ' . Configuration::class . ' - ' . $mandrillResponse,
self::LOG_CATEGORY
);

return false;
}

$return = true;
foreach ($mandrillResponse as $recipient) {
foreach ($this->_mandrillResponse as &$recipient) {
$recipient = ArrayHelper::toArray($recipient);
switch ($recipient['status']) {
case self::STATUS_INVALID:
$return = false;
Expand Down
23 changes: 11 additions & 12 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -767,8 +767,7 @@ public function attachContent($content, array $options = []): Message
if (is_string($content) && strlen($content) !== 0) {
$this->_attachments[] = [
'name' => ArrayHelper::getValue($purifiedOptions, 'fileName', ('file_' . count($this->_attachments))),
'type' => ArrayHelper::getValue($purifiedOptions, 'contentType',
$this->getMimeTypeFromBinary($content)),
'type' => ArrayHelper::getValue($purifiedOptions, 'contentType', $this->getMimeTypeFromBinary($content)),
'content' => base64_encode($content),
];
}
Expand Down Expand Up @@ -832,15 +831,15 @@ public function embed($fileName, array $options = []): Message
public function embedContent($content, array $options = []): Message
{
$purifiedOptions = is_array($options) ? $options : [];
$mimeType = $this->getMimeTypeFromBinary($content);

if (is_string($content) && strlen($content) !== 0 && strpos($this->getMimeTypeFromBinary($content),
'image') === 0) {
if (is_string($content) && strlen($content) !== 0 && strpos($mimeType, 'image') === 0) {
$this->_images[] = [
'name' => ArrayHelper::getValue($purifiedOptions, 'fileName', ('file_' . count($this->_images))),
'type' => ArrayHelper::getValue(
$purifiedOptions,
'contentType',
$this->getMimeTypeFromBinary($content)
$mimeType
),
'content' => base64_encode($content),
];
Expand All @@ -866,11 +865,11 @@ public function setTemplateData(
): Message {
$this->_templateName = $templateName;

if ($templateLanguage === self::LANGUAGE_MAILCHIMP) {
// if ($templateLanguage === self::LANGUAGE_MAILCHIMP) {
$this->_templateContent = $this->convertParamsForTemplate($templateContent);
} elseif ($templateLanguage === self::LANGUAGE_HANDLEBARS) {
// if ($templateLanguage === self::LANGUAGE_HANDLEBARS) {
$this->setGlobalMergeVars($templateContent);
}
// }

$this->_mergeLanguage = $templateLanguage;

Expand Down Expand Up @@ -1432,10 +1431,10 @@ private function getReplyToString(): string
private function getFromName()
{
if ($this->_calculateDefaultValues) {
return $this->_fromName ? $this->_fromName : null;
return $this->_fromName ?: null;
}

return $this->_fromName ? $this->_fromName : Yii::$app->name;
return $this->_fromName ?: Yii::$app->name;
}

/**
Expand All @@ -1446,10 +1445,10 @@ private function getFromName()
private function getFromAddress()
{
if ($this->_calculateDefaultValues) {
return $this->_fromAddress ? $this->_fromAddress : null;
return $this->_fromAddress ?: null;
}

return $this->_fromAddress ? $this->_fromAddress : Yii::$app->params['adminEmail'];
return $this->_fromAddress ?: Yii::$app->params['adminEmail'];
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/MandrillMessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function testSetTemplateData()

$this->assertEquals('viewName', $this->_message->getTemplateName());

$this->assertEquals([
$this->assertArraySubset([
[
'name' => 'money',
'content' => 300,
Expand Down
157 changes: 157 additions & 0 deletions tests/MandrillSendTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php
/**
* @package yii2-mandrill
* @author Simon Karlen <simi.albi@gmail.com>
*/

namespace yiiunit\extensions\mandrill;

use nickcv\mandrill\Mailer;

/**
* Class MandrillSendTest
* @package yiiunit\extensions\mandrill
*/
class MandrillSendTest extends TestCase
{
/**
* @var string
*/
private $_apiKey;

/**
* @var string
*/
private $_fromAddress;

/**
* @var string
*/
private $_toAddress;

public function testSendMessage()
{
$mandrill = new Mailer(['apikey' => $this->_apiKey]);
$result = $mandrill->compose('test')
->setFrom($this->_fromAddress)
->setTo($this->_toAddress)
->setSubject('test email')
->embed($this->getTestImagePath())
->attach($this->getTestPdfPath())
->send();

$this->assertInternalType('array', $mandrill->getLastTransaction());
$lastTransaction = $mandrill->getLastTransaction()[0];
$this->assertArrayHasKey('email', $lastTransaction);
$this->assertEquals($this->_toAddress, $lastTransaction['email']);
$this->assertArrayHasKey('status', $lastTransaction);
$this->assertEquals('queued', $lastTransaction['status']);
$this->assertArrayHasKey('_id', $lastTransaction);

$this->assertTrue($result);
}

public function testSendMessageUsingMandrillTemplate()
{
$mandrill = new Mailer([
'apikey' => $this->_apiKey,
'useMandrillTemplates' => true,
]);
$result = $mandrill->compose('testTemplate', ['WORD' => 'my word'])
->setFrom($this->_fromAddress)
->setTo($this->_toAddress)
->setSubject('test template email')
->embed($this->getTestImagePath())
->attach($this->getTestPdfPath())
->setGlobalMergeVars(['MERGEVAR' => 'prova'])
->send();

$this->assertInternalType('array', $mandrill->getLastTransaction());
$lastTransaction = $mandrill->getLastTransaction()[0];
$this->assertArrayHasKey('email', $lastTransaction);
$this->assertEquals($this->_toAddress, $lastTransaction['email']);
$this->assertArrayHasKey('status', $lastTransaction);
$this->assertEquals('queued', $lastTransaction['status']);
$this->assertArrayHasKey('_id', $lastTransaction);

$this->assertTrue($result);
}

public function testSendMessageUsingMandrillTemplateHandlebars()
{
$mandrill = new Mailer([
'apikey' => $this->_apiKey,
'useMandrillTemplates' => true,
'useTemplateDefaults' => false,
'templateLanguage' => Mailer::LANGUAGE_HANDLEBARS,
]);
$result = $mandrill->compose('testTemplateHandlebars', ['variable' => 'test content'])
->setFrom($this->_fromAddress)
->setTo($this->_toAddress)
->setSubject('test handlebars')
->send();

$this->assertInternalType('array', $mandrill->getLastTransaction());
$lastTransaction = $mandrill->getLastTransaction()[0];
$this->assertArrayHasKey('email', $lastTransaction);
$this->assertEquals($this->_toAddress, $lastTransaction['email']);
$this->assertArrayHasKey('status', $lastTransaction);
$this->assertArrayHasKey('_id', $lastTransaction);

$this->assertTrue($result);
}

public function testCannotSendIfMandrillTemplateNotFound()
{
$mandrill = new Mailer([
'apikey' => $this->_apiKey,
'useMandrillTemplates' => true,
]);

$result = $mandrill->compose('madeupTemplate', ['WORD' => 'my word'])
->setFrom($this->_fromAddress)
->setTo($this->_toAddress)
->setSubject('test template email')
->embed($this->getTestImagePath())
->attach($this->getTestPdfPath())
->send();

$this->assertInternalType('array', $mandrill->getLastTransaction());
$this->assertArrayHasKey('status', $mandrill->getLastTransaction());
$this->assertEquals('error', $mandrill->getLastTransaction()['status']);

$this->assertFalse($result);
}

/**
* {@inheritDoc}
*/
protected function setUp()
{
parent::setUp();

$this->_apiKey = getenv('MANDRILL_API_KEY');
$this->_fromAddress = getenv('MANDRILL_FROM_ADDRESS');
$this->_toAddress = getenv('MANDRILL_TO_ADDRESS');

if (!$this->_apiKey || !$this->_fromAddress || !$this->_toAddress) {
$this->markTestSkipped('One of "API key", "from address" or "to address" not set in secrets. Test skipped.');
}
}

/**
* @return string
*/
private function getTestImagePath(): string
{
return __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'test.png';
}

/**
* @return string
*/
private function getTestPdfPath(): string
{
return __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'test.pdf';
}
}
Loading

0 comments on commit e7282c3

Please sign in to comment.