1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Script used to get a file in AWS S3 |
5
|
|
|
**/ |
6
|
|
|
|
7
|
|
|
require __DIR__ . "/../../vendor/autoload.php"; |
8
|
|
|
|
9
|
|
View Code Duplication |
function usage() |
|
|
|
|
10
|
|
|
{ |
11
|
|
|
echo("Usage: php ". basename(__FILE__) . " [-h] [--force] --bucket <s3 bucket> --file <filename> --to <filepath>\n"); |
12
|
|
|
echo("--help, -h: Print this help\n"); |
13
|
|
|
echo("--bucket <s3 bucket>: Name of the S3 bucket\n"); |
14
|
|
|
echo("--file <filename>: Name of the file in the S3 bucket\n"); |
15
|
|
|
echo("--to <filepath>: Full path to file where to save. You can override original filename.\n"); |
16
|
|
|
echo("--force: Force download even if file exists locally\n\n"); |
17
|
|
|
exit(0); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
function check_input_parameters($options) |
21
|
|
|
{ |
22
|
|
View Code Duplication |
if (!count($options) || isset($options['h']) || |
23
|
|
|
isset($options['help'])) |
24
|
|
|
usage(); |
25
|
|
|
|
26
|
|
View Code Duplication |
if (!isset($options['bucket']) || !isset($options['file']) || |
27
|
|
|
!isset($options['to'])) |
28
|
|
|
throw new \SA\CpeSdk\CpeException("Missing mandatory parameter!"); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
$options = getopt("h", array("bucket:", "file:", "to:", "force::", "help::")); |
32
|
|
|
check_input_parameters($options); |
33
|
|
|
|
34
|
|
|
// If local file already exists. We don't download unless --force |
35
|
|
|
if (!isset($options['force']) && |
36
|
|
|
file_exists($options['to']) && |
37
|
|
|
filesize($options['to'])) |
38
|
|
|
{ |
39
|
|
|
$out = [ "status" => "SUCCESS", |
40
|
|
|
"msg" => "[".__FILE__."] Using local copy: '" . $options['to'] . "'" ]; |
41
|
|
|
print json_encode($out)."\n"; |
42
|
|
|
exit(0); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
# Check if preper env vars are setup |
46
|
|
|
if (!($region = getenv("AWS_DEFAULT_REGION"))) |
47
|
|
|
throw new \SA\CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!"); |
48
|
|
|
|
49
|
|
|
// Get S3 client |
50
|
|
|
$s3 = new \Aws\S3\S3Client([ |
51
|
|
|
'version' => 'latest', |
52
|
|
|
'region' => $region |
53
|
|
|
]); |
54
|
|
|
|
55
|
|
|
// Download and Save object to a local file. |
56
|
|
|
$res = $s3->getObject(array( |
57
|
|
|
'Bucket' => $options['bucket'], |
58
|
|
|
'Key' => ltrim($options['file'], '/'), |
59
|
|
|
'SaveAs' => $options['to'] |
60
|
|
|
)); |
61
|
|
|
|
62
|
|
|
$out = [ "status" => "SUCCESS", |
63
|
|
|
"msg" => "[".__FILE__."] Download '" . $options['bucket'] . "/" . $options['file'] . "' successful !" ]; |
64
|
|
|
|
65
|
|
|
print json_encode($out)."\n"; |
66
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.