You are here

public function MessageQueueManager::sendMessage in Courier 8

Same name and namespace in other branches
  1. 2.x src/Service/MessageQueueManager.php \Drupal\courier\Service\MessageQueueManager::sendMessage()

Attempts to send the messages in the message queue item.

Attempts will halt as soon as a message is sent successfully, then the message queue item will be deleted.

Parameters

\Drupal\courier\MessageQueueItemInterface $mqi: A message queue item.

Return value

\Drupal\courier\ChannelInterface|FALSE The message that was sent, or FALSE if all messages failed to send.

Overrides MessageQueueManagerInterface::sendMessage

File

src/Service/MessageQueueManager.php, line 43

Class

MessageQueueManager
The message queue manager.

Namespace

Drupal\courier\Service

Code

public function sendMessage(MessageQueueItemInterface $mqi) {
  $options = $mqi
    ->getOptions();
  $channel_options = array_key_exists('channels', $options) ? $options['channels'] : [];
  unset($options['channels']);

  // Instead of iterating over messages, get the identity' channel preferences
  // again. This ensures preference order is up to date since significant time
  // may have passed since adding to queue.
  $channels = $this->identityChannelManager
    ->getChannelsForIdentity($mqi
    ->getIdentity());
  $messages = [];
  foreach ($channels as $channel) {
    if ($message = $mqi
      ->getMessage($channel)) {
      $messages[] = $message;
    }
  }

  /** @var \Drupal\courier\ChannelInterface[] $messages */
  foreach ($messages as $message) {
    $message_options = $options;

    // Transform options based on channel.
    $channel = $message
      ->getEntityTypeId();
    if (array_key_exists($channel, $channel_options)) {
      $message_options = array_merge($message_options, $channel_options[$channel]);
    }
    $t_args = [
      '@channel' => $channel,
      '@identity' => $mqi
        ->getIdentity()
        ->label(),
    ];
    try {
      $message::sendMessages([
        $message,
      ], $message_options);
      $this->logger
        ->info('Successfully sent @channel to @identity', $t_args);
      $mqi
        ->delete();
      return $message;
    } catch (\Exception $e) {
      $t_args['@exception'] = $e
        ->getMessage();
      $this->logger
        ->warning('Failed to send @channel to @identity: @exception', $t_args);
      continue;
    }
    break;
  }
  return FALSE;
}