-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathAwsS3Adapter.php
723 lines (632 loc) · 17.1 KB
/
AwsS3Adapter.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
<?php
namespace League\Flysystem\AwsS3v3;
use Aws\Result;
use Aws\S3\Exception\DeleteMultipleObjectsException;
use Aws\S3\Exception\S3Exception;
use Aws\S3\Exception\S3MultipartUploadException;
use Aws\S3\S3Client;
use Aws\S3\S3ClientInterface;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Adapter\AbstractAdapter;
use League\Flysystem\Adapter\CanOverwriteFiles;
use League\Flysystem\Config;
use League\Flysystem\Util;
class AwsS3Adapter extends AbstractAdapter implements CanOverwriteFiles
{
const PUBLIC_GRANT_URI = 'http://acs.amazonaws.com/groups/global/AllUsers';
/**
* @var array
*/
protected static $resultMap = [
'Body' => 'contents',
'ContentLength' => 'size',
'ContentType' => 'mimetype',
'Size' => 'size',
'Metadata' => 'metadata',
'StorageClass' => 'storageclass',
'ETag' => 'etag',
'VersionId' => 'versionid'
];
/**
* @var array
*/
protected static $metaOptions = [
'ACL',
'CacheControl',
'ContentDisposition',
'ContentEncoding',
'ContentLength',
'ContentMD5',
'ContentType',
'Expires',
'GrantFullControl',
'GrantRead',
'GrantReadACP',
'GrantWriteACP',
'Metadata',
'RequestPayer',
'SSECustomerAlgorithm',
'SSECustomerKey',
'SSECustomerKeyMD5',
'SSEKMSKeyId',
'ServerSideEncryption',
'StorageClass',
'Tagging',
'WebsiteRedirectLocation',
];
/**
* @var S3ClientInterface
*/
protected $s3Client;
/**
* @var string
*/
protected $bucket;
/**
* @var array
*/
protected $options = [];
/**
* @var bool
*/
private $streamReads;
public function __construct(S3ClientInterface $client, $bucket, $prefix = '', array $options = [], $streamReads = true)
{
$this->s3Client = $client;
$this->bucket = $bucket;
$this->setPathPrefix($prefix);
$this->options = $options;
$this->streamReads = $streamReads;
}
/**
* Get the S3Client bucket.
*
* @return string
*/
public function getBucket()
{
return $this->bucket;
}
/**
* Set the S3Client bucket.
*
* @return string
*/
public function setBucket($bucket)
{
$this->bucket = $bucket;
}
/**
* Get the S3Client instance.
*
* @return S3ClientInterface
*/
public function getClient()
{
return $this->s3Client;
}
/**
* Write a new file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return false|array false on failure file meta data on success
*/
public function write($path, $contents, Config $config)
{
return $this->upload($path, $contents, $config);
}
/**
* Update a file.
*
* @param string $path
* @param string $contents
* @param Config $config Config object
*
* @return false|array false on failure file meta data on success
*/
public function update($path, $contents, Config $config)
{
return $this->upload($path, $contents, $config);
}
/**
* Rename a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function rename($path, $newpath)
{
if ( ! $this->copy($path, $newpath)) {
return false;
}
return $this->delete($path);
}
/**
* Delete a file.
*
* @param string $path
*
* @return bool
*/
public function delete($path)
{
$location = $this->applyPathPrefix($path);
$command = $this->s3Client->getCommand(
'deleteObject',
[
'Bucket' => $this->bucket,
'Key' => $location,
]
);
$this->s3Client->execute($command);
return ! $this->has($path);
}
/**
* Delete a directory.
*
* @param string $dirname
*
* @return bool
*/
public function deleteDir($dirname)
{
try {
$prefix = $this->applyPathPrefix($dirname) . '/';
$this->s3Client->deleteMatchingObjects($this->bucket, $prefix);
} catch (DeleteMultipleObjectsException $exception) {
return false;
}
return true;
}
/**
* Create a directory.
*
* @param string $dirname directory name
* @param Config $config
*
* @return bool|array
*/
public function createDir($dirname, Config $config)
{
return $this->upload($dirname . '/', '', $config);
}
/**
* Check whether a file exists.
*
* @param string $path
*
* @return bool
*/
public function has($path)
{
$location = $this->applyPathPrefix($path);
if ($this->s3Client->doesObjectExist($this->bucket, $location, $this->options)) {
return true;
}
return $this->doesDirectoryExist($location);
}
/**
* Read a file.
*
* @param string $path
*
* @return false|array
*/
public function read($path)
{
$response = $this->readObject($path);
if ($response !== false) {
$response['contents'] = $response['contents']->getContents();
}
return $response;
}
/**
* List contents of a directory.
*
* @param string $directory
* @param bool $recursive
*
* @return array
*/
public function listContents($directory = '', $recursive = false)
{
$prefix = $this->applyPathPrefix(rtrim($directory, '/') . '/');
$options = ['Bucket' => $this->bucket, 'Prefix' => ltrim($prefix, '/')];
if ($recursive === false) {
$options['Delimiter'] = '/';
}
$listing = $this->retrievePaginatedListing($options);
$normalizer = [$this, 'normalizeResponse'];
$normalized = array_map($normalizer, $listing);
return Util::emulateDirectories($normalized);
}
/**
* @param array $options
*
* @return array
*/
protected function retrievePaginatedListing(array $options)
{
$resultPaginator = $this->s3Client->getPaginator('ListObjectsV2', $options);
$listing = [];
foreach ($resultPaginator as $result) {
$listing = array_merge($listing, $result->get('Contents') ?: [], $result->get('CommonPrefixes') ?: []);
}
return $listing;
}
/**
* Get all the meta data of a file or directory.
*
* @param string $path
*
* @return false|array
*/
public function getMetadata($path)
{
$command = $this->s3Client->getCommand(
'headObject',
[
'Bucket' => $this->bucket,
'Key' => $this->applyPathPrefix($path),
] + $this->options
);
/* @var Result $result */
try {
$result = $this->s3Client->execute($command);
} catch (S3Exception $exception) {
if ($this->is404Exception($exception)) {
return false;
}
throw $exception;
}
return $this->normalizeResponse($result->toArray(), $path);
}
/**
* @return bool
*/
private function is404Exception(S3Exception $exception)
{
$response = $exception->getResponse();
if ($response !== null && $response->getStatusCode() === 404) {
return true;
}
return false;
}
/**
* Get all the meta data of a file or directory.
*
* @param string $path
*
* @return false|array
*/
public function getSize($path)
{
return $this->getMetadata($path);
}
/**
* Get the mimetype of a file.
*
* @param string $path
*
* @return false|array
*/
public function getMimetype($path)
{
return $this->getMetadata($path);
}
/**
* Get the timestamp of a file.
*
* @param string $path
*
* @return false|array
*/
public function getTimestamp($path)
{
return $this->getMetadata($path);
}
/**
* Write a new file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function writeStream($path, $resource, Config $config)
{
return $this->upload($path, $resource, $config);
}
/**
* Update a file using a stream.
*
* @param string $path
* @param resource $resource
* @param Config $config Config object
*
* @return array|false false on failure file meta data on success
*/
public function updateStream($path, $resource, Config $config)
{
return $this->upload($path, $resource, $config);
}
/**
* Copy a file.
*
* @param string $path
* @param string $newpath
*
* @return bool
*/
public function copy($path, $newpath)
{
try {
$this->s3Client->copy(
$this->bucket,
$this->applyPathPrefix($path),
$this->bucket,
$this->applyPathPrefix($newpath),
$this->getRawVisibility($path) === AdapterInterface::VISIBILITY_PUBLIC
? 'public-read' : 'private',
$this->options
);
} catch (S3Exception $e) {
return false;
}
return true;
}
/**
* Read a file as a stream.
*
* @param string $path
*
* @return array|false
*/
public function readStream($path)
{
$response = $this->readObject($path);
if ($response !== false) {
$response['stream'] = $response['contents']->detach();
unset($response['contents']);
}
return $response;
}
/**
* Read an object and normalize the response.
*
* @param string $path
*
* @return array|bool
*/
protected function readObject($path)
{
$options = [
'Bucket' => $this->bucket,
'Key' => $this->applyPathPrefix($path),
] + $this->options;
if ($this->streamReads && ! isset($options['@http']['stream'])) {
$options['@http']['stream'] = true;
}
$command = $this->s3Client->getCommand('getObject', $options + $this->options);
try {
/** @var Result $response */
$response = $this->s3Client->execute($command);
} catch (S3Exception $e) {
return false;
}
return $this->normalizeResponse($response->toArray(), $path);
}
/**
* Set the visibility for a file.
*
* @param string $path
* @param string $visibility
*
* @return array|false file meta data
*/
public function setVisibility($path, $visibility)
{
$command = $this->s3Client->getCommand(
'putObjectAcl',
[
'Bucket' => $this->bucket,
'Key' => $this->applyPathPrefix($path),
'ACL' => $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private',
]
);
try {
$this->s3Client->execute($command);
} catch (S3Exception $exception) {
return false;
}
return compact('path', 'visibility');
}
/**
* Get the visibility of a file.
*
* @param string $path
*
* @return array|false
*/
public function getVisibility($path)
{
return ['visibility' => $this->getRawVisibility($path)];
}
/**
* {@inheritdoc}
*/
public function applyPathPrefix($path)
{
return ltrim(parent::applyPathPrefix($path), '/');
}
/**
* {@inheritdoc}
*/
public function setPathPrefix($prefix)
{
$prefix = ltrim((string) $prefix, '/');
return parent::setPathPrefix($prefix);
}
/**
* Get the object acl presented as a visibility.
*
* @param string $path
*
* @return string
*/
protected function getRawVisibility($path)
{
$command = $this->s3Client->getCommand(
'getObjectAcl',
[
'Bucket' => $this->bucket,
'Key' => $this->applyPathPrefix($path),
]
);
$result = $this->s3Client->execute($command);
$visibility = AdapterInterface::VISIBILITY_PRIVATE;
foreach ($result->get('Grants') as $grant) {
if (
isset($grant['Grantee']['URI'])
&& $grant['Grantee']['URI'] === self::PUBLIC_GRANT_URI
&& $grant['Permission'] === 'READ'
) {
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
break;
}
}
return $visibility;
}
/**
* Upload an object.
*
* @param string $path
* @param string|resource $body
* @param Config $config
*
* @return array|bool
*/
protected function upload($path, $body, Config $config)
{
$key = $this->applyPathPrefix($path);
$options = $this->getOptionsFromConfig($config);
$acl = array_key_exists('ACL', $options) ? $options['ACL'] : 'private';
if (!$this->isOnlyDir($path)) {
if ( ! isset($options['ContentType'])) {
$options['ContentType'] = Util::guessMimeType($path, $body);
}
if ( ! isset($options['ContentLength'])) {
$options['ContentLength'] = is_resource($body) ? Util::getStreamSize($body) : Util::contentSize($body);
}
if ($options['ContentLength'] === null) {
unset($options['ContentLength']);
}
}
try {
$this->s3Client->upload($this->bucket, $key, $body, $acl, ['params' => $options]);
} catch (S3MultipartUploadException $multipartUploadException) {
return false;
}
return $this->normalizeResponse($options, $path);
}
/**
* Check if the path contains only directories
*
* @param string $path
*
* @return bool
*/
private function isOnlyDir($path)
{
return substr($path, -1) === '/';
}
/**
* Get options from the config.
*
* @param Config $config
*
* @return array
*/
protected function getOptionsFromConfig(Config $config)
{
$options = $this->options;
if ($visibility = $config->get('visibility')) {
// For local reference
$options['visibility'] = $visibility;
// For external reference
$options['ACL'] = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private';
}
if ($mimetype = $config->get('mimetype')) {
// For local reference
$options['mimetype'] = $mimetype;
// For external reference
$options['ContentType'] = $mimetype;
}
foreach (static::$metaOptions as $option) {
if ( ! $config->has($option)) {
continue;
}
$options[$option] = $config->get($option);
}
return $options;
}
/**
* Normalize the object result array.
*
* @param array $response
* @param string $path
*
* @return array
*/
protected function normalizeResponse(array $response, $path = null)
{
$result = [
'path' => $path ?: $this->removePathPrefix(
isset($response['Key']) ? $response['Key'] : $response['Prefix']
),
];
$result = array_merge($result, Util::pathinfo($result['path']));
if (isset($response['LastModified'])) {
$result['timestamp'] = strtotime($response['LastModified']);
}
if ($this->isOnlyDir($result['path'])) {
$result['type'] = 'dir';
$result['path'] = rtrim($result['path'], '/');
return $result;
}
return array_merge($result, Util::map($response, static::$resultMap), ['type' => 'file']);
}
/**
* @param string $location
*
* @return bool
*/
protected function doesDirectoryExist($location)
{
// Maybe this isn't an actual key, but a prefix.
// Do a prefix listing of objects to determine.
$command = $this->s3Client->getCommand(
'ListObjectsV2',
[
'Bucket' => $this->bucket,
'Prefix' => rtrim($location, '/') . '/',
'MaxKeys' => 1,
]
);
try {
$result = $this->s3Client->execute($command);
return $result['Contents'] || $result['CommonPrefixes'];
} catch (S3Exception $e) {
if (in_array($e->getStatusCode(), [403, 404], true)) {
return false;
}
throw $e;
}
}
}