Completed
Push — master ( 891dbb...738494 )
by Frank
03:02
created

AwsS3Adapter::doesDirectoryExist()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
crap 2
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 64
    public function __construct(S3Client $client, $bucket, $prefix = '', array $options = [])
68
    {
69 64
        $this->s3Client = $client;
70 64
        $this->bucket = $bucket;
71 64
        $this->setPathPrefix($prefix);
72 64
        $this->options = $options;
73 64
    }
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 4
    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 4
        );
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 8
    public function has($path)
204
    {
205 8
        $location = $this->applyPathPrefix($path);
206
207 8
        if ($this->s3Client->doesObjectExist($this->bucket, $location)) {
208 2
            return true;
209
        }
210
211 6
        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
        $visibility = $this->getRawVisibility($path);
381
382 8
        $command = $this->s3Client->getCommand(
383 8
            'copyObject',
384
            [
385 8
                'Bucket' => $this->bucket,
386 8
                'Key' => $this->applyPathPrefix($newpath),
387 8
                'CopySource' => urlencode($this->bucket . '/' . $this->applyPathPrefix($path)),
388 8
                'ACL' => $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private',
389
            ]
390 8
        );
391
392
        try {
393 8
            $this->s3Client->execute($command);
394 8
        } catch (S3Exception $e) {
395 4
            return false;
396
        }
397
398 4
        return true;
399
    }
400
401
    /**
402
     * Read a file as a stream.
403
     *
404
     * @param string $path
405
     *
406
     * @return array|false
407
     */
408 2
    public function readStream($path)
409
    {
410 2
        $response = $this->readObject($path);
411
412 2
        if ($response !== false) {
413 2
            $response['stream'] = $response['contents']->detach();
414 2
            rewind($response['stream']);
415 2
            unset($response['contents']);
416 2
        }
417
418 2
        return $response;
419
    }
420
421
    /**
422
     * Read an object and normalize the response.
423
     *
424
     * @param $path
425
     *
426
     * @return array|bool
427
     */
428 6
    protected function readObject($path)
429
    {
430 6
        $command = $this->s3Client->getCommand(
431 6
            'getObject',
432
            [
433 6
                'Bucket' => $this->bucket,
434 6
                'Key' => $this->applyPathPrefix($path),
435
            ]
436 6
        );
437
438
        try {
439
            /** @var Result $response */
440 6
            $response = $this->s3Client->execute($command);
441 6
        } catch (S3Exception $e) {
442 2
            return false;
443
        }
444
445 4
        return $this->normalizeResponse($response->toArray(), $path);
446
    }
447
448
    /**
449
     * Set the visibility for a file.
450
     *
451
     * @param string $path
452
     * @param string $visibility
453
     *
454
     * @return array|false file meta data
455
     */
456 6
    public function setVisibility($path, $visibility)
457
    {
458 6
        $command = $this->s3Client->getCommand(
459 6
            'putObjectAcl',
460
            [
461 6
                'Bucket' => $this->bucket,
462 6
                'Key' => $this->applyPathPrefix($path),
463 6
                'ACL' => $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private',
464
            ]
465 6
        );
466
467
        try {
468 6
            $this->s3Client->execute($command);
469 6
        } catch (S3Exception $exception) {
470 2
            return false;
471
        }
472
473 4
        return compact('path', 'visibility');
474
    }
475
476
    /**
477
     * Get the visibility of a file.
478
     *
479
     * @param string $path
480
     *
481
     * @return array|false
482
     */
483 4
    public function getVisibility($path)
484
    {
485 4
        return ['visibility' => $this->getRawVisibility($path)];
486
    }
487
488
    /**
489
     * {@inheritdoc}
490
     */
491 58
    public function applyPathPrefix($prefix)
492
    {
493 58
        return ltrim(parent::applyPathPrefix($prefix), '/');
494
    }
495
496
    /**
497
     * {@inheritdoc}
498
     */
499 64
    public function setPathPrefix($prefix)
500
    {
501 64
        $prefix = ltrim($prefix, '/');
502
503 64
        return parent::setPathPrefix($prefix);
504
    }
505
506
    /**
507
     * Get the object acl presented as a visibility.
508
     *
509
     * @param string $path
510
     *
511
     * @return string
512
     */
513 12
    protected function getRawVisibility($path)
514
    {
515 12
        $command = $this->s3Client->getCommand(
516 12
            'getObjectAcl',
517
            [
518 12
                'Bucket' => $this->bucket,
519 12
                'Key' => $this->applyPathPrefix($path),
520
            ]
521 12
        );
522
523 12
        $result = $this->s3Client->execute($command);
524 12
        $visibility = AdapterInterface::VISIBILITY_PRIVATE;
525
526 12
        foreach ($result->get('Grants') as $grant) {
527
            if (
528 2
                isset($grant['Grantee']['URI'])
529 2
                && $grant['Grantee']['URI'] === self::PUBLIC_GRANT_URI
530 2
                && $grant['Permission'] === 'READ'
531 2
            ) {
532 2
                $visibility = AdapterInterface::VISIBILITY_PUBLIC;
533 2
                break;
534
            }
535 12
        }
536
537 12
        return $visibility;
538
    }
539
540
    /**
541
     * Upload an object.
542
     *
543
     * @param        $path
544
     * @param        $body
545
     * @param Config $config
546
     *
547
     * @return array
548
     */
549 10
    protected function upload($path, $body, Config $config)
550
    {
551 10
        $key = $this->applyPathPrefix($path);
552 10
        $options = $this->getOptionsFromConfig($config);
553 10
        $acl = isset($options['ACL']) ? $options['ACL'] : 'private';
554
555 10
        if ( ! isset($options['ContentType']) && is_string($body)) {
556 2
            $options['ContentType'] = Util::guessMimeType($path, $body);
557 2
        }
558
559 10
        if ( ! isset($options['ContentLength'])) {
560 10
            $options['ContentLength'] = is_string($body) ? Util::contentSize($body) : Util::getStreamSize($body);
561 10
        }
562
563 10
        $this->s3Client->upload($this->bucket, $key, $body, $acl, ['params' => $options]);
564
565 10
        return $this->normalizeResponse($options, $key);
566
    }
567
568
    /**
569
     * Get options from the config.
570
     *
571
     * @param Config $config
572
     *
573
     * @return array
574
     */
575 10
    protected function getOptionsFromConfig(Config $config)
576
    {
577 10
        $options = $this->options;
578
579 10
        if ($visibility = $config->get('visibility')) {
580
            // For local reference
581 8
            $options['visibility'] = $visibility;
582
            // For external reference
583 8
            $options['ACL'] = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'public-read' : 'private';
584 8
        }
585
586 10
        if ($mimetype = $config->get('mimetype')) {
587
            // For local reference
588 8
            $options['mimetype'] = $mimetype;
589
            // For external reference
590 8
            $options['ContentType'] = $mimetype;
591 8
        }
592
593 10
        foreach (static::$metaOptions as $option) {
594 10
            if ( ! $config->has($option)) {
595 10
                continue;
596
            }
597 8
            $options[$option] = $config->get($option);
598 10
        }
599
600 10
        return $options;
601
    }
602
603
    /**
604
     * Normalize the object result array.
605
     *
606
     * @param array  $response
607
     * @param string $path
608
     *
609
     * @return array
610
     */
611 22
    protected function normalizeResponse(array $response, $path = null)
612
    {
613
        $result = [
614 22
            'path' => $path ?: $this->removePathPrefix(
615
                isset($response['Key']) ? $response['Key'] : $response['Prefix']
616 22
            ),
617 22
        ];
618 22
        $result = array_merge($result, Util::pathinfo($result['path']));
619
620 22
        if (isset($response['LastModified'])) {
621 12
            $result['timestamp'] = strtotime($response['LastModified']);
622 12
        }
623
624 22
        if (substr($result['path'], -1) === '/') {
625 2
            $result['type'] = 'dir';
626 2
            $result['path'] = rtrim($result['path'], '/');
627
628 2
            return $result;
629
        }
630
631 20
        return array_merge($result, Util::map($response, static::$resultMap), ['type' => 'file']);
632
    }
633
634
    /**
635
     * @param $location
636
     *
637
     * @return bool
638
     */
639 6
    protected function doesDirectoryExist($location)
640
    {
641
        // Maybe this isn't an actual key, but a prefix.
642
        // Do a prefix listing of objects to determine.
643 6
        $command = $this->s3Client->getCommand(
644 6
            'listObjects',
645
            [
646 6
                'Bucket' => $this->bucket,
647 6
                'Prefix' => rtrim($location, '/') . '/',
648 6
                'MaxKeys' => 1,
649
            ]
650 6
        );
651
652 6
        $result = $this->s3Client->execute($command);
653
654 6
        return $result['Contents'] || $result['CommonPrefixes'];
655
    }
656
}
657