Test Failed
Branch master (3a0aa4)
by Domenico
16:55
created

UploadItemFromBody   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 104
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 21
eloc 42
dl 0
loc 104
ccs 0
cts 41
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B upload() 0 44 9
A validateParams() 0 6 3
B handle() 0 23 9
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 Exception;
16
use InvalidArgumentException;
17
use Matecat\SimpleS3\Commands\CommandHandler;
18
use Matecat\SimpleS3\Components\Validators\S3ObjectSafeNameValidator;
19
use Matecat\SimpleS3\Components\Validators\S3StorageClassNameValidator;
20
use Matecat\SimpleS3\Exceptions\InvalidS3NameException;
21
use Matecat\SimpleS3\Helpers\File;
22
use Matecat\SimpleS3\Helpers\FilenameValidator;
0 ignored issues
show
Bug introduced by
The type Matecat\SimpleS3\Helpers\FilenameValidator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
24
class UploadItemFromBody extends CommandHandler
25
{
26
    /**
27
     * Upload a content to S3.
28
     * For a complete reference of put object see:
29
     * https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html?highlight=put
30
     *
31
     * @param array $params
32
     *
33
     * @return bool
34
     * @throws Exception
35
     */
36
    public function handle(array $params = []): bool
37
    {
38
        $bucketName = $params[ 'bucket' ];
39
        $keyName    = $params[ 'key' ];
40
        $body       = $params[ 'body' ];
41
42
        if (isset($params[ 'bucket_check' ]) and true === $params[ 'bucket_check' ]) {
43
            $this->client->createBucketIfItDoesNotExist(['bucket' => $bucketName]);
44
        }
45
46
        if (false === S3ObjectSafeNameValidator::isValid($keyName)) {
47
            throw new InvalidS3NameException(sprintf('%s is not a valid S3 object name. [' . implode(', ', S3ObjectSafeNameValidator::validate($keyName)) . ']', $keyName));
48
        }
49
50
        if ((isset($params[ 'storage' ]) and false === S3StorageClassNameValidator::isValid($params[ 'storage' ]))) {
51
            throw new InvalidArgumentException(S3StorageClassNameValidator::validate($params[ 'storage' ])[ 0 ]);
52
        }
53
54
        if ($this->client->hasEncoder()) {
55
            $keyName = $this->client->getEncoder()->encode($keyName);
56
        }
57
58
        return $this->upload($bucketName, $keyName, $body, (isset($params[ 'storage' ])) ? $params[ 'storage' ] : null, (isset($params[ 'meta' ])) ? $params[ 'meta' ] : null);
59
    }
60
61
    /**
62
     * @param array $params
63
     *
64
     * @return bool
65
     */
66
    public function validateParams(array $params = []): bool
67
    {
68
        return (
69
                isset($params[ 'bucket' ]) and
70
                isset($params[ 'key' ]) and
71
                isset($params[ 'body' ])
72
        );
73
    }
74
75
    /**
76
     * @param string      $bucketName
77
     * @param string      $keyName
78
     * @param resource    $body
79
     * @param string|null $storage
80
     * @param array|null  $meta
81
     *
82
     * @return bool
83
     */
84
    private function upload(string $bucketName, string $keyName, $body, ?string $storage = null, ?array $meta = null): bool
85
    {
86
        try {
87
            $config = [
88
                    'Bucket'            => $bucketName,
89
                    'Key'               => $keyName,
90
                    'Body'              => $body,
91
                    'MetadataDirective' => 'REPLACE',
92
            ];
93
94
            if (null != $storage) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $storage of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
95
                $config[ 'StorageClass' ] = $storage;
96
            }
97
98
            if (null != $meta) {
99
                $config[ 'Metadata' ] = $meta;
100
            }
101
102
            $config[ 'Metadata' ][ 'original_name' ] = File::getBaseName($keyName);
103
104
            $result = $this->client->getConn()->putObject($config);
105
106
            if (($result instanceof ResultInterface) and $result[ '@metadata' ][ 'statusCode' ] === 200) {
107
                $this->commandHandlerLogger?->log($this, sprintf('File \'%s\' was successfully uploaded in \'%s\' bucket', $keyName, $bucketName));
108
109
                if (null == $storage and $this->client->hasCache()) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $storage of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
110
                    $version = null;
111
                    if (isset($result[ '@metadata' ][ 'headers' ][ 'x-amz-version-id' ])) {
112
                        $version = $result[ '@metadata' ][ 'headers' ][ 'x-amz-version-id' ];
113
                    }
114
115
                    $this->client->getCache()->set($bucketName, $keyName, '', $version);
116
                }
117
118
                return true;
119
            }
120
121
            $this->commandHandlerLogger?->log($this, sprintf('Something went wrong during upload of file \'%s\' in \'%s\' bucket', $keyName, $bucketName), 'warning');
122
123
            return false;
124
        } catch (InvalidArgumentException $e) {
125
            $this->commandHandlerLogger?->logExceptionAndReturnFalse($e);
126
127
            throw $e;
128
        }
129
    }
130
}
131