postoffice-1.0.x-dev/extensions/postoffice_compat/src/Plugin/Mail/CompatMailBase.php
extensions/postoffice_compat/src/Plugin/Mail/CompatMailBase.php
<?php
namespace Drupal\postoffice_compat\Plugin\Mail;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Mail\MailInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\RawMessage;
/**
* Base class for core compatibility mail plugins.
*/
abstract class CompatMailBase implements MailInterface {
/**
* The mailer.
*/
protected MailerInterface $mailer;
/**
* The log channel.
*/
protected LoggerChannelInterface $logger;
/**
* The text format to us.
*
* If this property is NULL, the default fallback format will be used.
*/
protected ?string $format = NULL;
/**
* Constructs a new core compatibility mail plugin base class.
*/
public function __construct(MailerInterface $mailer, LoggerChannelInterface $logger) {
$this->mailer = $mailer;
$this->logger = $logger;
}
/**
* Returns a symfony mail generated from the given core mail.
*/
abstract protected function emailFromMessage(array $message): RawMessage;
/**
* {@inheritdoc}
*/
public function format(array $message) {
$message['body'] = implode("\n\n", array_map(
fn ($chunk) => $chunk instanceof MarkupInterface ? $chunk : \check_markup($chunk, $this->format, $message['langcode']),
$message['body']
));
return $message;
}
/**
* {@inheritdoc}
*/
public function mail(array $message) {
$result = FALSE;
try {
$this->mailer->send($this->emailFromMessage($message));
$result = TRUE;
}
catch (\Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e]);
}
return $result;
}
}
