PluginProbe
WP-Stateless – Google Cloud Storage / 3.0.3
WP-Stateless – Google Cloud Storage v3.0.3
4.4.3 2.1.7 2.1.8 2.1.9 2.2.0 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.3.0 2.3.1 2.3.2 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.1.0 3.1.1 3.2.0 3.2.1 3.2.2 All 62 releases
wp-stateless / lib / Google / vendor / google / cloud-storage / src / StorageClient.php

StorageClient.php in WP-Stateless – Google Cloud Storage 3.0.3, at lib/Google/vendor/google/cloud-storage/src/StorageClient.php

573 lines 22.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Copyright 2015 Google Inc. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 namespace Google\Cloud\Storage;
19
20 use Google\Auth\FetchAuthTokenInterface;
21 use Google\Cloud\Core\ArrayTrait;
22 use Google\Cloud\Core\ClientTrait;
23 use Google\Cloud\Core\Exception\GoogleException;
24 use Google\Cloud\Core\Iterator\ItemIterator;
25 use Google\Cloud\Core\Iterator\PageIterator;
26 use Google\Cloud\Core\Timestamp;
27 use Google\Cloud\Core\Upload\SignedUrlUploader;
28 use Google\Cloud\Storage\Connection\ConnectionInterface;
29 use Google\Cloud\Storage\Connection\Rest;
30 use Psr\Cache\CacheItemPoolInterface;
31 use Psr\Http\Message\StreamInterface;
32
33 /**
34 * Google Cloud Storage allows you to store and retrieve data on Google's
35 * infrastructure. Find more information at the
36 * [Google Cloud Storage API docs](https://developers.google.com/storage).
37 *
38 * Example:
39 * ```
40 * use Google\Cloud\Storage\StorageClient;
41 *
42 * $storage = new StorageClient();
43 * ```
44 */
45 class StorageClient
46 {
47 use ArrayTrait;
48 use ClientTrait;
49
50 const VERSION = '1.22.0';
51
52 const FULL_CONTROL_SCOPE = 'https://www.googleapis.com/auth/devstorage.full_control';
53 const READ_ONLY_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_only';
54 const READ_WRITE_SCOPE = 'https://www.googleapis.com/auth/devstorage.read_write';
55
56 /**
57 * @var ConnectionInterface Represents a connection to Storage.
58 */
59 protected $connection;
60
61 /**
62 * Create a Storage client.
63 *
64 * @param array $config [optional] {
65 * Configuration options.
66 *
67 * @type string $apiEndpoint The hostname with optional port to use in
68 * place of the default service endpoint. Example:
69 * `foobar.com` or `foobar.com:1234`.
70 * @type string $projectId The project ID from the Google Developer's
71 * Console.
72 * @type CacheItemPoolInterface $authCache A cache used storing access
73 * tokens. **Defaults to** a simple in memory implementation.
74 * @type array $authCacheOptions Cache configuration options.
75 * @type callable $authHttpHandler A handler used to deliver Psr7
76 * requests specifically for authentication.
77 * @type FetchAuthTokenInterface $credentialsFetcher A credentials
78 * fetcher instance.
79 * @type callable $httpHandler A handler used to deliver Psr7 requests.
80 * Only valid for requests sent over REST.
81 * @type array $keyFile The contents of the service account credentials
82 * .json file retrieved from the Google Developer's Console.
83 * Ex: `json_decode(file_get_contents($path), true)`.
84 * @type string $keyFilePath The full path to your service account
85 * credentials .json file retrieved from the Google Developers
86 * Console.
87 * @type float $requestTimeout Seconds to wait before timing out the
88 * request. **Defaults to** `0` with REST and `60` with gRPC.
89 * @type int $retries Number of retries for a failed request.
90 * **Defaults to** `3`.
91 * @type array $scopes Scopes to be used for the request.
92 * }
93 */
94 public function __construct(array $config = [])
95 {
96 if (!isset($config['scopes'])) {
97 $config['scopes'] = [self::FULL_CONTROL_SCOPE];
98 }
99
100 $this->connection = new Rest($this->configureAuthentication($config) + [
101 'projectId' => $this->projectId
102 ]);
103 }
104
105 /**
106 * Lazily instantiates a bucket. There are no network requests made at this
107 * point. To see the operations that can be performed on a bucket please
108 * see {@see Google\Cloud\Storage\Bucket}.
109 *
110 * If `$userProject` is set to true, the current project ID (used to
111 * instantiate the client) will be billed for all requests. If
112 * `$userProject` is a project ID, given as a string, that project
113 * will be billed for all requests. This only has an effect when the bucket
114 * is not owned by the current or given project ID.
115 *
116 * Example:
117 * ```
118 * $bucket = $storage->bucket('my-bucket');
119 * ```
120 *
121 * @param string $name The name of the bucket to request.
122 * @param string|bool $userProject If true, the current Project ID
123 * will be used. If a string, that string will be used as the
124 * userProject argument, and that project will be billed for the
125 * request. **Defaults to** `false`.
126 * @return Bucket
127 */
128 public function bucket($name, $userProject = false)
129 {
130 if (!$userProject) {
131 $userProject = null;
132 } elseif (!is_string($userProject)) {
133 $userProject = $this->projectId;
134 }
135
136 return new Bucket($this->connection, $name, [
137 'requesterProjectId' => $userProject
138 ]);
139 }
140
141 /**
142 * Fetches all buckets in the project.
143 *
144 * Example:
145 * ```
146 * $buckets = $storage->buckets();
147 * ```
148 *
149 * ```
150 * // Get all buckets beginning with the prefix 'album'.
151 * $buckets = $storage->buckets([
152 * 'prefix' => 'album'
153 * ]);
154 *
155 * foreach ($buckets as $bucket) {
156 * echo $bucket->name() . PHP_EOL;
157 * }
158 * ```
159 *
160 * @see https://cloud.google.com/storage/docs/json_api/v1/buckets/list Buckets list API documentation.
161 *
162 * @param array $options [optional] {
163 * Configuration options.
164 *
165 * @type int $maxResults Maximum number of results to return per
166 * requested page.
167 * @type int $resultLimit Limit the number of results returned in total.
168 * **Defaults to** `0` (return all results).
169 * @type string $pageToken A previously-returned page token used to
170 * resume the loading of results from a specific point.
171 * @type string $prefix Filter results with this prefix.
172 * @type string $projection Determines which properties to return. May
173 * be either 'full' or 'noAcl'.
174 * @type string $fields Selector which will cause the response to only
175 * return the specified fields.
176 * @type string $userProject If set, this is the ID of the project which
177 * will be billed for the request.
178 * @type bool $bucketUserProject If true, each returned instance will
179 * have `$userProject` set to the value of `$options.userProject`.
180 * If false, `$options.userProject` will be used ONLY for the
181 * listBuckets operation. If `$options.userProject` is not set,
182 * this option has no effect. **Defaults to** `true`.
183 * }
184 * @return ItemIterator<Bucket>
185 * @throws GoogleException When a project ID has not been detected.
186 */
187 public function buckets(array $options = [])
188 {
189 $this->requireProjectId();
190
191 $resultLimit = $this->pluck('resultLimit', $options, false);
192 $bucketUserProject = $this->pluck('bucketUserProject', $options, false);
193 $bucketUserProject = !is_null($bucketUserProject)
194 ? $bucketUserProject
195 : true;
196 $userProject = (isset($options['userProject']) && $bucketUserProject)
197 ? $options['userProject']
198 : null;
199
200 return new ItemIterator(
201 new PageIterator(
202 function (array $bucket) use ($userProject) {
203 return new Bucket(
204 $this->connection,
205 $bucket['name'],
206 $bucket + ['requesterProjectId' => $userProject]
207 );
208 },
209 [$this->connection, 'listBuckets'],
210 $options + ['project' => $this->projectId],
211 ['resultLimit' => $resultLimit]
212 )
213 );
214 }
215
216 /**
217 * Create a bucket. Bucket names must be unique as Cloud Storage uses a flat
218 * namespace. For more information please see
219 * [bucket name requirements](https://cloud.google.com/storage/docs/naming#requirements)
220 *
221 * Example:
222 * ```
223 * $bucket = $storage->createBucket('bucket');
224 * ```
225 *
226 * ```
227 * // Create a bucket with logging enabled.
228 * $bucket = $storage->createBucket('myBeautifulBucket', [
229 * 'logging' => [
230 * 'logBucket' => 'bucketToLogTo',
231 * 'logObjectPrefix' => 'myPrefix'
232 * ]
233 * ]);
234 * ```
235 *
236 * @see https://cloud.google.com/storage/docs/json_api/v1/buckets/insert Buckets insert API documentation.
237 *
238 * @param string $name Name of the bucket to be created.
239 * @codingStandardsIgnoreStart
240 * @param array $options [optional] {
241 * Configuration options.
242 *
243 * @type string $predefinedAcl Predefined ACL to apply to the bucket.
244 * Acceptable values include, `"authenticatedRead"`,
245 * `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
246 * `"projectPrivate"`, and `"publicRead"`.
247 * @type string $predefinedDefaultObjectAcl Apply a predefined set of
248 * default object access controls to this bucket.
249 * @type string $projection Determines which properties to return. May
250 * be either `"full"` or `"noAcl"`. **Defaults to** `"noAcl"`,
251 * unless the bucket resource specifies acl or defaultObjectAcl
252 * properties, when it defaults to `"full"`.
253 * @type string $fields Selector which will cause the response to only
254 * return the specified fields.
255 * @type array $acl Access controls on the bucket.
256 * @type array $cors The bucket's Cross-Origin Resource Sharing (CORS)
257 * configuration.
258 * @type array $defaultObjectAcl Default access controls to apply to new
259 * objects when no ACL is provided.
260 * @type array|Lifecycle $lifecycle The bucket's lifecycle configuration.
261 * @type string $location The location of the bucket. **Defaults to**
262 * `"US"`.
263 * @type array $logging The bucket's logging configuration, which
264 * defines the destination bucket and optional name prefix for the
265 * current bucket's logs.
266 * @type string $storageClass The bucket's storage class. This defines
267 * how objects in the bucket are stored and determines the SLA and
268 * the cost of storage. Acceptable values include the following
269 * strings: `"STANDARD"`, `"NEARLINE"`, `"COLDLINE"` and
270 * `"ARCHIVE"`. Legacy values including `"MULTI_REGIONAL"`,
271 * `"REGIONAL"` and `"DURABLE_REDUCED_AVAILABILITY"` are also
272 * available, but should be avoided for new implementations. For
273 * more information, refer to the
274 * [Storage Classes](https://cloud.google.com/storage/docs/storage-classes)
275 * documentation. **Defaults to** `"STANDARD"`.
276 * @type array $versioning The bucket's versioning configuration.
277 * @type array $website The bucket's website configuration.
278 * @type array $billing The bucket's billing configuration.
279 * @type bool $billing.requesterPays When `true`, requests to this bucket
280 * and objects within it must provide a project ID to which the
281 * request will be billed.
282 * @type array $labels The Bucket labels. Labels are represented as an
283 * array of keys and values. To remove an existing label, set its
284 * value to `null`.
285 * @type string $userProject If set, this is the ID of the project which
286 * will be billed for the request.
287 * @type bool $bucketUserProject If true, the returned instance will
288 * have `$userProject` set to the value of `$options.userProject`.
289 * If false, `$options.userProject` will be used ONLY for the
290 * createBucket operation. If `$options.userProject` is not set,
291 * this option has no effect. **Defaults to** `true`.
292 * @type array $encryption Encryption configuration used by default for
293 * newly inserted objects.
294 * @type string $encryption.defaultKmsKeyName A Cloud KMS Key used to
295 * encrypt objects uploaded into this bucket. Should be in the
296 * format
297 * `projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key`.
298 * Please note the KMS key ring must use the same location as the
299 * bucket.
300 * @type bool $defaultEventBasedHold When `true`, newly created objects
301 * in this bucket will be retained indefinitely until an event
302 * occurs, signified by the hold's release.
303 * @type array $retentionPolicy Defines the retention policy for a
304 * bucket. In order to lock a retention policy, please see
305 * {@see Google\Cloud\Storage\Bucket::lockRetentionPolicy()}.
306 * @type int $retentionPolicy.retentionPeriod Specifies the retention
307 * period for objects in seconds. During the retention period an
308 * object cannot be overwritten or deleted. Retention period must
309 * be greater than zero and less than 100 years.
310 * @type array $iamConfiguration The bucket's IAM configuration.
311 * @type bool $iamConfiguration.bucketPolicyOnly.enabled this is an alias
312 * for $iamConfiguration.uniformBucketLevelAccess.
313 * @type bool $iamConfiguration.uniformBucketLevelAccess.enabled If set and
314 * true, access checks only use bucket-level IAM policies or
315 * above. When enabled, requests attempting to view or manipulate
316 * ACLs will fail with error code 400. **NOTE**: Before using
317 * Uniform bucket-level access, please review the
318 * [feature documentation](https://cloud.google.com/storage/docs/uniform-bucket-level-access),
319 * as well as
320 * [Should You Use uniform bucket-level access](https://cloud.google.com/storage/docs/uniform-bucket-level-access#should-you-use)
321 * }
322 * @codingStandardsIgnoreEnd
323 * @return Bucket
324 * @throws GoogleException When a project ID has not been detected.
325 */
326 public function createBucket($name, array $options = [])
327 {
328 $this->requireProjectId();
329
330 if (isset($options['lifecycle']) && $options['lifecycle'] instanceof Lifecycle) {
331 $options['lifecycle'] = $options['lifecycle']->toArray();
332 }
333
334 $bucketUserProject = $this->pluck('bucketUserProject', $options, false);
335 $bucketUserProject = !is_null($bucketUserProject)
336 ? $bucketUserProject
337 : true;
338 $userProject = (isset($options['userProject']) && $bucketUserProject)
339 ? $options['userProject']
340 : null;
341
342 $response = $this->connection->insertBucket($options + ['name' => $name, 'project' => $this->projectId]);
343 return new Bucket(
344 $this->connection,
345 $name,
346 $response + ['requesterProjectId' => $userProject]
347 );
348 }
349
350 /**
351 * Registers this StorageClient as the handler for stream reading/writing.
352 *
353 * @param string $protocol The name of the protocol to use. **Defaults to** `gs`.
354 * @throws \RuntimeException
355 */
356 public function registerStreamWrapper($protocol = null)
357 {
358 return StreamWrapper::register($this, $protocol);
359 }
360
361 /**
362 * Unregisters the SteamWrapper
363 *
364 * @param string $protocol The name of the protocol to unregister. **Defaults to** `gs`.
365 */
366 public function unregisterStreamWrapper($protocol = null)
367 {
368 StreamWrapper::unregister($protocol);
369 }
370
371 /**
372 * Create an uploader to handle a Signed URL.
373 *
374 * Example:
375 * ```
376 * $uploader = $storage->signedUrlUploader($uri, fopen('/path/to/myfile.doc', 'r'));
377 * ```
378 *
379 * @param string $uri The URI to accept an upload request.
380 * @param string|resource|StreamInterface $data The data to be uploaded
381 * @param array $options [optional] Configuration Options. Refer to
382 * {@see Google\Cloud\Core\Upload\AbstractUploader::__construct()}.
383 * @return SignedUrlUploader
384 */
385 public function signedUrlUploader($uri, $data, array $options = [])
386 {
387 return new SignedUrlUploader($this->connection->requestWrapper(), $data, $uri, $options);
388 }
389
390 /**
391 * Create a Timestamp object.
392 *
393 * Example:
394 * ```
395 * $timestamp = $storage->timestamp(new \DateTime('2003-02-05 11:15:02.421827Z'));
396 * ```
397 *
398 * @param \DateTimeInterface $timestamp The timestamp value.
399 * @param int $nanoSeconds [optional] The number of nanoseconds in the timestamp.
400 * @return Timestamp
401 */
402 public function timestamp(\DateTimeInterface $timestamp, $nanoSeconds = null)
403 {
404 return new Timestamp($timestamp, $nanoSeconds);
405 }
406
407 /**
408 * Get the service account email associated with this client.
409 *
410 * Example:
411 * ```
412 * $serviceAccount = $storage->getServiceAccount();
413 * ```
414 *
415 * @param array $options [optional] {
416 * Configuration options.
417 *
418 * @type string $userProject If set, this is the ID of the project which
419 * will be billed for the request.
420 * }
421 * @return string
422 */
423 public function getServiceAccount(array $options = [])
424 {
425 $resp = $this->connection->getServiceAccount($options + ['projectId' => $this->projectId]);
426 return $resp['email_address'];
427 }
428
429 /**
430 * List Service Account HMAC keys in the project.
431 *
432 * Example:
433 * ```
434 * $hmacKeys = $storage->hmacKeys();
435 * ```
436 *
437 * ```
438 * // Get the HMAC keys associated with a Service Account email
439 * $hmacKeys = $storage->hmacKeys([
440 * 'serviceAccountEmail' => $serviceAccountEmail
441 * ]);
442 * ```
443 *
444 * @param array $options {
445 * Configuration Options
446 *
447 * @type string $serviceAccountEmail If present, only keys for the given
448 * service account are returned.
449 * @type bool $showDeletedKeys Whether or not to show keys in the
450 * DELETED state.
451 * @type string $userProject If set, this is the ID of the project which
452 * will be billed for the request.
453 * @type string $projectId The project ID to use, if different from that
454 * with which the client was created.
455 * }
456 * @return ItemIterator<HmacKey>
457 */
458 public function hmacKeys(array $options = [])
459 {
460 $options += [
461 'projectId' => $this->projectId
462 ];
463
464 if (!$options['projectId']) {
465 $this->requireProjectId();
466 }
467
468 $resultLimit = $this->pluck('resultLimit', $options, false);
469 return new ItemIterator(
470 new PageIterator(
471 function (array $metadata) use ($options) {
472 return $this->hmacKey(
473 $metadata['accessId'],
474 $options['projectId'],
475 $metadata
476 );
477 },
478 [$this->connection, 'listHmacKeys'],
479 $options,
480 ['resultLimit' => $resultLimit]
481 )
482 );
483 }
484
485 /**
486 * Lazily instantiate an HMAC Key instance using an Access ID.
487 *
488 * Example:
489 * ```
490 * $hmacKey = $storage->hmacKey($accessId);
491 * ```
492 *
493 * @param string $accessId The ID of the HMAC Key.
494 * @param string $projectId [optional] The project ID to use, if different
495 * from that with which the client was created.
496 * @param array $metadata [optional] HMAC key metadata.
497 * @return HmacKey
498 */
499 public function hmacKey($accessId, $projectId = null, array $metadata = [])
500 {
501 if (!$projectId) {
502 $this->requireProjectId();
503 }
504
505 return new HmacKey($this->connection, $projectId ?: $this->projectId, $accessId, $metadata);
506 }
507
508 /**
509 * Creates a new HMAC key for the specified service account.
510 *
511 * Please note that the HMAC secret is only available at creation. Make sure
512 * to note the secret after creation.
513 *
514 * Example:
515 * ```
516 * $response = $storage->createHmacKey('account@myProject.iam.gserviceaccount.com');
517 * $secret = $response->secret();
518 * ```
519 *
520 * @param string $serviceAccountEmail Email address of the service account.
521 * @param array $options {
522 * Configuration Options
523 *
524 * @type string $userProject If set, this is the ID of the project which
525 * will be billed for the request. **NOTE**: This option is
526 * currently ignored by Cloud Storage.
527 * @type string $projectId The project ID to use, if different from that
528 * with which the client was created.
529 * }
530 * @return CreatedHmacKey
531 */
532 public function createHmacKey($serviceAccountEmail, array $options = [])
533 {
534 $options += [
535 'projectId' => $this->projectId
536 ];
537
538 if (!$options['projectId']) {
539 $this->requireProjectId();
540 }
541
542 $res = $this->connection->createHmacKey([
543 'projectId' => $options['projectId'],
544 'serviceAccountEmail' => $serviceAccountEmail
545 ] + $options);
546
547 $key = new HmacKey(
548 $this->connection,
549 $options['projectId'],
550 $res['metadata']['accessId'],
551 $res['metadata']
552 );
553
554 return new CreatedHmacKey($key, $res['secret']);
555 }
556
557 /**
558 * Throw an exception if no project ID available.
559 *
560 * @return void
561 * @throws GoogleException
562 */
563 private function requireProjectId()
564 {
565 if (!$this->projectId) {
566 throw new GoogleException(
567 'No project ID was provided, ' .
568 'and we were unable to detect a default project ID.'
569 );
570 }
571 }
572 }
573