/
Bucket.php
1682 lines (1609 loc) · 68.5 KB
/
Bucket.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Storage;
use Google\Cloud\Core\ArrayTrait;
use Google\Cloud\Core\Exception\GoogleException;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Core\Exception\ServiceException;
use Google\Cloud\Core\Iam\Iam;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\Iterator\PageIterator;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Core\Upload\ResumableUploader;
use Google\Cloud\Core\Upload\StreamableUploader;
use Google\Cloud\PubSub\Topic;
use Google\Cloud\Storage\Connection\ConnectionInterface;
use Google\Cloud\Storage\Connection\IamBucket;
use Google\Cloud\Storage\SigningHelper;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\MimeType;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\StreamInterface;
/**
* Buckets are the basic containers that hold your data. Everything that you
* store in Google Cloud Storage must be contained in a bucket.
*
* Example:
* ```
* use Google\Cloud\Storage\StorageClient;
*
* $storage = new StorageClient();
*
* $bucket = $storage->bucket('my-bucket');
* ```
*/
class Bucket
{
use ArrayTrait;
use EncryptionTrait;
const NOTIFICATION_TEMPLATE = '//pubsub.googleapis.com/%s';
const TOPIC_TEMPLATE = 'projects/%s/topics/%s';
const TOPIC_REGEX = '/projects\/[^\/]*\/topics\/(.*)/';
/**
* @var Acl ACL for the bucket.
*/
private $acl;
/**
* @var ConnectionInterface Represents a connection to Cloud Storage.
* @internal
*/
private $connection;
/**
* @var Acl Default ACL for objects created within the bucket.
*/
private $defaultAcl;
/**
* @var array The bucket's identity.
*/
private $identity;
/**
* @var string The project ID.
*/
private $projectId;
/**
* @var array|null The bucket's metadata.
*/
private $info;
/**
* @var Iam|null
*/
private $iam;
/**
* @param ConnectionInterface $connection Represents a connection to Cloud
* Storage. This object is created by StorageClient,
* and should not be instantiated outside of this client.
* @param string $name The bucket's name.
* @param array $info [optional] The bucket's metadata.
*/
public function __construct(ConnectionInterface $connection, $name, array $info = [])
{
$this->connection = $connection;
$this->identity = [
'bucket' => $name,
'userProject' => $this->pluck('requesterProjectId', $info, false)
];
$this->info = $info;
$this->projectId = $this->connection->projectId();
$this->acl = new Acl($this->connection, 'bucketAccessControls', $this->identity);
$this->defaultAcl = new Acl($this->connection, 'defaultObjectAccessControls', $this->identity);
}
/**
* Configure ACL for this bucket.
*
* Example:
* ```
* $acl = $bucket->acl();
* ```
*
* @see https://cloud.google.com/storage/docs/access-control More about Access Control Lists
*
* @return Acl An ACL instance configured to handle the bucket's access
* control policies.
*/
public function acl()
{
return $this->acl;
}
/**
* Configure default object ACL for this bucket.
*
* Example:
* ```
* $acl = $bucket->defaultAcl();
* ```
*
* @see https://cloud.google.com/storage/docs/access-control More about Access Control Lists
* @return Acl An ACL instance configured to handle the bucket's default
* object access control policies.
*/
public function defaultAcl()
{
return $this->defaultAcl;
}
/**
* Check whether or not the bucket exists.
*
* Example:
* ```
* if ($bucket->exists()) {
* echo 'Bucket exists!';
* }
* ```
*
* @param array $options [optional] {
* Configuration options.
* }
* @return bool
*/
public function exists(array $options = [])
{
try {
$this->connection->getBucket($options + $this->identity + ['fields' => 'name']);
} catch (NotFoundException $ex) {
return false;
}
return true;
}
/**
* Upload your data in a simple fashion. Uploads will default to being
* resumable if the file size is greater than 5mb.
*
* Example:
* ```
* $object = $bucket->upload(
* fopen(__DIR__ . '/image.jpg', 'r')
* );
* ```
*
* ```
* // Upload an object in a resumable fashion while setting a new name for
* // the object and including the content language.
* $options = [
* 'resumable' => true,
* 'name' => '/images/new-name.jpg',
* 'metadata' => [
* 'contentLanguage' => 'en'
* ]
* ];
*
* $object = $bucket->upload(
* fopen(__DIR__ . '/image.jpg', 'r'),
* $options
* );
* ```
*
* ```
* // Upload an object with a customer-supplied encryption key.
* $key = base64_encode(openssl_random_pseudo_bytes(32)); // Make sure to remember your key.
*
* $object = $bucket->upload(
* fopen(__DIR__ . '/image.jpg', 'r'),
* ['encryptionKey' => $key]
* );
* ```
*
* ```
* // Upload an object utilizing an encryption key managed by the Cloud Key Management Service (KMS).
* $object = $bucket->upload(
* fopen(__DIR__ . '/image.jpg', 'r'),
* [
* 'metadata' => [
* 'kmsKeyName' => 'projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key'
* ]
* ]
* );
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable
* uploads.
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation.
* @see https://cloud.google.com/storage/docs/encryption#customer-supplied Customer-supplied encryption keys.
* @see https://github.com/google/php-crc32 crc32c PHP extension for hardware-accelerated validation hashes.
*
* @param string|resource|StreamInterface|null $data The data to be uploaded.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination. Required when data is
* of type string or null.
* @type bool $resumable Indicates whether or not the upload will be
* performed in a resumable fashion.
* @type bool|string $validate Indicates whether or not validation will
* be applied using md5 or crc32c hashing functionality. If
* enabled, and the calculated hash does not match that of the
* upstream server, the upload will be rejected. Available options
* are `true`, `false`, `md5` and `crc32`. If true, either md5 or
* crc32c will be chosen based on your platform. If false, no
* validation hash will be sent. Choose either `md5` or `crc32` to
* force a hash method regardless of performance implications.
* **Defaults to** `true`.
* @type int $chunkSize If provided the upload will be done in chunks.
* The size must be in multiples of 262144 bytes. With chunking
* you have increased reliability at the risk of higher overhead.
* It is recommended to not use chunking.
* @type callable $uploadProgressCallback If provided together with
* $resumable == true the given callable function/method will be
* called after each successfully uploaded chunk. The callable
* function/method will receive the number of uploaded bytes
* after each uploaded chunk as a parameter to this callable.
* It's useful if you want to create a progress bar when using
* resumable upload type together with $chunkSize parameter.
* If $chunkSize is not set the callable function/method will be
* called only once after the successful file upload.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type array $retention The full list of available options are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
* @type string $retention.retainUntilTime The earliest time in RFC 3339
* UTC "Zulu" format that the object can be deleted or replaced.
* This is the retention configuration set for this object.
* @type string $retention.mode The mode of the retention configuration,
* which can be either `"Unlocked"` or `"Locked"`.
* @type array $metadata The full list of available options are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
* @type array $metadata.metadata User-provided metadata, in key/value pairs.
* @type string $encryptionKey A base64 encoded AES-256 customer-supplied
* encryption key. If you would prefer to manage encryption
* utilizing the Cloud Key Management Service (KMS) please use the
* `$metadata.kmsKeyName` setting. Please note if using KMS the
* key ring must use the same location as the bucket.
* @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the
* customer-supplied encryption key. This value will be calculated
* from the `encryptionKey` on your behalf if not provided, but
* for best performance it is recommended to pass in a cached
* version of the already calculated SHA.
* }
* @return StorageObject
* @throws \InvalidArgumentException
*/
public function upload($data, array $options = [])
{
if ($this->isObjectNameRequired($data) && !isset($options['name'])) {
throw new \InvalidArgumentException('A name is required when data is of type string or null.');
}
$encryptionKey = $options['encryptionKey'] ?? null;
$encryptionKeySHA256 = $options['encryptionKeySHA256'] ?? null;
$response = $this->connection->insertObject(
$this->formatEncryptionHeaders($options) + $this->identity + [
'data' => $data
]
)->upload();
return new StorageObject(
$this->connection,
$response['name'],
$this->identity['bucket'],
$response['generation'],
$response,
$encryptionKey,
$encryptionKeySHA256
);
}
/**
* Asynchronously uploads an object.
*
* Please note this method does not support resumable or streaming uploads.
*
* Example:
* ```
* $promise = $bucket->uploadAsync('Lorem Ipsum', ['name' => 'keyToData']);
* $object = $promise->wait();
* ```
*
* ```
* // Upload multiple objects to a bucket asynchronously.
* $promises = [];
* $objects = ['key1' => 'Lorem', 'key2' => 'Ipsum', 'key3' => 'Gypsum'];
*
* foreach ($objects as $k => $v) {
* $promises[] = $bucket->uploadAsync($v, ['name' => $k])
* ->then(function (StorageObject $object) {
* echo $object->name() . PHP_EOL;
* }, function(\Exception $e) {
* throw new Exception('An error has occurred in the matrix.', null, $e);
* });
* }
*
* foreach ($promises as $promise) {
* $promise->wait();
* }
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation.
* @see https://cloud.google.com/storage/docs/encryption#customer-supplied Customer-supplied encryption keys.
* @see https://github.com/google/php-crc32 crc32c PHP extension for hardware-accelerated validation hashes.
* @see https://github.com/guzzle/promises Learn more about Guzzle Promises
*
* @param string|resource|StreamInterface|null $data The data to be uploaded.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination. Required when data is
* of type string or null.
* @type bool|string $validate Indicates whether or not validation will
* be applied using md5 or crc32c hashing functionality. If
* enabled, and the calculated hash does not match that of the
* upstream server, the upload will be rejected. Available options
* are `true`, `false`, `md5` and `crc32`. If true, either md5 or
* crc32c will be chosen based on your platform. If false, no
* validation hash will be sent. Choose either `md5` or `crc32` to
* force a hash method regardless of performance implications.
* **Defaults to** `true`.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type array $metadata The full list of available options are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
* @type array $metadata.metadata User-provided metadata, in key/value pairs.
* @type string $encryptionKey A base64 encoded AES-256 customer-supplied
* encryption key. If you would prefer to manage encryption
* utilizing the Cloud Key Management Service (KMS) please use the
* `$metadata.kmsKeyName` setting. Please note if using KMS the
* key ring must use the same location as the bucket.
* @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the
* customer-supplied encryption key. This value will be calculated
* from the `encryptionKey` on your behalf if not provided, but
* for best performance it is recommended to pass in a cached
* version of the already calculated SHA.
* }
* @return PromiseInterface<StorageObject>
* @throws \InvalidArgumentException
* @experimental The experimental flag means that while we believe this method
* or class is ready for use, it may change before release in backwards-
* incompatible ways. Please use with caution, and test thoroughly when
* upgrading.
*/
public function uploadAsync($data, array $options = [])
{
if ($this->isObjectNameRequired($data) && !isset($options['name'])) {
throw new \InvalidArgumentException('A name is required when data is of type string or null.');
}
$encryptionKey = $options['encryptionKey'] ?? null;
$encryptionKeySHA256 = $options['encryptionKeySHA256'] ?? null;
$promise = $this->connection->insertObject(
$this->formatEncryptionHeaders($options) +
$this->identity +
[
'data' => $data,
'resumable' => false
]
)->uploadAsync();
return $promise->then(
function (array $response) use ($encryptionKey, $encryptionKeySHA256) {
return new StorageObject(
$this->connection,
$response['name'],
$this->identity['bucket'],
$response['generation'],
$response,
$encryptionKey,
$encryptionKeySHA256
);
}
);
}
/**
* Get a resumable uploader which can provide greater control over the
* upload process. This is recommended when dealing with large files where
* reliability is key.
*
* Example:
* ```
* $uploader = $bucket->getResumableUploader(
* fopen(__DIR__ . '/image.jpg', 'r')
* );
*
* try {
* $object = $uploader->upload();
* } catch (GoogleException $ex) {
* $resumeUri = $uploader->getResumeUri();
* $object = $uploader->resume($resumeUri);
* }
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable
* uploads.
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation.
*
* @param string|resource|StreamInterface|null $data The data to be uploaded.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination. Required when data is
* of type string or null.
* @type bool $validate Indicates whether or not validation will be
* applied using md5 hashing functionality. If true and the
* calculated hash does not match that of the upstream server the
* upload will be rejected.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include `"authenticatedRead`",
* `"bucketOwnerFullControl`", `"bucketOwnerRead`", `"private`",
* `"projectPrivate`", and `"publicRead"`.
* @type array $metadata The available options for metadata are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
* @type string $encryptionKey A base64 encoded AES-256 customer-supplied
* encryption key. If you would prefer to manage encryption
* utilizing the Cloud Key Management Service (KMS) please use the
* $metadata['kmsKeyName'] setting. Please note if using KMS the
* key ring must use the same location as the bucket.
* @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the
* customer-supplied encryption key. This value will be calculated
* from the `encryptionKey` on your behalf if not provided, but
* for best performance it is recommended to pass in a cached
* version of the already calculated SHA.
* @type callable $uploadProgressCallback The given callable
* function/method will be called after each successfully uploaded
* chunk. The callable function/method will receive the number of
* uploaded bytes after each uploaded chunk as a parameter to this
* callable. It's useful if you want to create a progress bar when
* using resumable upload type together with $chunkSize parameter.
* If $chunkSize is not set the callable function/method will be
* called only once after the successful file upload.
* }
* @return ResumableUploader
* @throws \InvalidArgumentException
*/
public function getResumableUploader($data, array $options = [])
{
if ($this->isObjectNameRequired($data) && !isset($options['name'])) {
throw new \InvalidArgumentException('A name is required when data is of type string or null.');
}
return $this->connection->insertObject(
$this->formatEncryptionHeaders($options) + $this->identity + [
'data' => $data,
'resumable' => true
]
);
}
/**
* Get a streamable uploader which can provide greater control over the
* upload process. This is useful for generating large files and uploading
* the contents in chunks.
*
* Example:
* ```
* $uploader = $bucket->getStreamableUploader(
* 'initial contents',
* ['name' => 'data.txt']
* );
*
* // finish uploading the item
* $uploader->upload();
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable
* uploads.
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation.
*
* @param string|resource|StreamInterface $data The data to be uploaded.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination. Required when data is
* of type string or null.
* @type bool $validate Indicates whether or not validation will be
* applied using md5 hashing functionality. If true and the
* calculated hash does not match that of the upstream server the
* upload will be rejected.
* @type int $chunkSize If provided the upload will be done in chunks.
* The size must be in multiples of 262144 bytes. With chunking
* you have increased reliability at the risk of higher overhead.
* It is recommended to not use chunking.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type array $metadata The available options for metadata are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
* @type string $encryptionKey A base64 encoded AES-256 customer-supplied
* encryption key. If you would prefer to manage encryption
* utilizing the Cloud Key Management Service (KMS) please use the
* $metadata['kmsKeyName'] setting. Please note if using KMS the
* key ring must use the same location as the bucket.
* @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the
* customer-supplied encryption key. This value will be calculated
* from the `encryptionKey` on your behalf if not provided, but
* for best performance it is recommended to pass in a cached
* version of the already calculated SHA.
* }
* @return StreamableUploader
* @throws \InvalidArgumentException
*/
public function getStreamableUploader($data, array $options = [])
{
if ($this->isObjectNameRequired($data) && !isset($options['name'])) {
throw new \InvalidArgumentException('A name is required when data is of type string or null.');
}
return $this->connection->insertObject(
$this->formatEncryptionHeaders($options) + $this->identity + [
'data' => $data,
'streamable' => true,
'validate' => false
]
);
}
/**
* Lazily instantiates an object. There are no network requests made at this
* point.
*
* To see the operations that can be performed on an object please
* see {@see StorageObject}.
*
* Example:
* ```
* $object = $bucket->object('file.txt');
* ```
*
* @param string $name The name of the object to request.
* @param array $options [optional] {
* Configuration options.
*
* @type string $generation Request a specific revision of the object.
* @type string $encryptionKey A base64 encoded AES-256 customer-supplied
* encryption key. It will be neccesary to provide this when a key
* was used during the object's creation.
* @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the
* customer-supplied encryption key. This value will be calculated
* from the `encryptionKey` on your behalf if not provided, but
* for best performance it is recommended to pass in a cached
* version of the already calculated SHA.
* }
* @return StorageObject
*/
public function object($name, array $options = [])
{
$generation = $options['generation'] ?? null;
$encryptionKey = $options['encryptionKey'] ?? null;
$encryptionKeySHA256 = $options['encryptionKeySHA256'] ?? null;
return new StorageObject(
$this->connection,
$name,
$this->identity['bucket'],
$generation,
array_filter([
'requesterProjectId' => $this->identity['userProject']
]),
$encryptionKey,
$encryptionKeySHA256
);
}
/**
* Restores an object.
*
* Example:
* ```
* $object = $bucket->restore('file.txt');
* ```
*
* @param string $name The name of the object to restore.
* @param string $generation Request a specific generation of the object.
* @param array $options [optional] {
* Configuration Options.
*
* @type string $ifGenerationMatch Makes the operation conditional on whether
* the object's current generation matches the given value.
* @type string $ifGenerationNotMatch Makes the operation conditional on whether
* the object's current generation matches the given value.
* @type string $ifMetagenerationMatch If set, only restores
* if its metageneration matches this value.
* @type string $ifMetagenerationNotMatch If set, only restores
* if its metageneration does not match this value.
* }
* @return StorageObject
*/
public function restore($name, $generation, array $options = [])
{
$res = $this->connection->restoreObject([
'bucket' => $this->identity['bucket'],
'generation' => $generation,
'object' => $name,
] + $options);
return new StorageObject(
$this->connection,
$name,
$this->identity['bucket'],
$res['generation'], // restored object will have a new generation
$res + array_filter([
'requesterProjectId' => $this->identity['userProject']
])
);
}
/**
* Fetches all objects in the bucket.
*
* Example:
* ```
* // Get all objects beginning with the prefix 'photo'
* $objects = $bucket->objects([
* 'prefix' => 'photo',
* 'fields' => 'items/name,nextPageToken'
* ]);
*
* foreach ($objects as $object) {
* echo $object->name() . PHP_EOL;
* }
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/list Objects list API documentation.
*
* @param array $options [optional] {
* Configuration options.
*
* @type string $delimiter Returns results in a directory-like mode.
* Results will contain only objects whose names, aside from the
* prefix, do not contain delimiter. Objects whose names, aside
* from the prefix, contain delimiter will have their name,
* truncated after the delimiter, returned in prefixes. Duplicate
* prefixes are omitted.
* @type bool $includeFoldersAsPrefixes If true, will also include folders
* and managed folders (besides objects) in the returned prefixes.
* Only applicable if delimiter is set to '/'.
* @type int $maxResults Maximum number of results to return per
* request. **Defaults to** `1000`.
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* @type string $pageToken A previously-returned page token used to
* resume the loading of results from a specific point.
* @type string $prefix Filter results with this prefix.
* @type string $projection Determines which properties to return. May
* be either `"full"` or `"noAcl"`.
* @type bool $versions If true, lists all versions of an object as
* distinct results. **Defaults to** `false`.
* @type string $fields Selector which will cause the response to only
* return the specified fields.
* @type string $matchGlob A glob pattern to filter results. The string
* value must be UTF-8 encoded. See:
* https://cloud.google.com/storage/docs/json_api/v1/objects/list#list-object-glob
* }
* @return ObjectIterator<StorageObject>
*/
public function objects(array $options = [])
{
$resultLimit = $this->pluck('resultLimit', $options, false);
return new ObjectIterator(
new ObjectPageIterator(
function (array $object) {
return new StorageObject(
$this->connection,
$object['name'],
$this->identity['bucket'],
isset($object['generation']) ? $object['generation'] : null,
$object + array_filter([
'requesterProjectId' => $this->identity['userProject']
])
);
},
[$this->connection, 'listObjects'],
$options + $this->identity,
['resultLimit' => $resultLimit]
)
);
}
/**
* Create a Cloud PubSub notification.
*
* Please note, the desired topic must be given the IAM role of
* "pubsub.publisher" from the service account associated with the project
* which contains the bucket you would like to receive notifications from.
* Please see the example below for a programmatic example of achieving
* this.
*
* Example:
* ```
* // Update the permissions on the desired topic prior to creating the
* // notification.
* use Google\Cloud\Core\Iam\PolicyBuilder;
* use Google\Cloud\PubSub\PubSubClient;
*
* $pubSub = new PubSubClient();
* $topicName = 'my-topic';
* $serviceAccountEmail = $storage->getServiceAccount();
* $topic = $pubSub->topic($topicName);
* $iam = $topic->iam();
* $updatedPolicy = (new PolicyBuilder($iam->policy()))
* ->addBinding('roles/pubsub.publisher', [
* "serviceAccount:$serviceAccountEmail"
* ])
* ->result();
* $iam->setPolicy($updatedPolicy);
*
* $notification = $bucket->createNotification($topicName);
* ```
*
* ```
* // Use a fully qualified topic name.
* $notification = $bucket->createNotification('projects/my-project/topics/my-topic');
* ```
*
* ```
* // Provide a Topic object from the Cloud PubSub component.
* use Google\Cloud\PubSub\PubSubClient;
*
* $pubSub = new PubSubClient();
* $topic = $pubSub->topic('my-topic');
* $notification = $bucket->createNotification($topic);
* ```
*
* ```
* // Supplying event types to trigger the notifications.
* $notification = $bucket->createNotification('my-topic', [
* 'event_types' => [
* 'OBJECT_DELETE',
* 'OBJECT_METADATA_UPDATE'
* ]
* ]);
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/storage/docs/pubsub-notifications Cloud PubSub Notifications.
* @see https://cloud.google.com/storage/docs/json_api/v1/notifications/insert Notifications insert API documentation.
* @see https://cloud.google.com/storage/docs/reporting-changes Registering Object Changes.
* @codingStandardsIgnoreEnd
*
* @param string|Topic $topic The topic used to publish notifications.
* @param array $options [optional] {
* Configuration options.
*
* @type array $custom_attributes An optional list of additional
* attributes to attach to each Cloud PubSub message published for
* this notification subscription.
* @type array $event_types If present, only send notifications about
* listed event types. If empty, sent notifications for all event
* types. Acceptablue values include `"OBJECT_FINALIZE"`,
* `"OBJECT_METADATA_UPDATE"`, `"OBJECT_DELETE"`
* , `"OBJECT_ARCHIVE"`.
* @type string $object_name_prefix If present, only apply this
* notification configuration to object names that begin with this
* prefix.
* @type string $payload_format The desired content of the Payload.
* Acceptable values include `"JSON_API_V1"`, `"NONE"`.
* **Defaults to** `"JSON_API_V1"`.
* }
* @return Notification
* @throws \InvalidArgumentException When providing a type other than string
* or {@see \Google\Cloud\PubSub\Topic} as $topic.
* @throws GoogleException When a project ID has not been detected.
* @experimental The experimental flag means that while we believe this
* method or class is ready for use, it may change before release in
* backwards-incompatible ways. Please use with caution, and test
* thoroughly when upgrading.
*/
public function createNotification($topic, array $options = [])
{
$res = $this->connection->insertNotification($options + $this->identity + [
'topic' => $this->getFormattedTopic($topic),
'payload_format' => 'JSON_API_V1'
]);
return new Notification(
$this->connection,
$res['id'],
$this->identity['bucket'],
$res + [
'requesterProjectId' => $this->identity['userProject']
]
);
}
/**
* Lazily instantiates a notification. There are no network requests made at
* this point.
*
* To see the operations that can be performed on a notification
* please see {@see Notification}.
*
* Example:
* ```
* $notification = $bucket->notification('4582');
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/notifications#resource Notifications API documentation.
*
* @param string $id The ID of the notification to access.
* @return Notification
* @experimental The experimental flag means that while we believe this
* method or class is ready for use, it may change before release in
* backwards-incompatible ways. Please use with caution, and test
* thoroughly when upgrading.
*/
public function notification($id)
{
return new Notification(
$this->connection,
$id,
$this->identity['bucket'],
['requesterProjectId' => $this->identity['userProject']]
);
}
/**
* Fetches all notifications associated with this bucket.
*
* Example:
* ```
* $notifications = $bucket->notifications();
*
* foreach ($notifications as $notification) {
* echo $notification->id() . PHP_EOL;
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/storage/docs/json_api/v1/notifications/list Notifications list API documentation.
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] {
* Configuration options.
*
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* }
* @return ItemIterator<Notification>
* @experimental The experimental flag means that while we believe this
* method or class is ready for use, it may change before release in
* backwards-incompatible ways. Please use with caution, and test
* thoroughly when upgrading.
*/
public function notifications(array $options = [])
{
$resultLimit = $this->pluck('resultLimit', $options, false);
return new ItemIterator(
new PageIterator(
function (array $notification) {
return new Notification(
$this->connection,
$notification['id'],
$this->identity['bucket'],
$notification + [
'requesterProjectId' => $this->identity['userProject']
]
);
},
[$this->connection, 'listNotifications'],
$options + $this->identity,
['resultLimit' => $resultLimit]
)
);
}
/**
* Delete the bucket.
*
* Example:
* ```
* $bucket->delete();
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/buckets/delete Buckets delete API documentation.
*
* @param array $options [optional] {
* Configuration options.
* @type string $ifMetagenerationMatch If set, only deletes the bucket
* if its metageneration matches this value.
* @type string $ifMetagenerationNotMatch If set, only deletes the
* bucket if its metageneration does not match this value.
* }
* @return void
*/
public function delete(array $options = [])
{
$this->connection->deleteBucket($options + $this->identity);
}
/**
* Update the bucket. Upon receiving a result the local bucket's data will
* be updated.
*
* Example:
* ```
* // Enable logging on an existing bucket.
* $bucket->update([
* 'logging' => [
* 'logBucket' => 'myBucket',
* 'logObjectPrefix' => 'prefix'
* ]
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/buckets/patch Buckets patch API documentation.
* @see https://cloud.google.com/storage/docs/key-terms#bucket-labels Bucket Labels
*
* @codingStandardsIgnoreStart
* @param array $options [optional] {
* Configuration options.
*
* @type string $ifMetagenerationMatch Makes the return of the bucket
* metadata conditional on whether the bucket's current
* metageneration matches the given value.
* @type string $ifMetagenerationNotMatch Makes the return of the bucket
* metadata conditional on whether the bucket's current
* metageneration does not match the given value.
* @type string $predefinedAcl Predefined ACL to apply to the bucket.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type string $predefinedDefaultObjectAcl Apply a predefined set of
* default object access controls to this bucket. Acceptable
* values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type string $projection Determines which properties to return. May
* be either `"full"` or `"noAcl"`.
* @type string $fields Selector which will cause the response to only
* return the specified fields.
* @type array $acl Access controls on the bucket.
* @type array $cors The bucket's Cross-Origin Resource Sharing (CORS)
* configuration.
* @type array $defaultObjectAcl Default access controls to apply to new
* objects when no ACL is provided.
* @type array|Lifecycle $lifecycle The bucket's lifecycle configuration.
* @type array $logging The bucket's logging configuration, which
* defines the destination bucket and optional name prefix for the
* current bucket's logs.
* @type string $storageClass 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