You are here

public function OrderMailEventSubscriber::onMailSend in Commerce Core 8.2

Reacts to an order email being sent.

Parameters

\Drupal\commerce\Event\PostMailSendEvent $event: The "post mail send" event.

File

modules/log/src/EventSubscriber/OrderMailEventSubscriber.php, line 58

Class

OrderMailEventSubscriber
Reacts to order emails sent via the Commerce mail handler.

Namespace

Drupal\commerce_log\EventSubscriber

Code

public function onMailSend(PostMailSendEvent $event) {
  $params = $event
    ->getParams();
  if (!isset($params['order'])) {
    return;
  }

  /** @var \Drupal\commerce_log\LogStorageInterface $log_storage */
  $log_storage = $this->entityTypeManager
    ->getStorage('commerce_log');
  $message = $event
    ->getMessage();
  $result = (bool) $message['result'];
  $definitions = $this->logTemplateManager
    ->getDefinitions();

  // Check if we have a log template matching "mail_<mail_key>",
  // (e.g "mail_order_receipt"), otherwise, fallback to the generic
  // "order_mail" log template.
  // In case the email could not be delivered, we use the "failure" log
  // template, either the specific one, or the generic one in case
  // it does not exist.
  $template_id = $result ? 'mail_' . $params['id'] : 'mail_' . $params['id'] . '_failure';
  if (!isset($definitions[$template_id])) {
    $template_id = $result ? 'order_mail' : 'order_mail_failure';
  }
  $log_params = [
    'id' => $params['id'],
    'to_email' => $event
      ->getMessage()['to'],
  ];
  $log_storage
    ->generate($params['order'], $template_id, $log_params)
    ->save();
}