Passed
Push — master ( 3a0aa4...dae184 )
by Domenico
03:53
created

DownloadItem::validateParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 *  This file is part of the Simple S3 package.
4
 *
5
 * (c) Mauro Cassani<https://github.com/mauretto78>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 */
11
12
namespace Matecat\SimpleS3\Commands\Handlers;
13
14
use Aws\ResultInterface;
15
use Aws\S3\Exception\S3Exception;
16
use Exception;
17
use Matecat\SimpleS3\Commands\CommandHandler;
18
19
class DownloadItem extends CommandHandler
20
{
21
    /**
22
     * Downaload an item.
23
     * For a complete reference:
24
     * https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html
25
     *
26
     * @param array $params
27
     *
28
     * @return bool
29
     * @throws Exception
30
     */
31 1
    public function handle(array $params = []): bool
32
    {
33 1
        $bucketName = $params[ 'bucket' ];
34 1
        $keyName    = $params[ 'key' ];
35
36 1
        if ($this->client->hasEncoder()) {
37 1
            $keyName = $this->client->getEncoder()->encode($keyName);
38
        }
39
40
        try {
41 1
            $download = $this->client->getConn()->getObject([
42 1
                    'Bucket' => $bucketName,
43 1
                    'Key'    => $keyName,
44 1
                    'SaveAs' => (isset($params[ 'save_as' ])) ? $params[ 'save_as' ] : $params[ 'key' ],
45 1
            ]);
46
47 1
            if (($download instanceof ResultInterface) and $download[ '@metadata' ][ 'statusCode' ] === 200) {
48 1
                $this->commandHandlerLogger?->log($this, sprintf('\'%s\' was successfully downloaded from bucket \'%s\'', $keyName, $bucketName));
49
50 1
                return true;
51
            }
52
53
            $this->commandHandlerLogger?->log($this, sprintf('Something went wrong during downloading \'%s\' from bucket \'%s\'', $keyName, $bucketName), 'warning');
54
55
            return false;
56
        } catch (S3Exception $e) {
57
            $this->commandHandlerLogger?->logExceptionAndReturnFalse($e);
58
59
            throw $e;
60
        }
61
    }
62
63
    /**
64
     * @param array $params
65
     *
66
     * @return bool
67
     */
68 1
    public function validateParams(array $params = []): bool
69
    {
70 1
        return (
71 1
                isset($params[ 'bucket' ]) and
72 1
                isset($params[ 'key' ])
73 1
        );
74
    }
75
}
76