# Cloud Storage Client - Class StorageClient (2.3.0)

2.3.0 (latest) 2.2.0 2.1.0 2.0.0 1.51.0 1.50.0 1.49.2 1.48.7 1.47.0 1.46.0 1.45.0 1.44.0 1.43.1 1.42.1 1.41.4 1.37.0 1.36.1 1.35.0 1.34.0 1.33.4 1.32.0 1.31.2 1.30.3 Reference documentation and code samples for the Cloud Storage Client class StorageClient.

Google Cloud Storage allows you to store and retrieve data on Google's
infrastructure. Find more information at the
[Google Cloud Storage API docs](https://developers.google.com/storage).

Example:

    use Google\Cloud\Storage\StorageClient;

    $storage = new StorageClient();

## Namespace

Google \\ Cloud \\ Storage

## Methods

### __construct

Create a Storage client.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `config` | `array` Configuration options. |
| `↳ apiEndpoint` | `string` The hostname with optional port to use in place of the default service endpoint. Example: `foobar.com` or `foobar.com:1234`. |
| `↳ projectId` | `string` The project ID from the Google Developer's Console. |
| `↳ authCache` | `Psr\Cache\CacheItemPoolInterface` A cache used storing access tokens. **Defaults to** a simple in memory implementation. |
| `↳ authCacheOptions` | `array` Cache configuration options. |
| `↳ authHttpHandler` | `callable` A handler used to deliver Psr7 requests specifically for authentication. |
| `↳ credentialsFetcher` | `https://docs.cloud.google.com/php/docs/reference/auth/latest/FetchAuthTokenInterface.html` A credentials fetcher instance. |
| `↳ httpHandler` | `callable` A handler used to deliver Psr7 requests. Only valid for requests sent over REST. |
| `↳ keyFile` | `array` \[DEPRECATED\] This option is being deprecated because of a potential security risk. This option does not validate the credential configuration. The security risk occurs when a credential configuration is accepted from a source that is not under your control and used without validation on your side. If you know that you will be loading credential configurations of a specific type, it is recommended to create the credentials directly and configure them using the `credentialsFetcher` option instead. `use Google\Auth\Credentials\ServiceAccountCredentials; $credentialsFetcher = new ServiceAccountCredentials($scopes, $json); $creds = new StorageClient(['credentialsFetcher' => $creds]);` This will ensure that an unexpected credential type with potential for malicious intent is not loaded unintentionally. You might still have to do validation for certain credential types. If you are loading your credential configuration from an untrusted source and have not mitigated the risks (e.g. by validating the configuration yourself), make these changes as soon as possible to prevent security risks to your environment. Regardless of the method used, it is always your responsibility to validate configurations received from external sources. @see <https://cloud.google.com/docs/authentication/external/externally-sourced-credentials> |
| `↳ keyFilePath` | `string` \[DEPRECATED\] This option is being deprecated because of a potential security risk. This option does not validate the credential configuration. The security risk occurs when a credential configuration is accepted from a source that is not under your control and used without validation on your side. If you know that you will be loading credential configurations of a specific type, it is recommended to create the credentials directly and configure them using the `credentialsFetcher` option instead. `use Google\Auth\Credentials\ServiceAccountCredentials; $credentialsFetcher = new ServiceAccountCredentials($scopes, $json); $creds = new StorageClient(['credentialsFetcher' => $creds]);` This will ensure that an unexpected credential type with potential for malicious intent is not loaded unintentionally. You might still have to do validation for certain credential types. If you are loading your credential configuration from an untrusted source and have not mitigated the risks (e.g. by validating the configuration yourself), make these changes as soon as possible to prevent security risks to your environment. Regardless of the method used, it is always your responsibility to validate configurations received from external sources. @see <https://cloud.google.com/docs/authentication/external/externally-sourced-credentials> |
| `↳ requestTimeout` | `float` Seconds to wait before timing out the request. **Defaults to** `0` with REST and `60` with gRPC. |
| `↳ retries` | `int` Number of retries for a failed request. **Defaults to** `3`. |
| `↳ retryStrategy` | `string` Retry strategy to signify that we never want to retry an operation even if the error is retryable. **Defaults to** `StorageClient::RETRY_IDEMPOTENT`. |
| `↳ restDelayFunction` | `callable` Executes a delay, defaults to utilizing `usleep`. Function signature should match: `function (int $delay) : void`. |
| `↳ restCalcDelayFunction` | `callable` Sets the conditions for determining how long to wait between attempts to retry. Function signature should match: `function (int $attempt) : int`. |
| `↳ restRetryFunction` | `callable` Sets the conditions for whether or not a request should attempt to retry. Function signature should match: `function (\Exception $ex) : bool`. |
| `↳ restRetryListener` | `callable` Runs after the restRetryFunction. This might be used to simply consume the exception and $arguments b/w retries. This returns the new $arguments thus allowing modification on demand for $arguments. For ex: changing the headers in b/w retries. |
| `↳ scopes` | `array` Scopes to be used for the request. |
| `↳ quotaProject` | `string` Specifies a user project to bill for access charges associated with the request. |

### bucket

Lazily instantiates a bucket.

There are no network requests made at this point. To see the operations
that can be performed on a bucket please see [Bucket](https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket).

If `$userProject` is set to true, the current project ID (used to
instantiate the client) will be billed for all requests. If
`$userProject` is a project ID, given as a string, that project
will be billed for all requests. This only has an effect when the bucket
is not owned by the current or given project ID.

Example:

    $bucket = $storage->bucket('my-bucket');

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `name` | `string` The name of the bucket to request. |
| `userProject` | `string|bool` If true, the current Project ID will be used. If a string, that string will be used as the userProject argument, and that project will be billed for the request. **Defaults to** `false`. |
| `options` | `array` Configuration Options. |
| `↳ softDeleted` | `bool` If set to true, only soft-deleted bucket versions are listed as distinct results in order of bucket name and generation number. The default value is false. |
| `↳ generation` | `string` If present, selects a specific soft-deleted version of this bucket instead of the live version. This parameter is required if softDeleted is set to true. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket` |   |

### buckets

See also:

- [Buckets list API documentation.](https://cloud.google.com/storage/docs/json_api/v1/buckets/list)

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `options` | `array` Configuration options. |
| `↳ maxResults` | `int` Maximum number of results to return per requested page. |
| `↳ resultLimit` | `int` Limit the number of results returned in total. **Defaults to** `0` (return all results). |
| `↳ pageToken` | `string` A previously-returned page token used to resume the loading of results from a specific point. |
| `↳ prefix` | `string` Filter results with this prefix. |
| `↳ projection` | `string` Determines which properties to return. May be either 'full' or 'noAcl'. |
| `↳ fields` | `string` Selector which will cause the response to only return the specified fields. |
| `↳ userProject` | `string` If set, this is the ID of the project which will be billed for the request. |
| `↳ softDeleted` | `bool` If set to true, only soft-deleted bucket versions are listed as distinct results in order of bucket name and generation number. The default value is false. |
| `↳ bucketUserProject` | `bool` If true, each returned instance will have `$userProject` set to the value of `$options.userProject`. If false, `$options.userProject` will be used ONLY for the listBuckets operation. If `$options.userProject` is not set, this option has no effect. **Defaults to** `true`. |
| `↳ returnPartialSuccess` | `bool` If true, the returned iterator will contain an `unreachable` property with a list of buckets that were not retrieved. **Note:** If set to false (default) and unreachable buckets are found, the operation will throw an exception. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/BucketIterator<https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket>` |   |

### restore

Restores a soft-deleted bucket.

Example:

    $bucket = $storage->bucket->restore('my-bucket');

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `name` | `string` The name of the bucket to restore. |
| `generation` | `string` The specific version of the bucket to be restored. |
| `options` | `array` Configuration Options. |
| `↳ projection` | `string` Determines which properties to return. May be either `"full"` or `"noAcl"`. **Defaults to** `"noAcl"`, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to `"full"`. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket` |   |

### createBucket

See also:

- [Buckets insert API documentation.](https://cloud.google.com/storage/docs/json_api/v1/buckets/insert)

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `name` | `string` Name of the bucket to be created. |
| `options` | `array` Configuration options. |
| `↳ predefinedAcl` | `string` Predefined ACL to apply to the bucket. Acceptable values include, `"authenticatedRead"`, `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`, `"projectPrivate"`, and `"publicRead"`. |
| `↳ predefinedDefaultObjectAcl` | `string` Apply a predefined set of default object access controls to this bucket. |
| `↳ enableObjectRetention` | `bool` Whether object retention should be enabled on this bucket. For more information, refer to the [Object Retention Lock](https://cloud.google.com/storage/docs/object-lock) documentation. |
| `↳ projection` | `string` Determines which properties to return. May be either `"full"` or `"noAcl"`. **Defaults to** `"noAcl"`, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to `"full"`. |
| `↳ fields` | `string` Selector which will cause the response to only return the specified fields. |
| `↳ acl` | `array` Access controls on the bucket. |
| `↳ cors` | `array` The bucket's Cross-Origin Resource Sharing (CORS) configuration. |
| `↳ defaultObjectAcl` | `array` Default access controls to apply to new objects when no ACL is provided. |
| `↳ lifecycle` | `array|https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Lifecycle` The bucket's lifecycle configuration. |
| `↳ location` | `string` The location of the bucket. If specifying a dual-region, the `customPlacementConfig` property should be set in conjunction. For more information, see [Bucket Locations](https://cloud.google.com/storage/docs/locations). **Defaults to** `"US"`. |
| `↳ hierarchicalNamespace` | `array` The hierarchical namespace configuration on this bucket. |
| `↳ customPlacementConfig` | `array` The bucket's dual regions. For more information, see [Bucket Locations](https://cloud.google.com/storage/docs/locations). |
| `↳ logging` | `array` The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. |
| `↳ storageClass` | `string` The bucket's storage class. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Acceptable values include the following strings: `"STANDARD"`, `"NEARLINE"`, `"COLDLINE"` and `"ARCHIVE"`. Legacy values including `"MULTI_REGIONAL"`, `"REGIONAL"` and `"DURABLE_REDUCED_AVAILABILITY"` are also available, but should be avoided for new implementations. For more information, refer to the [Storage Classes](https://cloud.google.com/storage/docs/storage-classes) documentation. **Defaults to** `"STANDARD"`. |
| `↳ autoclass` | `array` The bucket's autoclass configuration. Buckets can have either StorageClass OLM rules or Autoclass, but not both. When Autoclass is enabled on a bucket, adding StorageClass OLM rules will result in failure. For more information, refer to [Storage Autoclass](https://cloud.google.com/storage/docs/autoclass) |
| `↳ versioning` | `array` The bucket's versioning configuration. |
| `↳ website` | `array` The bucket's website configuration. |
| `↳ billing` | `array` The bucket's billing configuration. | **Properties** || |---|---| | **Name** | **Description** | | `requesterPays` | `bool` When `true`, requests to this bucket and objects within it must provide a project ID to which the request will be billed. | |
| `↳ labels` | `array` The Bucket labels. Labels are represented as an array of keys and values. To remove an existing label, set its value to `null`. |
| `↳ userProject` | `string` If set, this is the ID of the project which will be billed for the request. |
| `↳ bucketUserProject` | `bool` If true, the returned instance will have `$userProject` set to the value of `$options.userProject`. If false, `$options.userProject` will be used ONLY for the createBucket operation. If `$options.userProject` is not set, this option has no effect. **Defaults to** `true`. |
| `↳ encryption` | `array` Encryption configuration used by default for newly inserted objects. | **Properties** || |---|---| | **Name** | **Description** | | `defaultKmsKeyName` | `string` A Cloud KMS Key used to encrypt objects uploaded into this bucket. Should be in the format `projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key`. Please note the KMS key ring must use the same location as the bucket. | | `googleManagedEncryptionEnforcementConfig` | `array` Enforcement configuration for Google-managed encryption. | | `customerManagedEncryptionEnforcementConfig` | `array` Enforcement configuration for Cloud KMS (customer-managed) encryption. | | `customerSuppliedEncryptionEnforcementConfig` | `array` Enforcement configuration for customer-supplied encryption keys (CSEK). | |
| `↳ defaultEventBasedHold` | `bool` When `true`, newly created objects in this bucket will be retained indefinitely until an event occurs, signified by the hold's release. |
| `↳ retentionPolicy` | `array` Defines the retention policy for a bucket. In order to lock a retention policy, please see [Bucket::lockRetentionPolicy()](https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket#_Google_Cloud_Storage_Bucket__lockRetentionPolicy__). | **Properties** || |---|---| | **Name** | **Description** | | `retentionPeriod` | `int` Specifies the retention period for objects in seconds. During the retention period an object cannot be overwritten or deleted. Retention period must be greater than zero and less than 100 years. | |
| `↳ iamConfiguration` | `array` The bucket's IAM configuration. | **Properties** || |---|---| | **Name** | **Description** | | `bucketPolicyOnly.enabled` | `bool` this is an alias for $iamConfiguration.uniformBucketLevelAccess. | | `uniformBucketLevelAccess.enabled` | `bool` If set and true, access checks only use bucket-level IAM policies or above. When enabled, requests attempting to view or manipulate ACLs will fail with error code 400. **NOTE** : Before using Uniform bucket-level access, please review the [feature documentation](https://cloud.google.com/storage/docs/uniform-bucket-level-access), as well as [Should You Use uniform bucket-level access](https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use) | |
| `↳ rpo` | `string` Specifies the Turbo Replication setting for a dual-region bucket. The possible values are DEFAULT and ASYNC_TURBO. Trying to set the rpo for a non dual-region bucket will throw an exception. Non existence of this parameter is equivalent to it being DEFAULT. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/Bucket` |   |

### registerStreamWrapper

Registers this StorageClient as the handler for stream reading/writing.

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `protocol` | `string` The name of the protocol to use. **Defaults to** `gs`. |

### unregisterStreamWrapper

Unregisters the SteamWrapper

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `protocol` | `string` The name of the protocol to unregister. **Defaults to** `gs`. |

### signedUrlUploader

Create an uploader to handle a Signed URL.

Example:

    $uploader = $storage->signedUrlUploader($uri, fopen('/path/to/myfile.doc', 'r'));

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `uri` | `string` The URI to accept an upload request. |
| `data` | `string|resource|Psr\Http\Message\StreamInterface` The data to be uploaded |
| `options` | `array` \[optional\] Configuration Options. Refer to [Google\\Cloud\\Core\\Upload\\AbstractUploader::__construct()](https://docs.cloud.google.com/php/docs/reference/cloud-core/latest/Upload.AbstractUploader.html#_Google_Cloud_Core_Upload_AbstractUploader____construct__). |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-core/latest/Upload.SignedUrlUploader.html` |   |

### timestamp

Create a Timestamp object.

Example:

    $timestamp = $storage->timestamp(new \DateTime('2003-02-05 11:15:02.421827Z'));

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `timestamp` | `DateTimeInterface` The timestamp value. |
| `nanoSeconds` | `int` \[optional\] The number of nanoseconds in the timestamp. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-core/latest/Timestamp.html` |   |

### getServiceAccount

Get the service account email associated with this client.

Example:

    $serviceAccount = $storage->getServiceAccount();

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `options` | `array` Configuration options. |
| `↳ userProject` | `string` If set, this is the ID of the project which will be billed for the request. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `string` |   |

### hmacKeys

List Service Account HMAC keys in the project.

Example:

    $hmacKeys = $storage->hmacKeys();

    // Get the HMAC keys associated with a Service Account email
    $hmacKeys = $storage->hmacKeys([
        'serviceAccountEmail' => $serviceAccountEmail
    ]);

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `options` | `array` Configuration Options |
| `↳ serviceAccountEmail` | `string` If present, only keys for the given service account are returned. |
| `↳ showDeletedKeys` | `bool` Whether or not to show keys in the DELETED state. |
| `↳ userProject` | `string` If set, this is the ID of the project which will be billed for the request. |
| `↳ projectId` | `string` The project ID to use, if different from that with which the client was created. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-core/latest/Iterator.ItemIterator.html<https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/HmacKey>` |   |

### hmacKey

Lazily instantiate an HMAC Key instance using an Access ID.

Example:

    $hmacKey = $storage->hmacKey($accessId);

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `accessId` | `string` The ID of the HMAC Key. |
| `projectId` | `string` \[optional\] The project ID to use, if different from that with which the client was created. |
| `metadata` | `array` \[optional\] HMAC key metadata. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/HmacKey` |   |

### createHmacKey

Creates a new HMAC key for the specified service account.

Please note that the HMAC secret is only available at creation. Make sure
to note the secret after creation.

Example:

    $response = $storage->createHmacKey('account@myProject.iam.gserviceaccount.com');
    $secret = $response->secret();

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `serviceAccountEmail` | `string` Email address of the service account. |
| `options` | `array` Configuration Options |
| `↳ userProject` | `string` If set, this is the ID of the project which will be billed for the request. **NOTE**: This option is currently ignored by Cloud Storage. |
| `↳ projectId` | `string` The project ID to use, if different from that with which the client was created. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/php/docs/reference/cloud-storage/latest/CreatedHmacKey` |   |

## Constants

### VERSION

    Value: '2.3.0'

### FULL_CONTROL_SCOPE

    Value: 'https://www.googleapis.com/auth/devstorage.full_control'

### READ_ONLY_SCOPE

    Value: 'https://www.googleapis.com/auth/devstorage.read_only'

### READ_WRITE_SCOPE

    Value: 'https://www.googleapis.com/auth/devstorage.read_write'

### RETRY_NEVER

    Value: 'never'

Retry strategy to signify that we never want to retry an operation
even if the error is retryable.

We can set $options\['retryStrategy'\] to one of "always", "never" and
"idempotent".

### RETRY_ALWAYS

    Value: 'always'

Retry strategy to signify that we always want to retry an operation.

### RETRY_IDEMPOTENT

    Value: 'idempotent'

This is the default. This signifies that we want to retry an operation
only if it is retryable and the error is retryable.