|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace DocumentStorage\Adapter\Storage; |
|
4
|
|
|
|
|
5
|
|
|
use Aws\S3\S3Client; |
|
6
|
|
|
use DocumentStorage\Storage; |
|
7
|
|
|
use DocumentStorage\Exception\DocumentNotFoundException; |
|
8
|
|
|
use DocumentStorage\Exception\DocumentNotStoredException; |
|
9
|
|
|
|
|
10
|
|
|
class S3 implements Storage |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var \Aws\S3\S3Client */ |
|
13
|
|
|
private $s3Client; |
|
14
|
|
|
|
|
15
|
|
|
/** @var string */ |
|
16
|
|
|
private $bucket; |
|
17
|
|
|
|
|
18
|
|
|
/** @var string */ |
|
19
|
|
|
private $directory; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(S3Client $s3Client, string $bucket, string $directory = '') |
|
22
|
|
|
{ |
|
23
|
|
|
$this->s3Client = $s3Client; |
|
24
|
|
|
$this->bucket = $bucket; |
|
25
|
|
|
$this->directory = $directory; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function store(string $pathOrBody, string $docName, string $oldDocName = '') : string |
|
29
|
|
|
{ |
|
30
|
|
|
try { |
|
31
|
|
|
$uploadResult = $this->s3Client->upload( |
|
32
|
|
|
$this->bucket, |
|
33
|
|
|
$this->getKeyPath($docName), |
|
34
|
|
|
file_exists($pathOrBody) ? file_get_contents($pathOrBody) : $pathOrBody |
|
35
|
|
|
); |
|
36
|
|
|
} catch (\Exception $e) { |
|
37
|
|
|
throw new DocumentNotStoredException( |
|
38
|
|
|
sprintf('There was an error storing the document [%s]', $e->getMessage()) |
|
39
|
|
|
); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
// We can poll the object until it is accessible |
|
43
|
|
|
$this->s3Client->waitUntil( |
|
44
|
|
|
'ObjectExists', |
|
45
|
|
|
[ |
|
46
|
|
|
'Bucket' => $this->bucket, |
|
47
|
|
|
'Key' => $this->getKeyPath($docName), |
|
48
|
|
|
] |
|
49
|
|
|
); |
|
50
|
|
|
|
|
51
|
|
|
return $uploadResult['ObjectURL']; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function retrieve(string $docName) : string |
|
55
|
|
|
{ |
|
56
|
|
|
$args = [ |
|
57
|
|
|
'Bucket' => $this->bucket, |
|
58
|
|
|
'Key' => $this->getKeyPath($docName), |
|
59
|
|
|
]; |
|
60
|
|
|
|
|
61
|
|
|
try { |
|
62
|
|
|
return (string) $this->s3Client->getObject($args)->get('Body'); |
|
63
|
|
|
} catch (\Exception $e) { |
|
64
|
|
|
throw new DocumentNotFoundException( |
|
65
|
|
|
sprintf('Unable to retrieve document [%s] from bucket [%s]', $this->getKeyPath($docName), $this->bucket) |
|
66
|
|
|
); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
public function getUrl(string $docName) : string |
|
71
|
|
|
{ |
|
72
|
|
|
return $this->s3Client->getObjectUrl( |
|
73
|
|
|
$this->bucket, |
|
74
|
|
|
$this->getKeyPath($docName) |
|
75
|
|
|
); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
private function getKeyPath(string $docName) : string |
|
79
|
|
|
{ |
|
80
|
|
|
return ('' === $this->directory) |
|
81
|
|
|
? $docName |
|
82
|
|
|
: $this->directory.DIRECTORY_SEPARATOR.$docName; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|