You are here

public function PushNotificationsBroadcasterApns::sendBroadcast in Push Notifications 8

Send the broadcast message.

Throws

\Exception Array of tokens and payload necessary to send out a broadcast.

Overrides PushNotificationsBroadcasterInterface::sendBroadcast

File

src/PushNotificationsBroadcasterApns.php, line 194
Contains \Drupal\push_notifications\PushNotificationsBroadcasterApns.

Class

PushNotificationsBroadcasterApns
Broadcasts Android messages.

Namespace

Drupal\push_notifications

Code

public function sendBroadcast() {
  if (empty($this->tokens) || empty($this->payload)) {
    throw new \Exception('No tokens or payload set.');
  }

  // JSON-encode the payload.
  $payload = json_encode($this->payload);

  // Send a push notification to every recipient.
  $stream_counter = 0;
  foreach ($this->tokens as $token) {

    // Open an apns connection, if necessary.
    if ($stream_counter == 0) {
      $this
        ->openConnection();
    }
    $stream_counter++;
    $this->countAttempted++;
    $apns_message = chr(0) . chr(0) . chr(32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;

    // Write the payload to the currently active streaming connection.
    $success = fwrite($this->apns, $apns_message);
    if ($success) {
      $this->countSuccess++;
    }
    elseif ($success == 0 || $success == FALSE || $success < strlen($apns_message)) {
      \Drupal::logger('push_notifications')
        ->notice("APNS message could not be sent. Token: @token. fwrite returned @success_message", array(
        '@token' => $token,
        '@success_message' => $success,
      ));
    }

    // Reset the stream counter if no more messages should
    // be sent with the current stream context.
    // This results in the generation of a new stream context
    // at the beginning of this loop.
    if ($stream_counter >= $this->config
      ->get('stream_context_limit')) {
      $stream_counter = 0;
      if (is_resource($this->apns)) {
        fclose($this->apns);
      }
    }
  }

  // Close the apns connection if it hasn't already been closed.
  // Need to check if $apns is a resource, as pointer will not
  // be closed by fclose.
  if (is_resource($this->apns)) {
    fclose($this->apns);
  }

  // Mark success as true.
  $this->success = TRUE;
}