Google\Cloud\PubSub\Subscription::pull PHP Méthode

pull() public méthode

Example: $messages = $subscription->pull(); foreach ($messages as $message) { echo $message->data(); }
See also: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/pull Pull Subscriptions
public pull ( array $options = [] ) : Generator
$options array [optional] { Configuration Options @type bool $returnImmediately If set, the system will respond immediately, even if no messages are available. Otherwise, wait until new messages are available. @type int $maxMessages Limit the amount of messages pulled. }
Résultat Generator
    public function pull(array $options = [])
    {
        $options['pageToken'] = null;
        $options['returnImmediately'] = isset($options['returnImmediately']) ? $options['returnImmediately'] : false;
        $options['maxMessages'] = isset($options['maxMessages']) ? $options['maxMessages'] : self::MAX_MESSAGES;
        do {
            $response = $this->connection->pull($options + ['subscription' => $this->name]);
            if (isset($response['receivedMessages'])) {
                foreach ($response['receivedMessages'] as $message) {
                    (yield $this->messageFactory($message, $this->connection, $this->projectId, $this->encode));
                }
            }
            // If there's a page token, we'll request the next page.
            $options['pageToken'] = isset($response['nextPageToken']) ? $response['nextPageToken'] : null;
        } while ($options['pageToken']);
    }

Usage Example

 public function testPullPaged()
 {
     $messages = ['receivedMessages' => [['foo' => 'bar'], ['foo' => 'bat']], 'nextPageToken' => 'foo'];
     $this->connection->pull(Argument::that(function ($args) {
         if ($args['foo'] !== 'bar') {
             return false;
         }
         if ($args['returnImmediately'] !== true) {
             return false;
         }
         if ($args['maxMessages'] !== 2) {
             return false;
         }
         if (!in_array($args['pageToken'], [null, 'foo'])) {
             return false;
         }
         return true;
     }))->willReturn($messages)->shouldBeCalledTimes(3);
     $subscription = new Subscription($this->connection->reveal(), 'subscription-name', 'topic-name', 'project-id');
     $result = $subscription->pull(['foo' => 'bar', 'returnImmediately' => true, 'maxMessages' => 2]);
     $this->assertInstanceOf(Generator::class, $result);
     // enumerate the iterator and kill after it loops twice.
     $arr = [];
     $i = 0;
     foreach ($result as $message) {
         $i++;
         $arr[] = $message;
         if ($i == 6) {
             break;
         }
     }
     $this->assertEquals(6, count($arr));
 }