Cloud PubSub V1 Client - Class SubscriberClient (1.45.2)

Reference documentation and code samples for the Cloud PubSub V1 Client class SubscriberClient.

Service Description: The service that an application uses to manipulate subscriptions and to consume messages from a subscription via the Pull method or by establishing a bi-directional stream using the StreamingPull method.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:

$subscriberClient = new SubscriberClient();
try {
    $formattedSubscription = $subscriberClient->subscriptionName('[PROJECT]', '[SUBSCRIPTION]');
    $ackIds = [];
    $subscriberClient->acknowledge($formattedSubscription, $ackIds);
} finally {
    $subscriberClient->close();
}

Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.

This service has a new (beta) implementation. See Google\Cloud\PubSub\V1\Client\SubscriberClient to use the new surface.

Namespace

Google \ Cloud \ PubSub \ V1

Methods

__construct

Constructor.

Parameters
NameDescription
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage: In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.

↳ transport string|TransportInterface

The transport used for executing network requests. May be either the string rest or grpc. Defaults to grpc if gRPC support is detected on the system. Advanced usage: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.

acknowledge

Acknowledges the messages associated with the ack_ids in the AcknowledgeRequest. The Pub/Sub system can remove the relevant messages from the subscription.

Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error.

Parameters
NameDescription
subscription string

Required. The subscription whose message is being acknowledged. Format is projects/{project}/subscriptions/{sub}.

ackIds string[]

Required. The acknowledgment ID for the messages being acknowledged that was returned by the Pub/Sub system in the Pull response. Must not be empty.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The subscription whose message is being acknowledged.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 * @param string $ackIdsElement         The acknowledgment ID for the messages being acknowledged that
 *                                      was returned by the Pub/Sub system in the `Pull` response. Must not be
 *                                      empty.
 */
function acknowledge_sample(string $formattedSubscription, string $ackIdsElement): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $ackIds = [$ackIdsElement,];

    // Call the API and handle any network failures.
    try {
        $subscriberClient->acknowledge($formattedSubscription, $ackIds);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');
    $ackIdsElement = '[ACK_IDS]';

    acknowledge_sample($formattedSubscription, $ackIdsElement);
}

createSnapshot

Creates a snapshot from the requested subscription. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.

If the snapshot already exists, returns ALREADY_EXISTS. If the requested subscription doesn't exist, returns NOT_FOUND. If the backlog in the subscription is too old -- and the resulting snapshot would expire in less than 1 hour -- then FAILED_PRECONDITION is returned. See also the Snapshot.expire_time field. If the name is not provided in the request, the server will assign a random name for this snapshot on the same project as the subscription, conforming to the resource name format. The generated name is populated in the returned Snapshot object. Note that for REST API requests, you must specify a name in the request.

Parameters
NameDescription
name string

Required. User-provided name for this snapshot. If the name is not provided in the request, the server will assign a random name for this snapshot on the same project as the subscription. Note that for REST API requests, you must specify a name. See the resource name rules. Format is projects/{project}/snapshots/{snap}.

subscription string

Required. The subscription whose backlog the snapshot retains. Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the subscription. More precisely, this is defined as the messages in the subscription's backlog that are unacknowledged upon the successful completion of the CreateSnapshot request; as well as: (b) Any messages published to the subscription's topic following the successful completion of the CreateSnapshot request. Format is projects/{project}/subscriptions/{sub}.

optionalArgs array

Optional.

↳ labels array

See Creating and managing labels.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Snapshot
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\Snapshot;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedName         User-provided name for this snapshot. If the name is not provided
 *                                      in the request, the server will assign a random name for this snapshot on
 *                                      the same project as the subscription. Note that for REST API requests, you
 *                                      must specify a name.  See the [resource name
 *                                      rules](https://cloud.google.com/pubsub/docs/admin#resource_names). Format
 *                                      is `projects/{project}/snapshots/{snap}`. Please see
 *                                      {@see SubscriberClient::snapshotName()} for help formatting this field.
 * @param string $formattedSubscription The subscription whose backlog the snapshot retains.
 *                                      Specifically, the created snapshot is guaranteed to retain:
 *                                      (a) The existing backlog on the subscription. More precisely, this is
 *                                      defined as the messages in the subscription's backlog that are
 *                                      unacknowledged upon the successful completion of the
 *                                      `CreateSnapshot` request; as well as:
 *                                      (b) Any messages published to the subscription's topic following the
 *                                      successful completion of the CreateSnapshot request.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 */
function create_snapshot_sample(string $formattedName, string $formattedSubscription): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var Snapshot $response */
        $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = SubscriberClient::snapshotName('[PROJECT]', '[SNAPSHOT]');
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');

    create_snapshot_sample($formattedName, $formattedSubscription);
}

createSubscription

Creates a subscription to a given topic. See the resource name rules.

If the subscription already exists, returns ALREADY_EXISTS. If the corresponding topic doesn't exist, returns NOT_FOUND.

If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the resource name format. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request.

Parameters
NameDescription
name string

Required. The name of the subscription. It must have the format "projects/{project}/subscriptions/{subscription}". {subscription} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9]), dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog".

topic string

Required. The name of the topic from which this subscription is receiving messages. Format is projects/{project}/topics/{topic}. The value of this field will be _deleted-topic_ if the topic has been deleted.

optionalArgs array

Optional.

↳ pushConfig PushConfig

If push delivery is used with this subscription, this field is used to configure it.

↳ bigqueryConfig BigQueryConfig

If delivery to BigQuery is used with this subscription, this field is used to configure it.

↳ cloudStorageConfig CloudStorageConfig

If delivery to Google Cloud Storage is used with this subscription, this field is used to configure it.

↳ ackDeadlineSeconds int

The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ModifyAckDeadline with the corresponding ack_id if using non-streaming pull or send the ack_id in a StreamingModifyAckDeadlineRequest if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message.

↳ retainAckedMessages bool

Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the message_retention_duration window. This must be true if you would like to Seek to a timestamp in the past to replay previously-acknowledged messages.

↳ messageRetentionDuration Duration

How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If retain_acked_messages is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a Seek can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes.

↳ labels array

See Creating and managing labels.

↳ enableMessageOrdering bool

If true, messages published with the same ordering_key in PubsubMessage will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order.

↳ expirationPolicy ExpirationPolicy

A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If expiration_policy is not set, a default policy with ttl of 31 days will be used. The minimum allowed value for expiration_policy.ttl is 1 day. If expiration_policy is set, but expiration_policy.ttl is not set, the subscription never expires.

↳ filter string

An expression written in the Pub/Sub filter language. If non-empty, then only PubsubMessages whose attributes field matches the filter are delivered on this subscription. If empty, then no messages are filtered out.

↳ deadLetterPolicy DeadLetterPolicy

A policy that specifies the conditions for dead lettering messages in this subscription. If dead_letter_policy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this subscription.

↳ retryPolicy RetryPolicy

A policy that specifies how Pub/Sub retries message delivery for this subscription. If not set, the default retry policy is applied. This generally implies that messages will be retried as soon as possible for healthy subscribers. RetryPolicy will be triggered on NACKs or acknowledgement deadline exceeded events for a given message.

↳ detached bool

Indicates whether the subscription is detached from its topic. Detached subscriptions don't receive messages from their topic and don't retain any backlog. Pull and StreamingPull requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to the endpoint will not be made.

↳ enableExactlyOnceDelivery bool

If true, Pub/Sub provides the following guarantees for the delivery of a message with a given value of message_id on this subscription: * The message sent to a subscriber is guaranteed not to be resent before the message's acknowledgement deadline expires. * An acknowledged message will not be resent to a subscriber. Note that subscribers may still receive multiple copies of a message when enable_exactly_once_delivery is true if the message was published multiple times by a publisher client. These copies are considered distinct by Pub/Sub and have distinct message_id values.

↳ topicMessageRetentionDuration Duration

Output only. Indicates the minimum duration for which a message is retained after it is published to the subscription's topic. If this field is set, messages published to the subscription's topic in the last topic_message_retention_duration are always available to subscribers. See the message_retention_duration field in Topic. This field is set only in responses from the server; it is ignored if it is set in any requests.

↳ state int

Output only. An output-only field indicating whether or not the subscription can receive messages. For allowed values, use constants defined on Google\Cloud\PubSub\V1\Subscription\State

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Subscription
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;
use Google\Cloud\PubSub\V1\Subscription;

/**
 * @param string $name           The name of the subscription. It must have the format
 *                               `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must
 *                               start with a letter, and contain only letters (`[A-Za-z]`), numbers
 *                               (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`),
 *                               plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters
 *                               in length, and it must not start with `"goog"`.
 * @param string $formattedTopic The name of the topic from which this subscription is receiving
 *                               messages. Format is `projects/{project}/topics/{topic}`. The value of this
 *                               field will be `_deleted-topic_` if the topic has been deleted. Please see
 *                               {@see SubscriberClient::topicName()} for help formatting this field.
 */
function create_subscription_sample(string $name, string $formattedTopic): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var Subscription $response */
        $response = $subscriberClient->createSubscription($name, $formattedTopic);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $name = '[NAME]';
    $formattedTopic = SubscriberClient::topicName('[PROJECT]', '[TOPIC]');

    create_subscription_sample($name, $formattedTopic);
}

deleteSnapshot

Removes an existing snapshot. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.

When the snapshot is deleted, all messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new one may be created with the same name, but the new one has no association with the old snapshot or its subscription, unless the same subscription is specified.

Parameters
NameDescription
snapshot string

Required. The name of the snapshot to delete. Format is projects/{project}/snapshots/{snap}.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSnapshot The name of the snapshot to delete.
 *                                  Format is `projects/{project}/snapshots/{snap}`. Please see
 *                                  {@see SubscriberClient::snapshotName()} for help formatting this field.
 */
function delete_snapshot_sample(string $formattedSnapshot): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        $subscriberClient->deleteSnapshot($formattedSnapshot);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSnapshot = SubscriberClient::snapshotName('[PROJECT]', '[SNAPSHOT]');

    delete_snapshot_sample($formattedSnapshot);
}

deleteSubscription

Deletes an existing subscription. All messages retained in the subscription are immediately dropped. Calls to Pull after deletion will return NOT_FOUND. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription or its topic unless the same topic is specified.

Parameters
NameDescription
subscription string

Required. The subscription to delete. Format is projects/{project}/subscriptions/{sub}.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The subscription to delete.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 */
function delete_subscription_sample(string $formattedSubscription): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        $subscriberClient->deleteSubscription($formattedSubscription);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');

    delete_subscription_sample($formattedSubscription);
}

getSnapshot

Gets the configuration details of a snapshot. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.

Parameters
NameDescription
snapshot string

Required. The name of the snapshot to get. Format is projects/{project}/snapshots/{snap}.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Snapshot
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\Snapshot;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSnapshot The name of the snapshot to get.
 *                                  Format is `projects/{project}/snapshots/{snap}`. Please see
 *                                  {@see SubscriberClient::snapshotName()} for help formatting this field.
 */
function get_snapshot_sample(string $formattedSnapshot): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var Snapshot $response */
        $response = $subscriberClient->getSnapshot($formattedSnapshot);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSnapshot = SubscriberClient::snapshotName('[PROJECT]', '[SNAPSHOT]');

    get_snapshot_sample($formattedSnapshot);
}

getSubscription

Gets the configuration details of a subscription.

Parameters
NameDescription
subscription string

Required. The name of the subscription to get. Format is projects/{project}/subscriptions/{sub}.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Subscription
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;
use Google\Cloud\PubSub\V1\Subscription;

/**
 * @param string $formattedSubscription The name of the subscription to get.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 */
function get_subscription_sample(string $formattedSubscription): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var Subscription $response */
        $response = $subscriberClient->getSubscription($formattedSubscription);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');

    get_subscription_sample($formattedSubscription);
}

listSnapshots

Lists the existing snapshots. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.

Parameters
NameDescription
project string

Required. The name of the project in which to list snapshots. Format is projects/{project-id}.

optionalArgs array

Optional.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\PubSub\V1\Snapshot;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedProject The name of the project in which to list snapshots.
 *                                 Format is `projects/{project-id}`. Please see
 *                                 {@see SubscriberClient::projectName()} for help formatting this field.
 */
function list_snapshots_sample(string $formattedProject): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $subscriberClient->listSnapshots($formattedProject);

        /** @var Snapshot $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProject = SubscriberClient::projectName('[PROJECT]');

    list_snapshots_sample($formattedProject);
}

listSubscriptions

Lists matching subscriptions.

Parameters
NameDescription
project string

Required. The name of the project in which to list subscriptions. Format is projects/{project-id}.

optionalArgs array

Optional.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\PubSub\V1\SubscriberClient;
use Google\Cloud\PubSub\V1\Subscription;

/**
 * @param string $formattedProject The name of the project in which to list subscriptions.
 *                                 Format is `projects/{project-id}`. Please see
 *                                 {@see SubscriberClient::projectName()} for help formatting this field.
 */
function list_subscriptions_sample(string $formattedProject): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $subscriberClient->listSubscriptions($formattedProject);

        /** @var Subscription $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedProject = SubscriberClient::projectName('[PROJECT]');

    list_subscriptions_sample($formattedProject);
}

modifyAckDeadline

Modifies the ack deadline for a specific message. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted. Note that this does not modify the subscription-level ackDeadlineSeconds used for subsequent messages.

Parameters
NameDescription
subscription string

Required. The name of the subscription. Format is projects/{project}/subscriptions/{sub}.

ackIds string[]

Required. List of acknowledgment IDs.

ackDeadlineSeconds int

Required. The new ack deadline with respect to the time this request was sent to the Pub/Sub system. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero might immediately make the message available for delivery to another subscriber client. This typically results in an increase in the rate of message redeliveries (that is, duplicates). The minimum deadline you can specify is 0 seconds. The maximum deadline you can specify is 600 seconds (10 minutes).

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The name of the subscription.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 * @param string $ackIdsElement         List of acknowledgment IDs.
 * @param int    $ackDeadlineSeconds    The new ack deadline with respect to the time this request was
 *                                      sent to the Pub/Sub system. For example, if the value is 10, the new ack
 *                                      deadline will expire 10 seconds after the `ModifyAckDeadline` call was
 *                                      made. Specifying zero might immediately make the message available for
 *                                      delivery to another subscriber client. This typically results in an
 *                                      increase in the rate of message redeliveries (that is, duplicates).
 *                                      The minimum deadline you can specify is 0 seconds.
 *                                      The maximum deadline you can specify is 600 seconds (10 minutes).
 */
function modify_ack_deadline_sample(
    string $formattedSubscription,
    string $ackIdsElement,
    int $ackDeadlineSeconds
): void {
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $ackIds = [$ackIdsElement,];

    // Call the API and handle any network failures.
    try {
        $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');
    $ackIdsElement = '[ACK_IDS]';
    $ackDeadlineSeconds = 0;

    modify_ack_deadline_sample($formattedSubscription, $ackIdsElement, $ackDeadlineSeconds);
}

modifyPushConfig

Modifies the PushConfig for a specified subscription.

This may be used to change a push subscription to a pull one (signified by an empty PushConfig) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the PushConfig.

Parameters
NameDescription
subscription string

Required. The name of the subscription. Format is projects/{project}/subscriptions/{sub}.

pushConfig Google\Cloud\PubSub\V1\PushConfig

Required. The push configuration for future deliveries.

An empty pushConfig indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription if Pull or StreamingPull is not called.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\PushConfig;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The name of the subscription.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 */
function modify_push_config_sample(string $formattedSubscription): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $pushConfig = new PushConfig();

    // Call the API and handle any network failures.
    try {
        $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');

    modify_push_config_sample($formattedSubscription);
}

pull

Pulls messages from the server.

Parameters
NameDescription
subscription string

Required. The subscription from which messages should be pulled. Format is projects/{project}/subscriptions/{sub}.

maxMessages int

Required. The maximum number of messages to return for this request. Must be a positive integer. The Pub/Sub system may return fewer than the number specified.

optionalArgs array

Optional.

↳ returnImmediately bool

Optional. If this field set to true, the system will respond immediately even if it there are no messages available to return in the Pull response. Otherwise, the system may wait (for a bounded amount of time) until at least one message is available, rather than returning no messages. Warning: setting this field to true is discouraged because it adversely impacts the performance of Pull operations. We recommend that users do not set this field.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\PullResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\PullResponse;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The subscription from which messages should be pulled.
 *                                      Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 * @param int    $maxMessages           The maximum number of messages to return for this request. Must
 *                                      be a positive integer. The Pub/Sub system may return fewer than the number
 *                                      specified.
 */
function pull_sample(string $formattedSubscription, int $maxMessages): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var PullResponse $response */
        $response = $subscriberClient->pull($formattedSubscription, $maxMessages);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');
    $maxMessages = 0;

    pull_sample($formattedSubscription, $maxMessages);
}

seek

Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.

Parameters
NameDescription
subscription string

Required. The subscription to affect.

optionalArgs array

Optional.

↳ time Timestamp

The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of message_retention_duration and retain_acked_messages). For example, if time corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored.

↳ snapshot string

The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is projects/{project}/snapshots/{snap}.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\SeekResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SeekResponse;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription The subscription to affect. Please see
 *                                      {@see SubscriberClient::subscriptionName()} for help formatting this field.
 */
function seek_sample(string $formattedSubscription): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var SeekResponse $response */
        $response = $subscriberClient->seek($formattedSubscription);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');

    seek_sample($formattedSubscription);
}

streamingPull

Establishes a stream with the server, which sends messages down to the client. The client streams acknowledgements and ack deadline modifications back to the server. The server will close the stream and return the status on any error. The server may close the stream with status UNAVAILABLE to reassign server-side resources, in which case, the client should re-establish the stream. Flow control can be achieved by configuring the underlying RPC channel.

Parameters
NameDescription
optionalArgs array

Optional.

↳ timeoutMillis int

Timeout to use for this call.

Returns
TypeDescription
Google\ApiCore\BidiStream
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\BidiStream;
use Google\Cloud\PubSub\V1\StreamingPullRequest;
use Google\Cloud\PubSub\V1\StreamingPullResponse;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $formattedSubscription    The subscription for which to initialize the new stream. This
 *                                         must be provided in the first request on the stream, and must not be set in
 *                                         subsequent requests from client to server.
 *                                         Format is `projects/{project}/subscriptions/{sub}`. Please see
 *                                         {@see SubscriberClient::subscriptionName()} for help formatting this field.
 * @param int    $streamAckDeadlineSeconds The ack deadline to use for the stream. This must be provided in
 *                                         the first request on the stream, but it can also be updated on subsequent
 *                                         requests from client to server. The minimum deadline you can specify is 10
 *                                         seconds. The maximum deadline you can specify is 600 seconds (10 minutes).
 */
function streaming_pull_sample(string $formattedSubscription, int $streamAckDeadlineSeconds): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $request = (new StreamingPullRequest())
        ->setSubscription($formattedSubscription)
        ->setStreamAckDeadlineSeconds($streamAckDeadlineSeconds);

    // Call the API and handle any network failures.
    try {
        /** @var BidiStream $stream */
        $stream = $subscriberClient->streamingPull();
        $stream->writeAll([$request,]);

        /** @var StreamingPullResponse $element */
        foreach ($stream->closeWriteAndReadAll() as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedSubscription = SubscriberClient::subscriptionName('[PROJECT]', '[SUBSCRIPTION]');
    $streamAckDeadlineSeconds = 0;

    streaming_pull_sample($formattedSubscription, $streamAckDeadlineSeconds);
}

updateSnapshot

Updates an existing snapshot. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.

Parameters
NameDescription
snapshot Google\Cloud\PubSub\V1\Snapshot

Required. The updated snapshot object.

updateMask Google\Protobuf\FieldMask

Required. Indicates which fields in the provided snapshot to update. Must be specified and non-empty.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Snapshot
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\Snapshot;
use Google\Cloud\PubSub\V1\SubscriberClient;
use Google\Protobuf\FieldMask;

/**
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function update_snapshot_sample(): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $snapshot = new Snapshot();
    $updateMask = new FieldMask();

    // Call the API and handle any network failures.
    try {
        /** @var Snapshot $response */
        $response = $subscriberClient->updateSnapshot($snapshot, $updateMask);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

updateSubscription

Updates an existing subscription. Note that certain properties of a subscription, such as its topic, are not modifiable.

Parameters
NameDescription
subscription Google\Cloud\PubSub\V1\Subscription

Required. The updated subscription object.

updateMask Google\Protobuf\FieldMask

Required. Indicates which fields in the provided subscription to update. Must be specified and non-empty.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\PubSub\V1\Subscription
Example
use Google\ApiCore\ApiException;
use Google\Cloud\PubSub\V1\SubscriberClient;
use Google\Cloud\PubSub\V1\Subscription;
use Google\Protobuf\FieldMask;

/**
 * @param string $subscriptionName           The name of the subscription. It must have the format
 *                                           `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must
 *                                           start with a letter, and contain only letters (`[A-Za-z]`), numbers
 *                                           (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`),
 *                                           plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters
 *                                           in length, and it must not start with `"goog"`.
 * @param string $formattedSubscriptionTopic The name of the topic from which this subscription is receiving
 *                                           messages. Format is `projects/{project}/topics/{topic}`. The value of this
 *                                           field will be `_deleted-topic_` if the topic has been deleted. Please see
 *                                           {@see SubscriberClient::topicName()} for help formatting this field.
 */
function update_subscription_sample(
    string $subscriptionName,
    string $formattedSubscriptionTopic
): void {
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $subscription = (new Subscription())
        ->setName($subscriptionName)
        ->setTopic($formattedSubscriptionTopic);
    $updateMask = new FieldMask();

    // Call the API and handle any network failures.
    try {
        /** @var Subscription $response */
        $response = $subscriberClient->updateSubscription($subscription, $updateMask);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $subscriptionName = '[NAME]';
    $formattedSubscriptionTopic = SubscriberClient::topicName('[PROJECT]', '[TOPIC]');

    update_subscription_sample($subscriptionName, $formattedSubscriptionTopic);
}

getIamPolicy

Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.

Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.

optionalArgs array

Optional.

↳ options GetPolicyOptions

OPTIONAL: A GetPolicyOptions object for specifying options to GetIamPolicy.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\Policy
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $resource REQUIRED: The resource for which the policy is being requested.
 *                         See the operation documentation for the appropriate value for this field.
 */
function get_iam_policy_sample(string $resource): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Call the API and handle any network failures.
    try {
        /** @var Policy $response */
        $response = $subscriberClient->getIamPolicy($resource);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';

    get_iam_policy_sample($resource);
}

setIamPolicy

Sets the access control policy on the specified resource. Replaces any existing policy.

Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED errors.

Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.

policy Google\Cloud\Iam\V1\Policy

REQUIRED: The complete policy to be applied to the resource. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them.

optionalArgs array

Optional.

↳ updateMask FieldMask

OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: paths: "bindings, etag"

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\Policy
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $resource REQUIRED: The resource for which the policy is being specified.
 *                         See the operation documentation for the appropriate value for this field.
 */
function set_iam_policy_sample(string $resource): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $policy = new Policy();

    // Call the API and handle any network failures.
    try {
        /** @var Policy $response */
        $response = $subscriberClient->setIamPolicy($resource, $policy);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';

    set_iam_policy_sample($resource);
}

testIamPermissions

Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.

Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.

Parameters
NameDescription
resource string

REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.

permissions string[]

The set of permissions to check for the resource. Permissions with wildcards (such as '' or 'storage.') are not allowed. For more information see IAM Overview.

optionalArgs array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Iam\V1\TestIamPermissionsResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Iam\V1\TestIamPermissionsResponse;
use Google\Cloud\PubSub\V1\SubscriberClient;

/**
 * @param string $resource           REQUIRED: The resource for which the policy detail is being requested.
 *                                   See the operation documentation for the appropriate value for this field.
 * @param string $permissionsElement The set of permissions to check for the `resource`. Permissions with
 *                                   wildcards (such as '*' or 'storage.*') are not allowed. For more
 *                                   information see
 *                                   [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
 */
function test_iam_permissions_sample(string $resource, string $permissionsElement): void
{
    // Create a client.
    $subscriberClient = new SubscriberClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $permissions = [$permissionsElement,];

    // Call the API and handle any network failures.
    try {
        /** @var TestIamPermissionsResponse $response */
        $response = $subscriberClient->testIamPermissions($resource, $permissions);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $resource = '[RESOURCE]';
    $permissionsElement = '[PERMISSIONS]';

    test_iam_permissions_sample($resource, $permissionsElement);
}

static::deletedTopicName

Formats a string containing the fully-qualified path to represent a deleted-topic resource.

Returns
TypeDescription
stringThe formatted _deleted-topic_ resource.

static::projectName

Formats a string containing the fully-qualified path to represent a project resource.

Parameter
NameDescription
project string
Returns
TypeDescription
stringThe formatted project resource.

static::projectTopicName

Formats a string containing the fully-qualified path to represent a project_topic resource.

Parameters
NameDescription
project string
topic string
Returns
TypeDescription
stringThe formatted project_topic resource.

static::snapshotName

Formats a string containing the fully-qualified path to represent a snapshot resource.

Parameters
NameDescription
project string
snapshot string
Returns
TypeDescription
stringThe formatted snapshot resource.

static::subscriptionName

Formats a string containing the fully-qualified path to represent a subscription resource.

Parameters
NameDescription
project string
subscription string
Returns
TypeDescription
stringThe formatted subscription resource.

static::topicName

Formats a string containing the fully-qualified path to represent a topic resource.

Parameters
NameDescription
project string
topic string
Returns
TypeDescription
stringThe formatted topic resource.

static::parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • deletedTopic: deleted-topic
  • project: projects/{project}
  • projectTopic: projects/{project}/topics/{topic}
  • snapshot: projects/{project}/snapshots/{snapshot}
  • subscription: projects/{project}/subscriptions/{subscription}
  • topic: projects/{project}/topics/{topic}

The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.

Parameters
NameDescription
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
TypeDescription
arrayAn associative array from name component IDs to component values.

Constants

SERVICE_NAME

Value: 'google.pubsub.v1.Subscriber'

The name of the service.

SERVICE_ADDRESS

Value: 'pubsub.googleapis.com'

The default address of the service.

DEFAULT_SERVICE_PORT

Value: 443

The default port of the service.

CODEGEN_NAME

Value: 'gapic'

The name of the code generator, to be included in the agent header.