Completed
Pull Request — master (#639)
by Tobias
01:35
created

AsyncAwsS3::rename()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 16

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.7333
c 0
b 0
f 0
cc 2
nc 3
nop 2
1
<?php
2
3
namespace Gaufrette\Adapter;
4
5
use AsyncAws\SimpleS3\SimpleS3Client;
6
use Gaufrette\Adapter;
7
use Gaufrette\Util;
8
9
/**
10
 * Amazon S3 adapter using the AsyncAws.
11
 *
12
 * @author  Michael Dowling <[email protected]>
13
 * @author Tobias Nyholm <[email protected]>
14
 */
15
class AsyncAwsS3 implements Adapter, MetadataSupporter, ListKeysAware, SizeCalculator, MimeTypeProvider
16
{
17
    /** @var SimpleS3Client */
18
    protected $service;
19
    /** @var string */
20
    protected $bucket;
21
    /** @var array */
22
    protected $options;
23
    /** @var bool */
24
    protected $bucketExists;
25
    /** @var array */
26
    protected $metadata = [];
27
    /** @var bool */
28
    protected $detectContentType;
29
30
    /**
31
     * @param SimpleS3Client $service
32
     * @param string   $bucket
33
     * @param array    $options
34
     * @param bool     $detectContentType
35
     */
36 View Code Duplication
    public function __construct(SimpleS3Client $service, $bucket, array $options = [], $detectContentType = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
37
    {
38
        if (!class_exists(SimpleS3Client::class)) {
39
            throw new \LogicException('You need to install package "async-aws/simple-s3" to use this adapter');
40
        }
41
        $this->service = $service;
42
        $this->bucket = $bucket;
43
        $this->options = array_replace(
44
            [
45
                'create' => false,
46
                'directory' => '',
47
                'acl' => 'private',
48
            ],
49
            $options
50
        );
51
52
        $this->detectContentType = $detectContentType;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 View Code Duplication
    public function setMetadata($key, $metadata)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
59
    {
60
        // BC with AmazonS3 adapter
61
        if (isset($metadata['contentType'])) {
62
            $metadata['ContentType'] = $metadata['contentType'];
63
            unset($metadata['contentType']);
64
        }
65
66
        $this->metadata[$key] = $metadata;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getMetadata($key)
73
    {
74
        return isset($this->metadata[$key]) ? $this->metadata[$key] : [];
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 View Code Duplication
    public function read($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
81
    {
82
        $this->ensureBucketExists();
83
        $options = $this->getOptions($key);
84
85
        try {
86
            // Get remote object
87
            $object = $this->service->getObject($options);
88
            // If there's no metadata array set up for this object, set it up
89
            if (!array_key_exists($key, $this->metadata) || !is_array($this->metadata[$key])) {
90
                $this->metadata[$key] = [];
91
            }
92
            // Make remote ContentType metadata available locally
93
            $this->metadata[$key]['ContentType'] = $object->getContentType();
94
95
            return $object->getBody()->getContentAsString();
96
        } catch (\Exception $e) {
97
            return false;
98
        }
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 View Code Duplication
    public function rename($sourceKey, $targetKey)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
105
    {
106
        $this->ensureBucketExists();
107
        $options = $this->getOptions(
108
            $targetKey,
109
            ['CopySource' => $this->bucket . '/' . $this->computePath($sourceKey)]
110
        );
111
112
        try {
113
            $this->service->copyObject(array_merge($options, $this->getMetadata($targetKey)));
114
115
            return $this->delete($sourceKey);
116
        } catch (\Exception $e) {
117
            return false;
118
        }
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function write($key, $content)
125
    {
126
        $this->ensureBucketExists();
127
        $options = $this->getOptions($key);
128
        unset($options['Bucket'], $options['Key']);
129
130
        /*
131
         * If the ContentType was not already set in the metadata, then we autodetect
132
         * it to prevent everything being served up as binary/octet-stream.
133
         */
134 View Code Duplication
        if (!isset($options['ContentType']) && $this->detectContentType) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
135
            $options['ContentType'] = $this->guessContentType($content);
136
        }
137
138
        try {
139
            $this->service->upload($this->bucket, $this->computePath($key), $content, $options);
140
141
            if (is_resource($content)) {
142
                return Util\Size::fromResource($content);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Gaufrette\Util\S...fromResource($content); (string) is incompatible with the return type declared by the interface Gaufrette\Adapter::write of type integer|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
143
            }
144
145
            return Util\Size::fromContent($content);
146
        } catch (\Exception $e) {
147
            return false;
148
        }
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    public function exists($key)
155
    {
156
        return $this->service->has($this->bucket, $this->computePath($key));
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162 View Code Duplication
    public function mtime($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
163
    {
164
        try {
165
            $result = $this->service->headObject($this->getOptions($key));
166
167
            return $result->getLastModified()->getTimestamp();
168
        } catch (\Exception $e) {
169
            return false;
170
        }
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176 View Code Duplication
    public function size($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
177
    {
178
        try {
179
            $result = $this->service->headObject($this->getOptions($key));
180
181
            return $result->getContentLength();
182
        } catch (\Exception $e) {
183
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Gaufrette\Adapter\SizeCalculator::size of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
184
        }
185
    }
186
187 View Code Duplication
    public function mimeType($key)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
188
    {
189
        try {
190
            $result = $this->service->headObject($this->getOptions($key));
191
192
            return $result->getContentType();
193
        } catch (\Exception $e) {
194
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Gaufrette\Adapter\MimeTypeProvider::mimeType of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
195
        }
196
    }
197
198
    /**
199
     * {@inheritdoc}
200
     */
201
    public function keys()
202
    {
203
        return $this->listKeys();
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209 View Code Duplication
    public function listKeys($prefix = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
210
    {
211
        $this->ensureBucketExists();
212
213
        $options = ['Bucket' => $this->bucket];
214
        if ((string) $prefix != '') {
215
            $options['Prefix'] = $this->computePath($prefix);
216
        } elseif (!empty($this->options['directory'])) {
217
            $options['Prefix'] = $this->options['directory'];
218
        }
219
220
        $keys = [];
221
        $result = $this->service->listObjectsV2($options);
222
        foreach ($result->getContents() as $file) {
223
            $keys[] = $this->computeKey($file->getKey());
224
        }
225
226
        return $keys;
227
    }
228
229
    /**
230
     * {@inheritdoc}
231
     */
232
    public function delete($key)
233
    {
234
        try {
235
            $this->service->deleteObject($this->getOptions($key));
236
237
            return true;
238
        } catch (\Exception $e) {
239
            return false;
240
        }
241
    }
242
243
    /**
244
     * {@inheritdoc}
245
     */
246
    public function isDirectory($key)
247
    {
248
        $result = $this->service->listObjectsV2([
249
            'Bucket' => $this->bucket,
250
            'Prefix' => rtrim($this->computePath($key), '/') . '/',
251
            'MaxKeys' => 1,
252
        ]);
253
254
        foreach ($result->getContents(true) as $file) {
255
            return true;
256
        }
257
258
        return false;
259
    }
260
261
    /**
262
     * Ensures the specified bucket exists. If the bucket does not exists
263
     * and the create option is set to true, it will try to create the
264
     * bucket. The bucket is created using the same region as the supplied
265
     * client object.
266
     *
267
     * @throws \RuntimeException if the bucket does not exists or could not be
268
     *                           created
269
     */
270 View Code Duplication
    protected function ensureBucketExists()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
271
    {
272
        if ($this->bucketExists) {
273
            return true;
274
        }
275
276
        if ($this->bucketExists = $this->service->bucketExists(['Bucket' => $this->bucket])->isSuccess()) {
277
            return true;
278
        }
279
280
        if (!$this->options['create']) {
281
            throw new \RuntimeException(sprintf(
282
                'The configured bucket "%s" does not exist.',
283
                $this->bucket
284
            ));
285
        }
286
287
        $this->service->createBucket([
288
            'Bucket' => $this->bucket,
289
        ]);
290
        $this->bucketExists = true;
291
292
        return true;
293
    }
294
295 View Code Duplication
    protected function getOptions($key, array $options = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
296
    {
297
        $options['ACL'] = $this->options['acl'];
298
        $options['Bucket'] = $this->bucket;
299
        $options['Key'] = $this->computePath($key);
300
301
        /*
302
         * Merge global options for adapter, which are set in the constructor, with metadata.
303
         * Metadata will override global options.
304
         */
305
        $options = array_merge($this->options, $options, $this->getMetadata($key));
306
307
        return $options;
308
    }
309
310
    protected function computePath($key)
311
    {
312
        if (empty($this->options['directory'])) {
313
            return $key;
314
        }
315
316
        return sprintf('%s/%s', $this->options['directory'], $key);
317
    }
318
319
    /**
320
     * Computes the key from the specified path.
321
     *
322
     * @param string $path
323
     *
324
     * return string
325
     */
326
    protected function computeKey($path)
327
    {
328
        return ltrim(substr($path, strlen($this->options['directory'])), '/');
329
    }
330
331
    /**
332
     * @param string $content
333
     *
334
     * @return string
335
     */
336 View Code Duplication
    private function guessContentType($content)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
337
    {
338
        $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
339
340
        if (is_resource($content)) {
341
            return $fileInfo->file(stream_get_meta_data($content)['uri']);
342
        }
343
344
        return $fileInfo->buffer($content);
345
    }
346
}
347