View source
<?php
namespace Drupal\commerce;
use Drupal\commerce\Event\CommerceEvents;
use Drupal\commerce\Event\PostMailSendEvent;
use Drupal\Core\Language\LanguageDefault;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class MailHandler implements MailHandlerInterface {
use StringTranslationTrait;
protected $languageDefault;
protected $languageManager;
protected $mailManager;
protected $eventDispatcher;
public function __construct(LanguageDefault $language_default, LanguageManagerInterface $language_manager, MailManagerInterface $mail_manager, EventDispatcherInterface $event_dispatcher) {
$this->languageDefault = $language_default;
$this->languageManager = $language_manager;
$this->mailManager = $mail_manager;
$this->eventDispatcher = $event_dispatcher;
}
public function sendMail($to, $subject, array $body, array $params = []) {
if (empty($to)) {
return FALSE;
}
$default_params = [
'headers' => [
'Content-Type' => 'text/html; charset=UTF-8;',
'Content-Transfer-Encoding' => '8Bit',
],
'id' => 'mail',
'from' => '',
'reply-to' => NULL,
'subject' => $subject,
'langcode' => $this->languageManager
->getCurrentLanguage()
->getId(),
'body' => $body,
];
if (!empty($params['cc'])) {
$default_params['headers']['Cc'] = $params['cc'];
}
if (!empty($params['bcc'])) {
$default_params['headers']['Bcc'] = $params['bcc'];
}
$params = array_replace($default_params, $params);
if ($params['langcode'] != $default_params['langcode']) {
$this
->changeActiveLanguage($params['langcode']);
}
$message = $this->mailManager
->mail('commerce', $params['id'], $to, $params['langcode'], $params, $params['reply-to']);
if ($params['langcode'] != $default_params['langcode']) {
$this
->changeActiveLanguage($default_params['langcode']);
}
$event = new PostMailSendEvent($params, $message);
$this->eventDispatcher
->dispatch(CommerceEvents::POST_MAIL_SEND, $event);
return (bool) $message['result'];
}
protected function changeActiveLanguage($langcode) {
if (!$this->languageManager
->isMultilingual()) {
return;
}
$language = $this->languageManager
->getLanguage($langcode);
if (!$language) {
return;
}
$this->languageDefault
->set($language);
$this->languageManager
->setConfigOverrideLanguage($language);
$this->languageManager
->reset();
$string_translation = $this
->getStringTranslation();
if ($string_translation instanceof TranslationManager) {
$string_translation
->setDefaultLangcode($language
->getId());
$string_translation
->reset();
}
}
}