-
Notifications
You must be signed in to change notification settings - Fork 443
/
Copy pathStorageObject.php
1276 lines (1220 loc) · 54 KB
/
StorageObject.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\NotFoundException;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Core\Upload\SignedUrlUploader;
use Google\Cloud\Storage\Connection\ConnectionInterface;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\StreamInterface;
/**
* Objects are the individual pieces of data that you store in Google Cloud
* Storage.
*
* Example:
* ```
* use Google\Cloud\Storage\StorageClient;
*
* $storage = new StorageClient();
*
* $bucket = $storage->bucket('my-bucket');
* $object = $bucket->object('my-object');
* ```
*/
class StorageObject
{
use ArrayTrait;
use EncryptionTrait;
/**
* @deprecated
*/
const DEFAULT_DOWNLOAD_URL = SigningHelper::DEFAULT_DOWNLOAD_HOST;
/**
* @var Acl ACL for the object.
*/
private $acl;
/**
* @var ConnectionInterface Represents a connection to Cloud Storage.
*/
protected $connection;
/**
* @var array|null The object's encryption data.
*/
private $encryptionData;
/**
* @var array The object's identity.
*/
private $identity;
/**
* @var array|null The object's metadata.
*/
private $info;
/**
* @param ConnectionInterface $connection Represents a connection to Cloud
* Storage.
* @param string $name The object's name.
* @param string $bucket The name of the bucket the object is contained in.
* @param string $generation [optional] The generation of the object.
* @param array $info [optional] The object's metadata.
* @param string $encryptionKey [optional] An AES-256 customer-supplied
* encryption key.
* @param string $encryptionKeySHA256 [optional] The SHA256 hash of the
* customer-supplied encryption key.
*/
public function __construct(
ConnectionInterface $connection,
$name,
$bucket,
$generation = null,
array $info = [],
$encryptionKey = null,
$encryptionKeySHA256 = null
) {
$this->connection = $connection;
$this->info = $info;
$this->encryptionData = [
'encryptionKey' => $encryptionKey,
'encryptionKeySHA256' => $encryptionKeySHA256
];
$this->identity = [
'bucket' => $bucket,
'object' => $name,
'generation' => $generation,
'userProject' => $this->pluck('requesterProjectId', $info, false)
];
$this->acl = new Acl($this->connection, 'objectAccessControls', $this->identity);
}
/**
* Configure ACL for this object.
*
* Example:
* ```
* $acl = $object->acl();
* ```
*
* @see https://cloud.google.com/storage/docs/access-control More about Access Control Lists
*
* @return Acl
*/
public function acl()
{
return $this->acl;
}
/**
* Check whether or not the object exists.
*
* Example:
* ```
* if ($object->exists()) {
* echo 'Object exists!';
* }
* ```
*
* @param array $options [optional] Configuration options.
* @return bool
*/
public function exists(array $options = [])
{
try {
$this->connection->getObject($this->identity + $options + ['fields' => 'name']);
} catch (NotFoundException $ex) {
return false;
}
return true;
}
/**
* Delete the object.
*
* Example:
* ```
* $object->delete();
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/delete Objects delete API documentation.
*
* @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 does not match the
* given value.
* @type string $ifMetagenerationMatch Makes the operation conditional
* on whether the object's current metageneration matches the
* given value.
* @type string $ifMetagenerationNotMatch Makes the operation
* conditional on whether the object's current metageneration does
* not match the given value.
* }
* @return void
*/
public function delete(array $options = [])
{
$this->connection->deleteObject($options + array_filter($this->identity));
}
/**
* Update the object. Upon receiving a result the local object's data will
* be updated.
*
* Example:
* ```
* // Add custom metadata to an existing object.
* $object->update([
* 'metadata' => [
* 'albumType' => 'family'
* ]
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/patch Objects patch API documentation.
*
* @param array $metadata The available options for metadata are outlined
* at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects#resource)
* @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 does not match the
* given value.
* @type string $ifMetagenerationMatch Makes the operation conditional
* on whether the object's current metageneration matches the
* given value.
* @type string $ifMetagenerationNotMatch Makes the operation
* conditional on whether the object's current metageneration does
* not match the given value.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* 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.
* }
* @return array
*/
public function update(array $metadata, array $options = [])
{
$options += $metadata;
// can only set predefinedAcl or acl
if (isset($options['predefinedAcl'])) {
$options['acl'] = null;
}
return $this->info = $this->connection->patchObject($options + array_filter($this->identity));
}
/**
* Copy the object to a destination bucket.
*
* Please note that if the destination bucket is the same as the source
* bucket and a new name is not provided the source object will be replaced
* with the copy of itself.
*
* Example:
* ```
* // Provide your destination bucket as a string and retain the source
* // object's name.
* $copiedObject = $object->copy('otherBucket');
* ```
*
* ```
* // Provide your destination bucket as a bucket object and choose a new
* // name for the copied object.
* $otherBucket = $storage->bucket('otherBucket');
* $copiedObject = $object->copy($otherBucket, [
* 'name' => 'newFile.txt'
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/copy Objects copy API documentation.
*
* @param Bucket|string $destination The destination bucket.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination object. **Defaults
* to** the name of the source object.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @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.
* @type string $ifGenerationMatch Makes the operation conditional on
* whether the destination object's current generation matches the
* given value.
* @type string $ifGenerationNotMatch Makes the operation conditional on
* whether the destination object's current generation does not
* match the given value.
* @type string $ifMetagenerationMatch Makes the operation conditional
* on whether the destination object's current metageneration
* matches the given value.
* @type string $ifMetagenerationNotMatch Makes the operation
* conditional on whether the destination object's current
* metageneration does not match the given value.
* @type string $ifSourceGenerationMatch Makes the operation conditional
* on whether the source object's current generation matches the
* given value.
* @type string $ifSourceGenerationNotMatch Makes the operation
* conditional on whether the source object's current generation
* does not match the given value.
* @type string $ifSourceMetagenerationMatch Makes the operation
* conditional on whether the source object's current
* metageneration matches the given value.
* @type string $ifSourceMetagenerationNotMatch Makes the operation
* conditional on whether the source object's current
* metageneration does not match the given value.
* }
* @return StorageObject
*/
public function copy($destination, array $options = [])
{
$key = isset($options['encryptionKey']) ? $options['encryptionKey'] : null;
$keySHA256 = isset($options['encryptionKeySHA256']) ? $options['encryptionKeySHA256'] : null;
$response = $this->connection->copyObject(
$this->formatDestinationRequest($destination, $options)
);
return new StorageObject(
$this->connection,
$response['name'],
$response['bucket'],
$response['generation'],
$response + ['requesterProjectId' => $this->identity['userProject']],
$key,
$keySHA256
);
}
/**
* Rewrite the object to a destination bucket.
*
* This method copies data using multiple requests so large objects can be
* copied with a normal length timeout per request rather than one very long
* timeout for a single request.
*
* Please note that if the destination bucket is the same as the source
* bucket and a new name is not provided the source object will be replaced
* with the copy of itself.
*
* Example:
* ```
* // Provide your destination bucket as a string and retain the source
* // object's name.
* $rewrittenObject = $object->rewrite('otherBucket');
* ```
*
* ```
* // Provide your destination bucket as a bucket object and choose a new
* // name for the copied object.
* $otherBucket = $storage->bucket('otherBucket');
* $rewrittenObject = $object->rewrite($otherBucket, [
* 'name' => 'newFile.txt'
* ]);
* ```
*
* ```
* // Rotate customer-supplied encryption keys.
* $key = file_get_contents(__DIR__ . '/key.txt');
* $destinationKey = base64_encode(openssl_random_pseudo_bytes(32)); // Make sure to remember your key.
*
* $rewrittenObject = $object->rewrite('otherBucket', [
* 'encryptionKey' => $key,
* 'destinationEncryptionKey' => $destinationKey
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite Objects rewrite API documentation.
* @see https://cloud.google.com/storage/docs/encryption#customer-supplied Customer-supplied encryption keys.
*
* @param Bucket|string $destination The destination bucket.
* @param array $options [optional] {
* Configuration options.
*
* @type string $name The name of the destination object. **Defaults
* to** the name of the source object.
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @type string $maxBytesRewrittenPerCall The maximum number of bytes
* that will be rewritten per rewrite request. Most callers
* shouldn't need to specify this parameter - it is primarily in
* place to support testing. If specified the value must be an
* integral multiple of 1 MiB (1048576). Also, this only applies
* to requests where the source and destination span locations
* and/or storage classes.
* @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.
* @type string $destinationEncryptionKey A base64 encoded AES-256
* customer-supplied encryption key that will be used to encrypt
* the rewritten object.
* @type string $destinationEncryptionKeySHA256 Base64 encoded SHA256
* hash of the customer-supplied destination encryption key. This
* value will be calculated from the `destinationEncryptionKey` 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 string $destinationKmsKeyName Name of the Cloud KMS key that
* will be used to encrypt the object. 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
* destination bucket.
* @type string $ifGenerationMatch Makes the operation conditional on
* whether the destination object's current generation matches the
* given value.
* @type string $ifGenerationNotMatch Makes the operation conditional on
* whether the destination object's current generation does not
* match the given value.
* @type string $ifMetagenerationMatch Makes the operation conditional
* on whether the destination object's current metageneration
* matches the given value.
* @type string $ifMetagenerationNotMatch Makes the operation
* conditional on whether the destination object's current
* metageneration does not match the given value.
* @type string $ifSourceGenerationMatch Makes the operation conditional
* on whether the source object's current generation matches the
* given value.
* @type string $ifSourceGenerationNotMatch Makes the operation
* conditional on whether the source object's current generation
* does not match the given value.
* @type string $ifSourceMetagenerationMatch Makes the operation
* conditional on whether the source object's current
* metageneration matches the given value.
* @type string $ifSourceMetagenerationNotMatch Makes the operation
* conditional on whether the source object's current
* metageneration does not match the given value.
* }
* @return StorageObject
* @throws \InvalidArgumentException
*/
public function rewrite($destination, array $options = [])
{
$options['useCopySourceHeaders'] = true;
$destinationKey = isset($options['destinationEncryptionKey']) ? $options['destinationEncryptionKey'] : null;
$destinationKeySHA256 = isset($options['destinationEncryptionKeySHA256'])
? $options['destinationEncryptionKeySHA256']
: null;
$options = $this->formatDestinationRequest($destination, $options);
do {
$response = $this->connection->rewriteObject($options);
$options['rewriteToken'] = isset($response['rewriteToken']) ? $response['rewriteToken'] : null;
} while ($options['rewriteToken']);
return new StorageObject(
$this->connection,
$response['resource']['name'],
$response['resource']['bucket'],
$response['resource']['generation'],
$response['resource'] + ['requesterProjectId' => $this->identity['userProject']],
$destinationKey,
$destinationKeySHA256
);
}
/**
* Renames the object.
*
* Please note that there is no atomic rename provided by the Storage API.
* This method is for convenience and is a set of sequential calls to copy
* and delete. Upon success the source object's metadata will be cleared,
* please use the returned object instead.
*
* Example:
* ```
* $object2 = $object->rename('object2.txt');
* echo $object2->name();
* ```
*
* @param string $name The new name.
* @param array $options [optional] {
* Configuration options.
*
* @type string $predefinedAcl Predefined ACL to apply to the object.
* Acceptable values include, `"authenticatedRead"`,
* `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
* `"projectPrivate"`, and `"publicRead"`.
* @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.
* @type string $ifGenerationMatch Makes the operation conditional on
* whether the destination object's current generation matches the
* given value.
* @type string $ifGenerationNotMatch Makes the operation conditional on
* whether the destination object's current generation does not
* match the given value.
* @type string $ifMetagenerationMatch Makes the operation conditional
* on whether the destination object's current metageneration
* matches the given value.
* @type string $ifMetagenerationNotMatch Makes the operation
* conditional on whether the destination object's current
* metageneration does not match the given value.
* @type string $ifSourceGenerationMatch Makes the operation conditional
* on whether the source object's current generation matches the
* given value.
* @type string $ifSourceGenerationNotMatch Makes the operation
* conditional on whether the source object's current generation
* does not match the given value.
* @type string $ifSourceMetagenerationMatch Makes the operation
* conditional on whether the source object's current
* metageneration matches the given value.
* @type string $ifSourceMetagenerationNotMatch Makes the operation
* conditional on whether the source object's current
* metageneration does not match the given value.
* @type string $destinationBucket Will move to this bucket if set. If
* not set, will default to the same bucket.
* }
* @return StorageObject The renamed object.
*/
public function rename($name, array $options = [])
{
$destinationBucket = isset($options['destinationBucket'])
? $options['destinationBucket']
: $this->identity['bucket'];
unset($options['destinationBucket']);
$copiedObject = $this->copy($destinationBucket, [
'name' => $name
] + $options);
$this->delete(
array_intersect_key($options, [
'restOptions' => null,
'retries' => null
])
);
$this->info = [];
return $copiedObject;
}
/**
* Download an object as a string.
*
* For an example of setting the range header to download a subrange of the
* object please see {@see Google\Cloud\Storage\StorageObject::downloadAsStream()}.
*
* Example:
* ```
* $string = $object->downloadAsString();
* echo $string;
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/get Objects get API documentation.
* @see https://cloud.google.com/storage/docs/json_api/v1/parameters#range Learn more about the Range header.
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $encryptionKey An AES-256 customer-supplied encryption
* key. It will be neccesary to provide this when a key was used
* during the object's creation. If provided one must also include
* an `encryptionKeySHA256`.
* @type string $encryptionKeySHA256 The SHA256 hash of the
* customer-supplied encryption key. It will be neccesary to
* provide this when a key was used during the object's creation.
* If provided one must also include an `encryptionKey`.
* }
* @return string
*/
public function downloadAsString(array $options = [])
{
return (string) $this->downloadAsStream($options);
}
/**
* Download an object to a specified location.
*
* For an example of setting the range header to download a subrange of the
* object please see {@see Google\Cloud\Storage\StorageObject::downloadAsStream()}.
*
* Example:
* ```
* $stream = $object->downloadToFile(__DIR__ . '/my-file.txt');
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/get Objects get API documentation.
* @see https://cloud.google.com/storage/docs/json_api/v1/parameters#range Learn more about the Range header.
*
* @param string $path Path to download the file to.
* @param array $options [optional] {
* Configuration Options.
*
* @type string $encryptionKey An AES-256 customer-supplied encryption
* key. It will be neccesary to provide this when a key was used
* during the object's creation. If provided one must also include
* an `encryptionKeySHA256`.
* @type string $encryptionKeySHA256 The SHA256 hash of the
* customer-supplied encryption key. It will be neccesary to
* provide this when a key was used during the object's creation.
* If provided one must also include an `encryptionKey`.
* }
* @return StreamInterface
*/
public function downloadToFile($path, array $options = [])
{
$destination = Utils::streamFor(fopen($path, 'w'));
Utils::copyToStream(
$this->downloadAsStream($options),
$destination
);
$destination->seek(0);
return $destination;
}
/**
* Download an object as a stream.
*
* Please note Google Cloud Storage respects the Range header as specified
* by [RFC7233](https://tools.ietf.org/html/rfc7233#section-3.1). See below
* for an example of this in action.
*
* Example:
* ```
* $stream = $object->downloadAsStream();
* echo $stream->getContents();
* ```
*
* ```
* // Set the Range header in order to download a subrange of the object. For more examples of
* // setting the Range header, please see [RFC7233](https://tools.ietf.org/html/rfc7233#section-3.1).
* $firstFiveBytes = '0-4'; // Get the first 5 bytes.
* $fromFifthByteToLastByte = '4-'; // Get the bytes starting with the 5th to the last.
* $lastFiveBytes = '-5'; // Get the last 5 bytes.
*
* $stream = $object->downloadAsStream([
* 'restOptions' => [
* 'headers' => [
* 'Range' => "bytes=$firstFiveBytes"
* ]
* ]
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/get Objects get API documentation.
* @see https://cloud.google.com/storage/docs/json_api/v1/parameters#range Learn more about the Range header.
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $encryptionKey An AES-256 customer-supplied encryption
* key. It will be neccesary to provide this when a key was used
* during the object's creation. If provided one must also include
* an `encryptionKeySHA256`.
* @type string $encryptionKeySHA256 The SHA256 hash of the
* customer-supplied encryption key. It will be neccesary to
* provide this when a key was used during the object's creation.
* If provided one must also include an `encryptionKey`.
* }
* @return StreamInterface
*/
public function downloadAsStream(array $options = [])
{
return $this->connection->downloadObject(
$this->formatEncryptionHeaders(
$options
+ $this->encryptionData
+ array_filter($this->identity)
)
);
}
/**
* Asynchronously download an object as a stream.
*
* For an example of setting the range header to download a subrange of the
* object please see {@see Google\Cloud\Storage\StorageObject::downloadAsStream()}.
*
* Example:
* ```
* use Psr\Http\Message\StreamInterface;
*
* $promise = $object->downloadAsStreamAsync()
* ->then(function (StreamInterface $data) {
* echo $data->getContents();
* });
*
* $promise->wait();
* ```
*
* ```
* // Download all objects in a bucket asynchronously.
* use GuzzleHttp\Promise;
* use Psr\Http\Message\StreamInterface;
*
* $promises = [];
*
* foreach ($bucket->objects() as $object) {
* $promises[] = $object->downloadAsStreamAsync()
* ->then(function (StreamInterface $data) {
* echo $data->getContents();
* });
* }
*
* Promise\unwrap($promises);
* ```
*
* @see https://cloud.google.com/storage/docs/json_api/v1/objects/get Objects get API documentation.
* @see https://cloud.google.com/storage/docs/json_api/v1/parameters#range Learn more about the Range header.
* @see https://github.com/guzzle/promises Learn more about Guzzle Promises
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $encryptionKey An AES-256 customer-supplied encryption
* key. It will be neccesary to provide this when a key was used
* during the object's creation. If provided one must also include
* an `encryptionKeySHA256`.
* @type string $encryptionKeySHA256 The SHA256 hash of the
* customer-supplied encryption key. It will be neccesary to
* provide this when a key was used during the object's creation.
* If provided one must also include an `encryptionKey`.
* }
* @return PromiseInterface<StreamInterface>
* @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 downloadAsStreamAsync(array $options = [])
{
return $this->connection->downloadObjectAsync(
$this->formatEncryptionHeaders(
$options
+ $this->encryptionData
+ array_filter($this->identity)
)
);
}
/**
* Create a Signed URL for this object.
*
* Signed URLs can be complex, and it is strongly recommended you read and
* understand the [documentation](https://cloud.google.com/storage/docs/access-control/signed-urls).
*
* In cases where a keyfile is available, signing is accomplished in the
* client using your Service Account private key. In Google Compute Engine,
* signing is accomplished using
* [IAM signBlob](https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob).
* Signing using IAM requires that your service account be granted the
* `iam.serviceAccounts.signBlob` permission, part of the "Service Account
* Token Creator" IAM role.
*
* Additionally, signing using IAM requires different scopes. When creating
* an instance of {@see Google\Cloud\Storage\StorageClient}, provide the
* `https://www.googleapis.com/auth/cloud-platform` scopein `$options.scopes`.
* This scope may be used entirely in place of the scopes provided in
* {@see Google\Cloud\Storage\StorageClient}.
*
* App Engine and Compute Engine will attempt to sign URLs using IAM.
*
* Example:
* ```
* $url = $object->signedUrl(new \DateTime('tomorrow'));
* ```
*
* ```
* // Create a signed URL allowing updates to the object.
* $url = $object->signedUrl(new \DateTime('tomorrow'), [
* 'method' => 'PUT'
* ]);
* ```
*
* ```
* // Use Signed URLs v4
* $url = $object->signedUrl(new \DateTime('tomorrow'), [
* 'version' => 'v4'
* ]);
* ```
*
* ```
* // Using Bucket-Bound hostnames
* // By default, a custom bucket-bound hostname will use `http` as the schema rather than `https`.
* // In order to get an https URI, we need to specify the proper scheme.
* $url = $object->signedUrl(new \DateTime('tomorrow'), [
* 'version' => 'v4',
* 'bucketBoundHostname' => 'cdn.example.com',
* 'scheme' => 'https'
* ]);
* ```
*
* ```
* // Using virtual hosted style URIs
* // When true, returns a URL with the hostname `<bucket>.storage.googleapis.com`.
* $url = $object->signedUrl(new \DateTime('tomorrow'), [
* 'virtualHostedStyle' => true
* ]);
* ````
*
* @see https://cloud.google.com/storage/docs/access-control/signed-urls Signed URLs
*
* @param Timestamp|\DateTimeInterface|int $expires Specifies when the URL
* will expire. May provide an instance of {@see Google\Cloud\Core\Timestamp},
* [http://php.net/datetimeimmutable](`\DateTimeImmutable`), or a
* UNIX timestamp as an integer.
* @param array $options {
* Configuration Options.
*
* @type string $bucketBoundHostname The hostname for the bucket, for
* instance `cdn.example.com`. May be used for Google Cloud Load
* Balancers or for custom bucket CNAMEs. **Defaults to**
* `storage.googleapis.com`.
* @type string $contentMd5 The MD5 digest value in base64. If you
* provide this, the client must provide this HTTP header with
* this same value in its request. If provided, take care to
* always provide this value as a base64 encoded string.
* @type string $contentType If you provide this value, the client must
* provide this HTTP header set to the same value.
* @type bool $forceOpenssl If true, OpenSSL will be used regardless of
* whether phpseclib is available. **Defaults to** `false`.
* @type array $headers If additional headers are provided, the server
* will check to make sure that the client provides matching
* values. Provide headers as a key/value array, where the key is
* the header name, and the value is an array of header values.
* Headers with multiple values may provide values as a simple
* array, or a comma-separated string. For a reference of allowed
* headers, see [Reference Headers](https://cloud.google.com/storage/docs/xml-api/reference-headers).
* Header values will be trimmed of leading and trailing spaces,
* multiple spaces within values will be collapsed to a single
* space, and line breaks will be replaced by an empty string.
* V2 Signed URLs may not provide `x-goog-encryption-key` or
* `x-goog-encryption-key-sha256` headers.
* @type array $keyFile Keyfile data to use in place of the keyfile with
* which the client was constructed. If `$options.keyFilePath` is
* set, this option is ignored.
* @type string $keyFilePath A path to a valid Keyfile to use in place
* of the keyfile with which the client was constructed.
* @type string $method One of `GET`, `PUT` or `DELETE`.
* **Defaults to** `GET`.
* @type string $responseDisposition The
* [`response-content-disposition`](http://www.iana.org/assignments/cont-disp/cont-disp.xhtml)
* parameter of the signed url.
* @type string $responseType The `response-content-type` parameter of the
* signed url. When the server contentType is `null`, this option
* may be used to control the content type of the response.
* @type string $saveAsName The filename to prompt the user to save the
* file as when the signed url is accessed. This is ignored if
* `$options.responseDisposition` is set.
* @type string $scheme Either `http` or `https`. Only used if a custom
* hostname is provided via `$options.bucketBoundHostname`. If a
* custom bucketBoundHostname is provided, **defaults to** `http`.
* In all other cases, **defaults to** `https`.
* @type string|array $scopes One or more authentication scopes to be
* used with a key file. This option is ignored unless
* `$options.keyFile` or `$options.keyFilePath` is set.
* @type array $queryParams Additional query parameters to be included
* as part of the signed URL query string. For allowed values,
* see [Reference Headers](https://cloud.google.com/storage/docs/xml-api/reference-headers#query).
* @type string $version One of "v2" or "v4". **Defaults to** `"v2"`.
* @type bool $virtualHostedStyle If `true`, URL will be of form
* `mybucket.storage.googleapis.com`. If `false`,
* `storage.googleapis.com/mybucket`. **Defaults to** `false`.
* }
* @return string
* @throws \InvalidArgumentException If the given expiration is invalid or in the past.
* @throws \InvalidArgumentException If the given `$options.method` is not valid.
* @throws \InvalidArgumentException If the given `$options.keyFilePath` is not valid.
* @throws \InvalidArgumentException If the given custom headers are invalid.
* @throws \InvalidArgumentException If the keyfile does not contain the required information.
* @throws \RuntimeException If the credentials provided cannot be used for signing strings.
*/
public function signedUrl($expires, array $options = [])
{
// May be overridden for testing.
$signingHelper = $this->pluck('helper', $options, false)
?: SigningHelper::getHelper();
$resource = sprintf(
'/%s/%s',
$this->identity['bucket'],
$this->identity['object']
);
return $signingHelper->sign(
$this->connection,
$expires,
$resource,
$this->identity['generation'],
$options
);
}
/**
* Create a Signed Upload URL for this object.
*
* This method differs from {@see Google\Cloud\Storage\StorageObject::signedUrl()}
* in that it allows you to initiate a new resumable upload session. This
* can be used to allow non-authenticated users to insert an object into a
* bucket.
*
* In order to upload data, a session URI must be
* obtained by sending an HTTP POST request to the URL returned from this
* method. See the [Cloud Storage Documentation](https://goo.gl/b1ZiZm) for
* more information.
*
* If you prefer to skip this initial step, you may find
* {@see Google\Cloud\Storage\StorageObject::beginSignedUploadSession()} to
* fit your needs. Note that `beginSignedUploadSession()` cannot be used
* with Google Cloud PHP's Signed URL Uploader, and does not support a
* configurable expiration date.
*
* Example:
* ```
* $url = $object->signedUploadUrl(new \DateTime('tomorrow'));
* ```
*
* ```
* // Use Signed URLs v4
* $url = $object->signedUploadUrl(new \DateTime('tomorrow'), [
* 'version' => 'v4'
* ]);
* ```
*
* @param Timestamp|\DateTimeInterface|int $expires Specifies when the URL
* will expire. May provide an instance of {@see Google\Cloud\Core\Timestamp},
* [http://php.net/datetimeimmutable](`\DateTimeImmutable`), or a
* UNIX timestamp as an integer.
* @param array $options {
* Configuration Options.
*
* @type string $contentMd5 The MD5 digest value in base64. If you
* provide this, the client must provide this HTTP header with
* this same value in its request. If provided, take care to
* always provide this value as a base64 encoded string.
* @type string $contentType If you provide this value, the client must
* provide this HTTP header set to the same value.
* @type bool $forceOpenssl If true, OpenSSL will be used regardless of
* whether phpseclib is available. **Defaults to** `false`.
* @type array $headers If additional headers are provided, the server
* will check to make sure that the client provides matching
* values. Provide headers as a key/value array, where the key is
* the header name, and the value is an array of header values.
* Headers with multiple values may provide values as a simple
* array, or a comma-separated string. For a reference of allowed
* headers, see [Reference Headers](https://cloud.google.com/storage/docs/xml-api/reference-headers).
* Header values will be trimmed of leading and trailing spaces,
* multiple spaces within values will be collapsed to a single
* space, and line breaks will be replaced by an empty string.
* V2 Signed URLs may not provide `x-goog-encryption-key` or
* `x-goog-encryption-key-sha256` headers.
* @type array $keyFile Keyfile data to use in place of the keyfile with
* which the client was constructed. If `$options.keyFilePath` is
* set, this option is ignored.
* @type string $keyFilePath A path to a valid Keyfile to use in place
* of the keyfile with which the client was constructed.
* @type string $responseDisposition The
* [`response-content-disposition`](http://www.iana.org/assignments/cont-disp/cont-disp.xhtml)
* parameter of the signed url.
* @type string $responseType The `response-content-type` parameter of the
* signed url. When the server contentType is `null`, this option
* may be used to control the content type of the response.
* @type string $saveAsName The filename to prompt the user to save the
* file as when the signed url is accessed. This is ignored if
* `$options.responseDisposition` is set.
* @type string $scheme Either `http` or `https`. Only used if a custom
* hostname is provided via `$options.bucketBoundHostname`. In all
* other cases, `https` is used. When a custom bucketBoundHostname
* is provided, **defaults to** `http`.
* @type string|array $scopes One or more authentication scopes to be
* used with a key file. This option is ignored unless
* `$options.keyFile` or `$options.keyFilePath` is set.
* @type array $queryParams Additional query parameters to be included
* as part of the signed URL query string. For allowed values,
* see [Reference Headers](https://cloud.google.com/storage/docs/xml-api/reference-headers#query).
* @type string $version One of "v2" or "v4". **Defaults to** `"v2"`.
* }
* @return string
*/
public function signedUploadUrl($expires, array $options = [])
{
$options += [
'headers' => []
];
$options['headers']['x-goog-resumable'] = 'start';
unset(
$options['cname'],
$options['bucketBoundHostname'],