Example #1
0
 /**
  * @param array $batch
  *
  * @return string[] A list of message IDs indexed by the same keys as $batch
  * @throws \Google_Service_Exception
  */
 public function pushBatch(array $batch)
 {
     if (count($batch) < 1) {
         return null;
     }
     $toPush = [];
     $messageKeys = array_keys($batch);
     foreach ($batch as $rawMsg) {
         $msg = new \Google_Service_Pubsub_PubsubMessage();
         $msg->setData(base64_encode(json_encode($rawMsg)));
         $toPush[] = $msg;
     }
     $topicPath = $this->_getTopic()->getName();
     $body = new \Google_Service_Pubsub_PublishBatchRequest();
     $body->setTopic($topicPath);
     $body->setMessages($toPush);
     $messageIds = [];
     $retry = true;
     while ($retry) {
         try {
             $retry = false;
             $result = $this->_getPubSubService()->topics->publishBatch($body);
             $returnedIds = $result->getMessageIds();
             $i = 0;
             foreach ($messageKeys as $key) {
                 $messageIds[$key] = $returnedIds[$i];
                 $i++;
             }
         } catch (\Google_Service_Exception $e) {
             if ($this->_isMissingResourceError($e, $topicPath)) {
                 $retry = true;
                 $this->_createTopic();
             } else {
                 throw $e;
             }
         }
     }
     return $messageIds;
 }
Example #2
0
    $request = json_decode($json, true);
    if (!isset($request['message']['data']) || !($message = base64_decode($request['message']['data']))) {
        return new Response('', 400);
    }
    // Store the received message in datastore
    // For a more complete demo of datastore,
    // @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/datastore
    $datastore = new DatastoreHelper($client, $projectId);
    $datastore->storeMessage($message);
    return new Response();
});
$app->post('/send_message', function () use($app) {
    // send the pubsub message
    if ($messageText = $app['request']->get('message')) {
        /** @var Google_Client $client */
        $client = $app['google_client'];
        $projectName = sprintf('projects/%s', $app['project_id']);
        $topicName = sprintf('%s/topics/%s', $projectName, $app['topic']);
        $pubsub = new Google_Service_Pubsub($client);
        // create pubsub message object
        $message = new Google_Service_Pubsub_PubsubMessage();
        $message->setData(base64_encode($messageText));
        // create pubsub request
        $request = new Google_Service_Pubsub_PublishRequest();
        $request->setMessages([$message]);
        $pubsub->projects_topics->publish($topicName, $request);
        return new Response('', 204);
    }
    return new Response('', 400);
});
return $app;