You are here

public function DefaultSmsProvider::queue in SMS Framework 2.x

Same name and namespace in other branches
  1. 8 src/Provider/DefaultSmsProvider.php \Drupal\sms\Provider\DefaultSmsProvider::queue()
  2. 2.1.x src/Provider/DefaultSmsProvider.php \Drupal\sms\Provider\DefaultSmsProvider::queue()

Queue a SMS message for sending or receiving.

Parameters

\Drupal\sms\Message\SmsMessageInterface $sms_message: A SMS message.

Return value

\Drupal\sms\Entity\SmsMessageInterface[] The queued messages. A single message may be transformed into many.

Throws

\Drupal\sms\Exception\SmsDirectionException Thrown if no direction is set for the message.

\Drupal\sms\Exception\RecipientRouteException Thrown if no gateway could be determined for the message.

Overrides SmsProviderInterface::queue

File

src/Provider/DefaultSmsProvider.php, line 47

Class

DefaultSmsProvider
The SMS provider that provides default messaging functionality.

Namespace

Drupal\sms\Provider

Code

public function queue(SmsMessageInterface $sms_message) {
  if (!$sms_message
    ->getDirection()) {
    throw new SmsDirectionException('Missing direction for message.');
  }
  $sms_messages = $this
    ->dispatchEvent(SmsEvents::MESSAGE_PRE_PROCESS, [
    $sms_message,
  ])
    ->getMessages();
  $sms_messages = $this
    ->dispatchEvent(SmsEvents::MESSAGE_QUEUE_PRE_PROCESS, $sms_messages)
    ->getMessages();
  foreach ($sms_messages as $gateway_id => &$sms_message) {

    // Tag so SmsEvents::MESSAGE_PRE_PROCESS is not dispatched again.
    $sms_message
      ->setOption('_skip_preprocess_event', TRUE);

    // Validate SMS message entities.
    if ($sms_message instanceof SmsMessageEntityInterface) {
      $errors = [];
      $violations = $sms_message
        ->validate();
      foreach ($violations
        ->getFieldNames() as $field_name) {
        foreach ($violations
          ->getByField($field_name) as $violation) {
          $errors[] = "[{$field_name}]: " . strip_tags((string) $violation
            ->getMessage());
        }
      }
      if ($errors) {
        throw new SmsException(sprintf('Can not queue SMS message because there are %s validation error(s): %s', count($errors), implode(' ', $errors)));
      }
    }
    if ($sms_message
      ->getGateway()
      ->getSkipQueue()) {
      switch ($sms_message
        ->getDirection()) {
        case Direction::INCOMING:
          $this
            ->incoming($sms_message);
          break;
        case Direction::OUTGOING:
          $this
            ->send($sms_message);
          break;
      }
      continue;
    }
    $sms_message = SmsMessage::convertFromSmsMessage($sms_message);
    $sms_message
      ->save();
  }

  // Queue has different post-process events because there is no result.
  return $this
    ->dispatchEvent(SmsEvents::MESSAGE_QUEUE_POST_PROCESS, $sms_messages)
    ->getMessages();
}