Cloud Storage Client - Class StorageClient (1.49.0) (original) (raw)
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 theGoogle Cloud Storage API docs.
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 | 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 | FetchAuthTokenInterface 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=newServiceAccountCredentials(credentialsFetcher = new ServiceAccountCredentials(credentialsFetcher=newServiceAccountCredentials(scopes, json);json); 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=newServiceAccountCredentials(credentialsFetcher = new ServiceAccountCredentials(credentialsFetcher=newServiceAccountCredentials(scopes, json);json); 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 argumentsb/wretries.Thisreturnsthenewarguments b/w retries. This returns the new argumentsb/wretries.Thisreturnsthenewarguments 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.
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:
| 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 |
| Bucket |
buckets
| 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 userProjectsettothevalueofuserProject set to the value of userProjectsettothevalueofoptions.userProject. If false, options.userProjectwillbeusedONLYforthelistBucketsoperation.Ifoptions.userProject will be used ONLY for the listBuckets operation. If options.userProjectwillbeusedONLYforthelistBucketsoperation.Ifoptions.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 |
| BucketIterator<Bucket> |
restore
Restores a soft-deleted bucket.
Example:
| 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 |
| Bucket |
createBucket
| 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 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|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. 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. |
| ↳ 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 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 |
| ↳ 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 boolWhen 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 userProjectsettothevalueofuserProject set to the value of userProjectsettothevalueofoptions.userProject. If false, options.userProjectwillbeusedONLYforthecreateBucketoperation.Ifoptions.userProject will be used ONLY for the createBucket operation. If options.userProjectwillbeusedONLYforthecreateBucketoperation.Ifoptions.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 stringA 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. |
| ↳ 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(). Properties Name Description retentionPeriod intSpecifies 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 boolthis is an alias for $iamConfiguration.uniformBucketLevelAccess. uniformBucketLevelAccess.enabled boolIf 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, as well as Should You Use uniform bucket-level access |
| ↳ 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 |
| 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:
| Parameters | |
|---|---|
| Name | Description |
| uri | string The URI to accept an upload request. |
| data | string|resource |
| options | array [optional] Configuration Options. Refer toGoogle\Cloud\Core\Upload\AbstractUploader::__construct(). |
| Returns | |
|---|---|
| Type | Description |
| Google\Cloud\Core\Upload\SignedUrlUploader |
timestamp
Create a Timestamp object.
Example:
| Parameters | |
|---|---|
| Name | Description |
| timestamp | DateTimeInterface The timestamp value. |
| nanoSeconds | int [optional] The number of nanoseconds in the timestamp. |
| Returns | |
|---|---|
| Type | Description |
| Google\Cloud\Core\Timestamp |
getServiceAccount
Get the service account email associated with this client.
Example:
| 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:
// Get the HMAC keys associated with a Service Account email <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>h</mi><mi>m</mi><mi>a</mi><mi>c</mi><mi>K</mi><mi>e</mi><mi>y</mi><mi>s</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">hmacKeys = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">hma</span><span class="mord mathnormal">cKeys</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>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 |
| Google\Cloud\Core\Iterator\ItemIterator<HmacKey> |
hmacKey
Lazily instantiate an HMAC Key instance using an Access ID.
Example:
| 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 |
| 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:
| 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 |
| CreatedHmacKey |
Constants
VERSION
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
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
Retry strategy to signify that we always want to retry an operation.
RETRY_IDEMPOTENT
This is the default. This signifies that we want to retry an operation only if it is retryable and the error is retryable.