Completed
Push — master ( 293185...9c8cd6 )
by Frank
03:36
created

AwsS3Adapter::upload()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.116

Importance

Changes 4
Bugs 2 Features 0
Metric Value
c 4
b 2
f 0
dl 0
loc 22
ccs 13
cts 15
cp 0.8667
rs 6.9811
cc 7
eloc 12
nc 24
nop 3
crap 7.116
1
<?php
2
3
namespace League\Flysystem\AwsS3v3;
4
5
use Aws\Result;
6
use Aws\S3\Exception\DeleteMultipleObjectsException;
7
use Aws\S3\Exception\S3Exception;
8
use Aws\S3\S3Client;
9
use League\Flysystem\Adapter\AbstractAdapter;
10
use League\Flysystem\AdapterInterface;
11
use League\Flysystem\Config;
12
use League\Flysystem\Util;
13
14
class AwsS3Adapter extends AbstractAdapter
15
{
16
    const PUBLIC_GRANT_URI = 'http://acs.amazonaws.com/groups/global/AllUsers';
17
18
    /**
19
     * @var array
20
     */
21
    protected static $resultMap = [
22
        'Body' => 'contents',
23
        'ContentLength' => 'size',
24
        'ContentType' => 'mimetype',
25
        'Size' => 'size',
26
    ];
27
28
    /**
29
     * @var array
30
     */
31
    protected static $metaOptions = [
32
        'CacheControl',
33
        'Expires',
34
        'StorageClass',
35
        'ServerSideEncryption',
36
        'Metadata',
37
        'ACL',
38
        'ContentType',
39
        'ContentEncoding',
40
        'ContentDisposition',
41
        'ContentLength',
42
    ];
43
44
    /**
45
     * @var S3Client
46
     */
47
    protected $s3Client;
48
49
    /**
50
     * @var string
51
     */
52
    protected $bucket;
53
54
    /**
55
     * @var array
56
     */
57
    protected $options = [];
58
59
    /**
60
     * Constructor.
61
     *
62
     * @param S3Client $client
63
     * @param string   $bucket
64
     * @param string   $prefix
65
     * @param array    $options
66
     */
67 68
    public function __construct(S3Client $client, $bucket, $prefix = '', array $options = [])
68
    {
69 68
        $this->s3Client = $client;
70 68
        $this->bucket = $bucket;
71 68
        $this->setPathPrefix($prefix);
72 68
        $this->options = $options;
73 68
    }
74
75
    /**
76
     * Get the S3Client bucket.
77
     *
78
     * @return string
79
     */
80 2
    public function getBucket()
81
    {
82 2
        return $this->bucket;
83
    }
84
85
    /**
86
     * Get the S3Client instance.
87
     *
88
     * @return S3Client
89
     */
90 2
    public function getClient()
91
    {
92 2
        return $this->s3Client;
93
    }
94
95
    /**
96
     * Write a new file.
97
     *
98
     * @param string $path
99
     * @param string $contents
100
     * @param Config $config Config object
101
     *
102
     * @return false|array false on failure file meta data on success
103
     */
104 2
    public function write($path, $contents, Config $config)
105
    {
106 2
        return $this->upload($path, $contents, $config);
107
    }
108
109
    /**
110
     * Update a file.
111
     *
112
     * @param string $path
113
     * @param string $contents
114
     * @param Config $config Config object
115
     *
116
     * @return false|array false on failure file meta data on success
117
     */
118 2
    public function update($path, $contents, Config $config)
119
    {
120 2
        return $this->upload($path, $contents, $config);
121
    }
122
123
    /**
124
     * Rename a file.
125
     *
126
     * @param string $path
127
     * @param string $newpath
128
     *
129
     * @return bool
130
     */
131 4
    public function rename($path, $newpath)
132
    {
133 4
        if ( ! $this->copy($path, $newpath)) {
134 2
            return false;
135
        }
136
137 2
        return $this->delete($path);
138
    }
139
140
    /**
141
     * Delete a file.
142
     *
143
     * @param string $path
144
     *
145
     * @return bool
146
     */
147 6
    public function delete($path)
148
    {
149 4
        $location = $this->applyPathPrefix($path);
150
151 4
        $command = $this->s3Client->getCommand(
152 4
            'deleteObject',
153
            [
154 4
                'Bucket' => $this->bucket,
155 4
                'Key' => $location,
156
            ]
157 6
        );
158
159 4
        $this->s3Client->execute($command);
160
161 4
        return ! $this->has($path);
162
    }
163
164
    /**
165
     * Delete a directory.
166
     *
167
     * @param string $dirname
168
     *
169
     * @return bool
170
     */
171 4
    public function deleteDir($dirname)
172
    {
173
        try {
174 4
            $prefix = $this->applyPathPrefix($dirname) . '/';
175 4
            $this->s3Client->deleteMatchingObjects($this->bucket, $prefix);
176 4
        } catch (DeleteMultipleObjectsException $exception) {
177 2
            return false;
178
        }
179
180 2
        return true;
181
    }
182
183
    /**
184
     * Create a directory.
185
     *
186
     * @param string $dirname directory name
187
     * @param Config $config
188
     *
189
     * @return bool|array
190
     */
191 2
    public function createDir($dirname, Config $config)
192
    {
193 2
        return $this->upload($dirname . '/', '', $config);
194
    }
195
196
    /**
197
     * Check whether a file exists.
198
     *
199
     * @param string $path
200
     *
201
     * @return bool
202
     */
203 12
    public function has($path)
204
    {
205 12
        $location = $this->applyPathPrefix($path);
206
207 12
        if ($this->s3Client->doesObjectExist($this->bucket, $location)) {
208 2
            return true;
209
        }
210
211 10
        return $this->doesDirectoryExist($location);
212
    }
213
214
    /**
215
     * Read a file.
216
     *
217
     * @param string $path
218
     *
219
     * @return false|array
220
     */
221 4
    public function read($path)
222
    {
223 4
        $response = $this->readObject($path);
224
225 4
        if ($response !== false) {
226 2
            $response['contents'] = $response['contents']->getContents();
227 2
        }
228
229 4
        return $response;
230
    }
231
232
    /**
233
     * List contents of a directory.
234
     *
235
     * @param string $directory
236
     * @param bool   $recursive
237
     *
238
     * @return array
239
     */
240 2
    public function listContents($directory = '', $recursive = false)
241
    {
242 2
        $prefix = $this->applyPathPrefix(rtrim($directory, '/') . '/');
243 2
        $options = ['Bucket' => $this->bucket, 'Prefix' => ltrim($prefix, '/')];
244
245 2
        if ($recursive === false) {
246 2
            $options['Delimiter'] = '/';
247 2
        }
248
249 2
        $listing = $this->retrievePaginatedListing($options);
250 2
        $normalizer = [$this, 'normalizeResponse'];
251 2
        $normalized = array_map($normalizer, $listing);
252
253 2
        return Util::emulateDirectories($normalized);
254
    }
255
256
    /**
257
     * @param array $options
258
     *
259
     * @return array
260
     */
261 2
    protected function retrievePaginatedListing(array $options)
262
    {
263 2
        $resultPaginator = $this->s3Client->getPaginator('ListObjects', $options);
264 2
        $listing = [];
265
266 2
        foreach ($resultPaginator as $result) {
267
            $listing = array_merge($listing, $result->get('Contents') ?: [], $result->get('CommonPrefixes') ?: []);
268 2
        }
269
270 2
        return $listing;
271
    }
272
273
    /**
274
     * Get all the meta data of a file or directory.
275
     *
276
     * @param string $path
277
     *
278
     * @return false|array
279
     */
280 12
    public function getMetadata($path)
281
    {
282 12
        $command = $this->s3Client->getCommand(
283 12
            'headObject',
284
            [
285 12
                'Bucket' => $this->bucket,
286 12
                'Key' => $this->applyPathPrefix($path),
287
            ]
288 12
        );
289
290
        /* @var Result $result */
291
        try {
292 12
            $result = $this->s3Client->execute($command);
293 12
        } catch (S3Exception $exception) {
294 4
            $response = $exception->getResponse();
295
296 4
            if ($response !== null && $response->getStatusCode() === 404) {
297 2
                return false;
298
            }
299
300 2
            throw $exception;
301
        }
302
303 8
        return $this->normalizeResponse($result->toArray(), $path);
304
    }
305
306
    /**
307
     * Get all the meta data of a file or directory.
308
     *
309
     * @param string $path
310
     *
311
     * @return false|array
312
     */
313 2
    public function getSize($path)
314
    {
315 2
        return $this->getMetadata($path);
316
    }
317
318
    /**
319
     * Get the mimetype of a file.
320
     *
321
     * @param string $path
322
     *
323
     * @return false|array
324
     */
325 2
    public function getMimetype($path)
326
    {
327 2
        return $this->getMetadata($path);
328
    }
329
330
    /**
331
     * Get the timestamp of a file.
332
     *
333
     * @param string $path
334
     *
335
     * @return false|array
336
     */
337 2
    public function getTimestamp($path)
338
    {
339 2
        return $this->getMetadata($path);
340
    }
341
342
    /**
343
     * Write a new file using a stream.
344
     *
345
     * @param string   $path
346
     * @param resource $resource
347
     * @param Config   $config Config object
348
     *
349
     * @return array|false false on failure file meta data on success
350
     */
351 2
    public function writeStream($path, $resource, Config $config)
352
    {
353 2
        return $this->upload($path, $resource, $config);
354
    }
355
356
    /**
357
     * Update a file using a stream.
358
     *
359
     * @param string   $path
360
     * @param resource $resource
361
     * @param Config   $config Config object
362
     *
363
     * @return array|false false on failure file meta data on success
364
     */
365 2
    public function updateStream($path, $resource, Config $config)
366
    {
367 2
        return $this->upload($path, $resource, $config);
368
    }
369
370
    /**
371
     * Copy a file.
372
     *
373
     * @param string $path
374
     * @param string $newpath
375
     *
376
     * @return bool
377
     */
378 8
    public function copy($path, $newpath)
379
    {
380 8
        $command = $this->s3Client->getCommand(
381 8
            'copyObject',
382
            [
383 8
                'Bucket' => $this->bucket,
384 8
                'Key' => $this->applyPathPrefix($newpath),
385 8
                'CopySource' => urlencode($this->bucket . '/' . $this->applyPathPrefix($path)),
386 8
                'ACL' => $this->getRawVisibility($path) === AdapterInterface::VISIBILITY_PUBLIC
387 8
                    ? 'public-read' : 'private',
388 8
            ] + $this->options
389 8
        );
390
391
        try {
392 8
            $this->s3Client->execute($command);
393 8
        } catch (S3Exception $e) {
394 4
            return false;
395
        }
396
397 4
        return true;
398
    }
399
400
    /**
401
     * Read a file as a stream.
402
     *
403
     * @param string $path
404
     *
405
     * @return array|false
406
     */
407 2
    public function readStream($path)
408
    {
409 2
        $response = $this->readObject($path);
410
411 2
        if ($response !== false) {
412 2
            $response['stream'] = $response['contents']->detach();
413 2
            unset($response['contents']);
414 2
        }
415
416 2
        return $response;
417
    }
418
419
    /**
420
     * Read an object and normalize the response.
421
     *
422
     * @param $path
423
     *
424
     * @return array|bool
425
     */
426 6
    protected function readObject($path)
427
    {
428 6
        $command = $this->s3Client->getCommand(
429 6
            'getObject',
430
            [
431 6
                'Bucket' => $this->bucket,
432 6
                'Key' => $this->applyPathPrefix($path),
433
                '@http' => [
434 6
                    'stream' => true,
435 6
                ],
436
            ]
437 6
        );
438
439
        try {
440
            /** @var Result $response */
441 6
            $response = $this->s3Client->execute($command);
442 6
        } catch (S3Exception $e) {
443 2
            return false;
444
        }
445
446 4
        return $this->normalizeResponse($response->toArray(), $path);
447
    }
448
449
    /**
450
     * Set the visibility for a file.
451
     *
452
     * @param string $path
453
     * @param string $visibility
454
     *
455
     * @return array|false file meta data
456
     */
457 6
    public function setVisibility($path, $visibility)
458
    {
459 6
        $command = $this->s3Client->getCommand(
460 6
            'putObjectAcl',
461
            [
462 6
                'Bucket' => $this->bucket,
463 6
                'Key' => $this->applyPathPrefix($path),
464 6
                'ACL' => $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private',
465
            ]
466 6
        );
467
468
        try {
469 6
            $this->s3Client->execute($command);
470 6
        } catch (S3Exception $exception) {
471 2
            return false;
472
        }
473
474 4
        return compact('path', 'visibility');
475
    }
476
477
    /**
478
     * Get the visibility of a file.
479
     *
480
     * @param string $path
481
     *
482
     * @return array|false
483
     */
484 4
    public function getVisibility($path)
485
    {
486 4
        return ['visibility' => $this->getRawVisibility($path)];
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492 62
    public function applyPathPrefix($prefix)
493
    {
494 62
        return ltrim(parent::applyPathPrefix($prefix), '/');
495
    }
496
497
    /**
498
     * {@inheritdoc}
499
     */
500 68
    public function setPathPrefix($prefix)
501
    {
502 68
        $prefix = ltrim($prefix, '/');
503
504 68
        return parent::setPathPrefix($prefix);
505
    }
506
507
    /**
508
     * Get the object acl presented as a visibility.
509
     *
510
     * @param string $path
511
     *
512
     * @return string
513
     */
514 12
    protected function getRawVisibility($path)
515
    {
516 12
        $command = $this->s3Client->getCommand(
517 12
            'getObjectAcl',
518
            [
519 12
                'Bucket' => $this->bucket,
520 12
                'Key' => $this->applyPathPrefix($path),
521
            ]
522 12
        );
523
524 12
        $result = $this->s3Client->execute($command);
525 12
        $visibility = AdapterInterface::VISIBILITY_PRIVATE;
526
527 12
        foreach ($result->get('Grants') as $grant) {
528
            if (
529 2
                isset($grant['Grantee']['URI'])
530 2
                && $grant['Grantee']['URI'] === self::PUBLIC_GRANT_URI
531 2
                && $grant['Permission'] === 'READ'
532 2
            ) {
533 2
                $visibility = AdapterInterface::VISIBILITY_PUBLIC;
534 2
                break;
535
            }
536 12
        }
537
538 12
        return $visibility;
539
    }
540
541
    /**
542
     * Upload an object.
543
     *
544
     * @param        $path
545
     * @param        $body
546
     * @param Config $config
547
     *
548
     * @return array
549
     */
550 10
    protected function upload($path, $body, Config $config)
551
    {
552 10
        $key = $this->applyPathPrefix($path);
553 10
        $options = $this->getOptionsFromConfig($config);
554 10
        $acl = isset($options['ACL']) ? $options['ACL'] : 'private';
555
556 10
        if ( ! isset($options['ContentType']) && is_string($body)) {
557 2
            $options['ContentType'] = Util::guessMimeType($path, $body);
558 2
        }
559
560 10
        if ( ! isset($options['ContentLength'])) {
561 10
            $options['ContentLength'] = is_string($body) ? Util::contentSize($body) : Util::getStreamSize($body);
562 10
        }
563
564 10
        if ($options['ContentLength'] === null) {
565
            unset($options['ContentLength']);
566
        }
567
568 10
        $this->s3Client->upload($this->bucket, $key, $body, $acl, ['params' => $options]);
569
570 10
        return $this->normalizeResponse($options, $key);
571
    }
572
573
    /**
574
     * Get options from the config.
575
     *
576
     * @param Config $config
577
     *
578
     * @return array
579
     */
580 10
    protected function getOptionsFromConfig(Config $config)
581
    {
582 10
        $options = $this->options;
583
584 10
        if ($visibility = $config->get('visibility')) {
585
            // For local reference
586 8
            $options['visibility'] = $visibility;
587
            // For external reference
588 8
            $options['ACL'] = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private';
589 8
        }
590
591 10
        if ($mimetype = $config->get('mimetype')) {
592
            // For local reference
593 8
            $options['mimetype'] = $mimetype;
594
            // For external reference
595 8
            $options['ContentType'] = $mimetype;
596 8
        }
597
598 10
        foreach (static::$metaOptions as $option) {
599 10
            if ( ! $config->has($option)) {
600 10
                continue;
601
            }
602 8
            $options[$option] = $config->get($option);
603 10
        }
604
605 10
        return $options;
606
    }
607
608
    /**
609
     * Normalize the object result array.
610
     *
611
     * @param array  $response
612
     * @param string $path
613
     *
614
     * @return array
615
     */
616 22
    protected function normalizeResponse(array $response, $path = null)
617
    {
618
        $result = [
619 22
            'path' => $path ?: $this->removePathPrefix(
620
                isset($response['Key']) ? $response['Key'] : $response['Prefix']
621 22
            ),
622 22
        ];
623 22
        $result = array_merge($result, Util::pathinfo($result['path']));
624
625 22
        if (isset($response['LastModified'])) {
626 12
            $result['timestamp'] = strtotime($response['LastModified']);
627 12
        }
628
629 22
        if (substr($result['path'], -1) === '/') {
630 2
            $result['type'] = 'dir';
631 2
            $result['path'] = rtrim($result['path'], '/');
632
633 2
            return $result;
634
        }
635
636 20
        return array_merge($result, Util::map($response, static::$resultMap), ['type' => 'file']);
637
    }
638
639
    /**
640
     * @param $location
641
     *
642
     * @return bool
643
     */
644 10
    protected function doesDirectoryExist($location)
645
    {
646
        // Maybe this isn't an actual key, but a prefix.
647
        // Do a prefix listing of objects to determine.
648 10
        $command = $this->s3Client->getCommand(
649 10
            'listObjects',
650
            [
651 10
                'Bucket' => $this->bucket,
652 10
                'Prefix' => rtrim($location, '/') . '/',
653 10
                'MaxKeys' => 1,
654
            ]
655 10
        );
656
657
        try {
658 10
            $result = $this->s3Client->execute($command);
659
660 6
            return $result['Contents'] || $result['CommonPrefixes'];
661 4
        } catch (S3Exception $e) {
662 4
            if ($e->getStatusCode() === 403) {
663 2
                return false;
664
            }
665
666 2
            throw $e;
667
        }
668
    }
669
}
670