diff --git a/src/MailgunHelper.php b/src/MailgunHelper.php index 38bbabd..045c53c 100644 --- a/src/MailgunHelper.php +++ b/src/MailgunHelper.php @@ -3,6 +3,7 @@ namespace LeKoala\Mailgun; use \Exception; +use Swift_Mailer; use Mailgun\Mailgun; use SilverStripe\Control\Director; use SilverStripe\Core\Environment; @@ -47,7 +48,9 @@ public static function getMailer() */ public static function isMailgunMailer() { - return self::getMailer()->getSwiftMailer()->getTransport() instanceof MailgunSwiftTransport; + return self::getMailer() + ->getSwiftMailer() + ->getTransport() instanceof MailgunSwiftTransport; } /** @@ -60,7 +63,9 @@ public static function getClient() if (!self::$client) { $key = self::config()->api_key; if (empty($key)) { - throw new \Exception("api_key is not configured for " . __CLASS__); + throw new \Exception( + 'api_key is not configured for ' . __CLASS__ + ); } $endpoint = self::DEFAULT_ENDPOINT; if (self::config()->endpoint) { @@ -102,7 +107,7 @@ public static function getDomain() if ($domain = Environment::getEnv('MAILGUN_DOMAIN')) { return $domain; } - throw new Exception("MAILGUN_DOMAIN not set"); + throw new Exception('MAILGUN_DOMAIN not set'); } /** @@ -164,15 +169,18 @@ public static function registerTransport() $client = self::getClient(); $mailer = self::getMailer(); if (!$mailer instanceof SwiftMailer) { - throw new Exception("Mailer must be an instance of " . SwiftMailer::class . " instead of " . get_class($mailer)); + throw new Exception( + 'Mailer must be an instance of ' . + SwiftMailer::class . + ' instead of ' . + get_class($mailer) + ); } $transport = new MailgunSwiftTransport($client); - $newSwiftMailer = $mailer->getSwiftMailer()->newInstance($transport); - $mailer->setSwiftMailer($newSwiftMailer); + $mailer->setSwiftMailer(new Swift_Mailer($transport)); return $mailer; } - /** * Resolve default send from address * @@ -184,8 +192,10 @@ public static function registerTransport() * @param bool $createDefault * @return string */ - public static function resolveDefaultFromEmail($from = null, $createDefault = true) - { + public static function resolveDefaultFromEmail( + $from = null, + $createDefault = true + ) { $original_from = $from; if (!empty($from)) { // If we have a sender, validate its email diff --git a/src/MailgunSwiftTransport.php b/src/MailgunSwiftTransport.php index 7689a3a..32b5bd7 100644 --- a/src/MailgunSwiftTransport.php +++ b/src/MailgunSwiftTransport.php @@ -6,7 +6,7 @@ use \Swift_MimePart; use \Swift_Transport; use \Swift_Attachment; -use \Swift_Mime_Message; +use \Swift_Mime_SimpleMessage; use \Swift_Events_SendEvent; use \Swift_Events_EventListener; use Psr\Log\LoggerInterface; @@ -22,7 +22,6 @@ */ class MailgunSwiftTransport implements Swift_Transport { - /** * @var Swift_Transport_SimpleMailInvoker */ @@ -86,22 +85,37 @@ public function stop() } /** - * @param Swift_Mime_Message $message + * Not used + */ + public function ping() + { + return true; + } + + /** + * @param Swift_Mime_SimpleMessage $message * @param null $failedRecipients * @return int Number of messages sent */ - public function send(Swift_Mime_Message $message, &$failedRecipients = null) - { + public function send( + Swift_Mime_SimpleMessage $message, + &$failedRecipients = null + ) { $this->resultApi = null; if ($event = $this->eventDispatcher->createSendEvent($this, $message)) { - $this->eventDispatcher->dispatchEvent($event, 'beforeSendPerformed'); + $this->eventDispatcher->dispatchEvent( + $event, + 'beforeSendPerformed' + ); if ($event->bubbleCancelled()) { return 0; } } $sendCount = 0; - $disableSending = $message->getHeaders()->has('X-SendingDisabled') || MailgunHelper::config()->disable_sending; + $disableSending = + $message->getHeaders()->has('X-SendingDisabled') || + MailgunHelper::config()->disable_sending; $emailData = $this->buildMessage($message); @@ -114,7 +128,9 @@ public function send(Swift_Mime_Message $message, &$failedRecipients = null) ]; $queued = true; } else { - $resultResponse = $client->messages()->send(MailgunHelper::getDomain(), $emailData); + $resultResponse = $client + ->messages() + ->send(MailgunHelper::getDomain(), $emailData); if ($resultResponse) { $result = [ 'message' => $resultResponse->getMessage(), @@ -154,12 +170,14 @@ public function send(Swift_Mime_Message $message, &$failedRecipients = null) /** * Log message content * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @param array $results Results from the api * @return void */ - protected function logMessageContent(Swift_Mime_Message $message, $results = []) - { + protected function logMessageContent( + Swift_Mime_SimpleMessage $message, + $results = [] + ) { $subject = $message->getSubject(); $body = $message->getBody(); $contentType = $this->getMessagePrimaryContentType($message); @@ -173,10 +191,16 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = []) $logContent .= 'From : ' . print_r($message->getFrom(), true) . "\n"; $logContent .= 'Headers:' . "\n"; foreach ($message->getHeaders()->getAll() as $header) { - $logContent .= ' ' . $header->getFieldName() . ': ' . $header->getFieldBody() . "\n"; + $logContent .= + ' ' . + $header->getFieldName() . + ': ' . + $header->getFieldBody() . + "\n"; } if (!empty($message->getTo())) { - $logContent .= 'Recipients : ' . print_r($message->getTo(), true) . "\n"; + $logContent .= + 'Recipients : ' . print_r($message->getTo(), true) . "\n"; } $logContent .= 'Results:' . "\n"; foreach ($results as $resultKey => $resultValue) { @@ -197,16 +221,32 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = []) $logContent .= '
'; foreach ($attachments as $attachment) { if ($attachment instanceof Swift_Attachment) { - $attachmentDestination = $logFolder . '/' . $logName . '_' . $attachment->getFilename(); - file_put_contents($attachmentDestination, $attachment->getBody()); - $logContent .= 'File : ' . $attachment->getFilename() . '
'; + $attachmentDestination = + $logFolder . + '/' . + $logName . + '_' . + $attachment->getFilename(); + file_put_contents( + $attachmentDestination, + $attachment->getBody() + ); + $logContent .= + 'File : ' . + $attachment->getFilename() . + '
'; } } } // Store it - $ext = ($contentType == 'text/html') ? 'html' : 'txt'; - $r = file_put_contents($logFolder . '/' . $logName . '.' . $ext, $logContent); + $ext = $contentType == 'text/html' ? 'html' : 'txt'; + $r = file_put_contents( + $logFolder . '/' . $logName . '.' . $ext, + $logContent + ); if (!$r && Director::isDev()) { throw new Exception('Failed to store email in ' . $logFolder); @@ -218,7 +258,9 @@ protected function logMessageContent(Swift_Mime_Message $message, $results = []) */ public function getLogger() { - return Injector::inst()->get(LoggerInterface::class)->withName('Mailgun'); + return Injector::inst() + ->get(LoggerInterface::class) + ->withName('Mailgun'); } /** @@ -234,10 +276,7 @@ public function registerPlugin(Swift_Events_EventListener $plugin) */ protected function getSupportedContentTypes() { - return array( - 'text/plain', - 'text/html' - ); + return ['text/plain', 'text/html']; } /** @@ -250,18 +289,19 @@ protected function supportsContentType($contentType) } /** - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @return string */ - protected function getMessagePrimaryContentType(Swift_Mime_Message $message) - { + protected function getMessagePrimaryContentType( + Swift_Mime_SimpleMessage $message + ) { $contentType = $message->getContentType(); if ($this->supportsContentType($contentType)) { return $contentType; } - // SwiftMailer hides the content type set in the constructor of Swift_Mime_Message as soon + // SwiftMailer hides the content type set in the constructor of Swift_Mime_SimpleMessage as soon // as you add another part to the message. We need to access the protected property // _userContentType to get the original type. $messageRef = new \ReflectionClass($message); @@ -277,11 +317,11 @@ protected function getMessagePrimaryContentType(Swift_Mime_Message $message) /** * Convert a Swift Message for the api * - * @param Swift_Mime_Message $message + * @param Swift_Mime_SimpleMessage $message * @return array Mailgun Send Message * @throws \Swift_SwiftException */ - public function buildMessage(Swift_Mime_Message $message) + public function buildMessage(Swift_Mime_SimpleMessage $message) { $contentType = $this->getMessagePrimaryContentType($message); @@ -291,7 +331,11 @@ public function buildMessage(Swift_Mime_Message $message) $fromFirstName = current($fromAddresses); if ($fromFirstName) { - $this->fromEmail = sprintf('%s <%s>', $fromFirstName, $fromFirstEmail); + $this->fromEmail = sprintf( + '%s <%s>', + $fromFirstName, + $fromFirstEmail + ); } else { $this->fromEmail = $fromFirstEmail; } @@ -299,16 +343,18 @@ public function buildMessage(Swift_Mime_Message $message) $toAddresses = $message->getTo(); $ccAddresses = $message->getCc() ? $message->getCc() : []; $bccAddresses = $message->getBcc() ? $message->getBcc() : []; - $replyToAddresses = $message->getReplyTo() ? $message->getReplyTo() : []; - - $recipients = array(); - $cc = array(); - $bcc = array(); - $attachments = array(); - $headers = array(); - $tags = array(); - $metadata = array(); - $mergeVars = array(); + $replyToAddresses = $message->getReplyTo() + ? $message->getReplyTo() + : []; + + $recipients = []; + $cc = []; + $bcc = []; + $attachments = []; + $headers = []; + $tags = []; + $metadata = []; + $mergeVars = []; $inlineCss = null; // Mandrill compatibility @@ -321,16 +367,25 @@ public function buildMessage(Swift_Mime_Message $message) } if ($message->getHeaders()->has('X-MC-Metadata')) { $metadataHeader = $message->getHeaders()->get('X-MC-Metadata'); - $metadata = json_decode($metadataHeader->getValue(), JSON_OBJECT_AS_ARRAY); + $metadata = json_decode( + $metadataHeader->getValue(), + JSON_OBJECT_AS_ARRAY + ); $message->getHeaders()->remove('X-MC-Metadata'); } if ($message->getHeaders()->has('X-MC-InlineCSS')) { - $inlineCss = $message->getHeaders()->get('X-MC-InlineCSS')->getValue(); + $inlineCss = $message + ->getHeaders() + ->get('X-MC-InlineCSS') + ->getValue(); $message->getHeaders()->remove('X-MC-InlineCSS'); } if ($message->getHeaders()->has('X-MC-MergeVars')) { $mergeVarsHeader = $message->getHeaders()->get('X-MC-MergeVars'); - $mergeVarsFromMC = json_decode($mergeVarsHeader->getValue(), JSON_OBJECT_AS_ARRAY); + $mergeVarsFromMC = json_decode( + $mergeVarsHeader->getValue(), + JSON_OBJECT_AS_ARRAY + ); // We need to transform them to a mandrill friendly format rcpt => vars, to email : {...} foreach ($mergeVarsFromMC as $row) { $mergeVars[$row['rcpt']] = $row['vars']; @@ -348,13 +403,23 @@ public function buildMessage(Swift_Mime_Message $message) } // @link https://documentation.mailgun.com/en/latest/user_manual.html#attaching-data-to-messages if ($message->getHeaders()->has('X-Mailgun-Variables')) { - $metadataHeader = $message->getHeaders()->get('X-Mailgun-Variables'); - $metadata = json_decode($metadataHeader->getValue(), JSON_OBJECT_AS_ARRAY); + $metadataHeader = $message + ->getHeaders() + ->get('X-Mailgun-Variables'); + $metadata = json_decode( + $metadataHeader->getValue(), + JSON_OBJECT_AS_ARRAY + ); $message->getHeaders()->remove('X-Mailgun-Variables'); } if ($message->getHeaders()->has('X-Mailgun-Recipient-Variables')) { - $recipientVariablesHeader = $message->getHeaders()->get('X-Mailgun-Recipient-Variables'); - $mergeVars = json_decode($recipientVariablesHeader->getValue(), JSON_OBJECT_AS_ARRAY); + $recipientVariablesHeader = $message + ->getHeaders() + ->get('X-Mailgun-Recipient-Variables'); + $mergeVars = json_decode( + $recipientVariablesHeader->getValue(), + JSON_OBJECT_AS_ARRAY + ); $message->getHeaders()->remove('X-Mailgun-Recipient-Variables'); } @@ -410,12 +475,18 @@ public function buildMessage(Swift_Mime_Message $message) // File attachment. You can post multiple attachment values. // Important: You must use multipart/form-data encoding when sending attachments. if ($child instanceof Swift_Attachment) { - $attachment = ['filename' => $child->getFilename(), 'fileContent' => $child->getBody()]; + $attachment = [ + 'filename' => $child->getFilename(), + 'fileContent' => $child->getBody(), + ]; $attachments[] = $attachment; - } elseif ($child instanceof Swift_MimePart && $this->supportsContentType($child->getContentType())) { - if ($child->getContentType() == "text/html") { + } elseif ( + $child instanceof Swift_MimePart && + $this->supportsContentType($child->getContentType()) + ) { + if ($child->getContentType() == 'text/html') { $bodyHtml = $child->getBody(); - } elseif ($child->getContentType() == "text/plain") { + } elseif ($child->getContentType() == 'text/plain') { $bodyText = $child->getBody(); } } @@ -433,12 +504,15 @@ public function buildMessage(Swift_Mime_Message $message) // Custom unsubscribe list if ($message->getHeaders()->has('List-Unsubscribe')) { - $headers['List-Unsubscribe'] = $message->getHeaders()->get('List-Unsubscribe')->getValue(); + $headers['List-Unsubscribe'] = $message + ->getHeaders() + ->get('List-Unsubscribe') + ->getValue(); } // Mailgun params format does not work well in yml, so we map them $rawParams = MailgunHelper::config()->default_params; - $defaultParams = []; + $defaultParams = []; foreach ($rawParams as $rawParamKey => $rawParamValue) { switch ($rawParamKey) { case 'inline': @@ -460,13 +534,13 @@ public function buildMessage(Swift_Mime_Message $message) } // Build base transmission - $mailgunMessage = array( + $mailgunMessage = [ 'to' => implode(',', $recipients), 'from' => $this->fromEmail, 'subject' => $message->getSubject(), 'html' => $bodyHtml, 'text' => $bodyText, - ); + ]; if ($reply_to) { $mailgunMessage['h:Reply-To'] = $reply_to; }