Completed
Push — master ( 2216a7...dd7f07 )
by
unknown
12s queued 10s
created

AzureBlobStorage::mimeType()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 15

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 3
nop 1
1
<?php
2
3
namespace Gaufrette\Adapter;
4
5
use Gaufrette\Adapter;
6
use Gaufrette\Util;
7
use Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface;
8
use MicrosoftAzure\Storage\Blob\Models\Blob;
9
use MicrosoftAzure\Storage\Blob\Models\Container;
10
use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
11
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
12
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
13
use MicrosoftAzure\Storage\Blob\Models\DeleteContainerOptions;
14
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
15
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
16
17
/**
18
 * Microsoft Azure Blob Storage adapter.
19
 *
20
 * @author Luciano Mammino <[email protected]>
21
 * @author Paweł Czyżewski <[email protected]>
22
 */
23
class AzureBlobStorage implements Adapter, MetadataSupporter, SizeCalculator, ChecksumCalculator, MimeTypeProvider
24
{
25
    /**
26
     * Error constants.
27
     */
28
    const ERROR_CONTAINER_ALREADY_EXISTS = 'ContainerAlreadyExists';
29
    const ERROR_CONTAINER_NOT_FOUND = 'ContainerNotFound';
30
31
    /**
32
     * @var AzureBlobStorage\BlobProxyFactoryInterface
33
     */
34
    protected $blobProxyFactory;
35
36
    /**
37
     * @var string
38
     */
39
    protected $containerName;
40
41
    /**
42
     * @var bool
43
     */
44
    protected $detectContentType;
45
46
    /**
47
     * @var \MicrosoftAzure\Storage\Blob\Internal\IBlob
48
     */
49
    protected $blobProxy;
50
51
    /**
52
     * @var bool
53
     */
54
    protected $multiContainerMode = false;
55
56
    /**
57
     * @var CreateContainerOptions
58
     */
59
    protected $createContainerOptions;
60
61
    /**
62
     * @param AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
63
     * @param string|null                                $containerName
64
     * @param bool                                       $create
65
     * @param bool                                       $detectContentType
66
     *
67
     * @throws \RuntimeException
68
     */
69
    public function __construct(BlobProxyFactoryInterface $blobProxyFactory, $containerName = null, $create = false, $detectContentType = true)
70
    {
71
        $this->blobProxyFactory = $blobProxyFactory;
72
        $this->containerName = $containerName;
73
        $this->detectContentType = $detectContentType;
74
        if (null === $containerName) {
75
            $this->multiContainerMode = true;
76
        } elseif ($create) {
77
            $this->createContainer($containerName);
78
        }
79
    }
80
81
    /**
82
     * @return CreateContainerOptions
83
     */
84
    public function getCreateContainerOptions()
85
    {
86
        return $this->createContainerOptions;
87
    }
88
89
    /**
90
     * @param CreateContainerOptions $options
91
     */
92
    public function setCreateContainerOptions(CreateContainerOptions $options)
93
    {
94
        $this->createContainerOptions = $options;
95
    }
96
97
    /**
98
     * Creates a new container.
99
     *
100
     * @param string                                                     $containerName
101
     * @param \MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions $options
102
     *
103
     * @throws \RuntimeException if cannot create the container
104
     */
105 View Code Duplication
    public function createContainer($containerName, CreateContainerOptions $options = null)
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...
106
    {
107
        $this->init();
108
109
        if (null === $options) {
110
            $options = $this->getCreateContainerOptions();
111
        }
112
113
        try {
114
            $this->blobProxy->createContainer($containerName, $options);
115
        } catch (ServiceException $e) {
116
            $errorCode = $this->getErrorCodeFromServiceException($e);
117
118
            if ($errorCode !== self::ERROR_CONTAINER_ALREADY_EXISTS) {
119
                throw new \RuntimeException(sprintf(
120
                    'Failed to create the configured container "%s": %s (%s).',
121
                    $containerName,
122
                    $e->getErrorText(),
123
                    $errorCode
124
                ));
125
            }
126
        }
127
    }
128
129
    /**
130
     * Deletes a container.
131
     *
132
     * @param string                 $containerName
133
     * @param DeleteContainerOptions $options
134
     *
135
     * @throws \RuntimeException if cannot delete the container
136
     */
137 View Code Duplication
    public function deleteContainer($containerName, DeleteContainerOptions $options = null)
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...
138
    {
139
        $this->init();
140
141
        try {
142
            $this->blobProxy->deleteContainer($containerName, $options);
143
        } catch (ServiceException $e) {
144
            $errorCode = $this->getErrorCodeFromServiceException($e);
145
146
            if ($errorCode !== self::ERROR_CONTAINER_NOT_FOUND) {
147
                throw new \RuntimeException(sprintf(
148
                    'Failed to delete the configured container "%s": %s (%s).',
149
                    $containerName,
150
                    $e->getErrorText(),
151
                    $errorCode
152
                ), $e->getCode());
153
            }
154
        }
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     * @throws \RuntimeException
160
     * @throws \InvalidArgumentException
161
     */
162 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...
163
    {
164
        $this->init();
165
        list($containerName, $key) = $this->tokenizeKey($key);
166
167
        try {
168
            $blob = $this->blobProxy->getBlob($containerName, $key);
169
170
            return stream_get_contents($blob->getContentStream());
171
        } catch (ServiceException $e) {
172
            $this->failIfContainerNotFound($e, sprintf('read key "%s"', $key), $containerName);
173
174
            return false;
175
        }
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     * @throws \RuntimeException
181
     * @throws \InvalidArgumentException
182
     */
183
    public function write($key, $content)
184
    {
185
        $this->init();
186
        list($containerName, $key) = $this->tokenizeKey($key);
187
188
        if (class_exists(CreateBlockBlobOptions::class)) {
189
            $options = new CreateBlockBlobOptions();
190
        } else {
191
            // for microsoft/azure-storage < 1.0
192
            $options = new CreateBlobOptions();
193
        }
194
195
        if ($this->detectContentType) {
196
            $contentType = $this->guessContentType($content);
197
198
            $options->setContentType($contentType);
199
        }
200
201
        try {
202
            if ($this->multiContainerMode) {
203
                $this->createContainer($containerName);
204
            }
205
206
            $this->blobProxy->createBlockBlob($containerName, $key, $content, $options);
0 ignored issues
show
Documentation introduced by
$options is of type object<MicrosoftAzure\St...dels\CreateBlobOptions>, but the function expects a null|object<MicrosoftAzu...CreateBlockBlobOptions>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
207
        } catch (ServiceException $e) {
208
            $this->failIfContainerNotFound($e, sprintf('write content for key "%s"', $key), $containerName);
209
210
            return false;
211
        }
212
        if (is_resource($content)) {
213
            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...
214
        }
215
216
        return Util\Size::fromContent($content);
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     * @throws \RuntimeException
222
     * @throws \InvalidArgumentException
223
     */
224
    public function exists($key)
225
    {
226
        $this->init();
227
        list($containerName, $key) = $this->tokenizeKey($key);
228
229
        $listBlobsOptions = new ListBlobsOptions();
230
        $listBlobsOptions->setPrefix($key);
231
232
        try {
233
            $blobsList = $this->blobProxy->listBlobs($containerName, $listBlobsOptions);
234
235
            foreach ($blobsList->getBlobs() as $blob) {
236
                if ($key === $blob->getName()) {
237
                    return true;
238
                }
239
            }
240
        } catch (ServiceException $e) {
241
            $errorCode = $this->getErrorCodeFromServiceException($e);
242
            if ($this->multiContainerMode && self::ERROR_CONTAINER_NOT_FOUND === $errorCode) {
243
                return false;
244
            }
245
            $this->failIfContainerNotFound($e, 'check if key exists', $containerName);
246
247
            throw new \RuntimeException(sprintf(
248
                'Failed to check if key "%s" exists in container "%s": %s (%s).',
249
                $key,
250
                $containerName,
251
                $e->getErrorText(),
252
                $errorCode
253
            ), $e->getCode());
254
        }
255
256
        return false;
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     * @throws \RuntimeException
262
     */
263
    public function keys()
264
    {
265
        $this->init();
266
267
        try {
268
            if ($this->multiContainerMode) {
269
                $containersList = $this->blobProxy->listContainers();
270
271
                return call_user_func_array('array_merge', array_map(
272
                    function (Container $container) {
273
                        $containerName = $container->getName();
274
275
                        return $this->fetchBlobs($containerName, $containerName);
276
                    },
277
                    $containersList->getContainers()
278
                ));
279
            }
280
281
            return $this->fetchBlobs($this->containerName);
282
        } catch (ServiceException $e) {
283
            $this->failIfContainerNotFound($e, 'retrieve keys', $this->containerName);
284
            $errorCode = $this->getErrorCodeFromServiceException($e);
285
286
            throw new \RuntimeException(sprintf(
287
                'Failed to list keys for the container "%s": %s (%s).',
288
                $this->containerName,
289
                $e->getErrorText(),
290
                $errorCode
291
            ), $e->getCode());
292
        }
293
    }
294
295
    /**
296
     * {@inheritdoc}
297
     * @throws \RuntimeException
298
     * @throws \InvalidArgumentException
299
     */
300 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...
301
    {
302
        $this->init();
303
        list($containerName, $key) = $this->tokenizeKey($key);
304
305
        try {
306
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
307
308
            return $properties->getProperties()->getLastModified()->getTimestamp();
309
        } catch (ServiceException $e) {
310
            $this->failIfContainerNotFound($e, sprintf('read mtime for key "%s"', $key), $containerName);
311
312
            return false;
313
        }
314
    }
315
316
    /**
317
     * {@inheritdoc}
318
     */
319 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...
320
    {
321
        $this->init();
322
        list($containerName, $key) = $this->tokenizeKey($key);
323
324
        try {
325
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
326
327
            return $properties->getProperties()->getContentLength();
328
        } catch (ServiceException $e) {
329
            $this->failIfContainerNotFound($e, sprintf('read content length for key "%s"', $key), $containerName);
330
331
            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...
332
        }
333
    }
334
335
    /**
336
     * {@inheritdoc}
337
     */
338 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...
339
    {
340
        $this->init();
341
        list($containerName, $key) = $this->tokenizeKey($key);
342
343
        try {
344
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
345
346
            return $properties->getProperties()->getContentType();
347
        } catch (ServiceException $e) {
348
            $this->failIfContainerNotFound($e, sprintf('read content mime type for key "%s"', $key), $containerName);
349
350
            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...
351
        }
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     */
357
    public function checksum($key)
358
    {
359
        $this->init();
360
        list($containerName, $key) = $this->tokenizeKey($key);
361
362
        try {
363
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
364
            $checksumBase64 = $properties->getProperties()->getContentMD5();
365
366
            return \bin2hex(\base64_decode($checksumBase64, true));
367
        } catch (ServiceException $e) {
368
            $this->failIfContainerNotFound($e, sprintf('read content MD5 for key "%s"', $key), $containerName);
369
370
            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\ChecksumCalculator::checksum 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...
371
        }
372
    }
373
374
    /**
375
     * {@inheritdoc}
376
     * @throws \RuntimeException
377
     * @throws \InvalidArgumentException
378
     */
379 View Code Duplication
    public function delete($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...
380
    {
381
        $this->init();
382
        list($containerName, $key) = $this->tokenizeKey($key);
383
384
        try {
385
            $this->blobProxy->deleteBlob($containerName, $key);
386
387
            return true;
388
        } catch (ServiceException $e) {
389
            $this->failIfContainerNotFound($e, sprintf('delete key "%s"', $key), $containerName);
390
391
            return false;
392
        }
393
    }
394
395
    /**
396
     * {@inheritdoc}
397
     * @throws \RuntimeException
398
     * @throws \InvalidArgumentException
399
     */
400
    public function rename($sourceKey, $targetKey)
401
    {
402
        $this->init();
403
404
        list($sourceContainerName, $sourceKey) = $this->tokenizeKey($sourceKey);
405
        list($targetContainerName, $targetKey) = $this->tokenizeKey($targetKey);
406
407
        try {
408
            if ($this->multiContainerMode) {
409
                $this->createContainer($targetContainerName);
410
            }
411
            $this->blobProxy->copyBlob($targetContainerName, $targetKey, $sourceContainerName, $sourceKey);
412
            $this->blobProxy->deleteBlob($sourceContainerName, $sourceKey);
413
414
            return true;
415
        } catch (ServiceException $e) {
416
            $this->failIfContainerNotFound($e, sprintf('rename key "%s"', $sourceKey), $sourceContainerName);
417
418
            return false;
419
        }
420
    }
421
422
    /**
423
     * {@inheritdoc}
424
     */
425
    public function isDirectory($key)
426
    {
427
        // Windows Azure Blob Storage does not support directories
428
        return false;
429
    }
430
431
    /**
432
     * {@inheritdoc}
433
     * @throws \RuntimeException
434
     * @throws \InvalidArgumentException
435
     */
436 View Code Duplication
    public function setMetadata($key, $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...
437
    {
438
        $this->init();
439
        list($containerName, $key) = $this->tokenizeKey($key);
440
441
        try {
442
            $this->blobProxy->setBlobMetadata($containerName, $key, $content);
443
        } catch (ServiceException $e) {
444
            $errorCode = $this->getErrorCodeFromServiceException($e);
445
446
            throw new \RuntimeException(sprintf(
447
                'Failed to set metadata for blob "%s" in container "%s": %s (%s).',
448
                $key,
449
                $containerName,
450
                $e->getErrorText(),
451
                $errorCode
452
            ), $e->getCode());
453
        }
454
    }
455
456
    /**
457
     * {@inheritdoc}
458
     * @throws \RuntimeException
459
     * @throws \InvalidArgumentException
460
     */
461 View Code Duplication
    public function getMetadata($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...
462
    {
463
        $this->init();
464
        list($containerName, $key) = $this->tokenizeKey($key);
465
466
        try {
467
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
468
469
            return $properties->getMetadata();
470
        } catch (ServiceException $e) {
471
            $errorCode = $this->getErrorCodeFromServiceException($e);
472
473
            throw new \RuntimeException(sprintf(
474
                'Failed to get metadata for blob "%s" in container "%s": %s (%s).',
475
                $key,
476
                $containerName,
477
                $e->getErrorText(),
478
                $errorCode
479
            ), $e->getCode());
480
        }
481
    }
482
483
    /**
484
     * Lazy initialization, automatically called when some method is called after construction.
485
     */
486
    protected function init()
487
    {
488
        if ($this->blobProxy === null) {
489
            $this->blobProxy = $this->blobProxyFactory->create();
490
        }
491
    }
492
493
    /**
494
     * Throws a runtime exception if a give ServiceException derived from a "container not found" error.
495
     *
496
     * @param ServiceException $exception
497
     * @param string           $action
498
     * @param string           $containerName
499
     *
500
     * @throws \RuntimeException
501
     */
502
    protected function failIfContainerNotFound(ServiceException $exception, $action, $containerName)
503
    {
504
        $errorCode = $this->getErrorCodeFromServiceException($exception);
505
506
        if ($errorCode === self::ERROR_CONTAINER_NOT_FOUND) {
507
            throw new \RuntimeException(sprintf(
508
                'Failed to %s: container "%s" not found.',
509
                $action,
510
                $containerName
511
            ), $exception->getCode());
512
        }
513
    }
514
515
    /**
516
     * Extracts the error code from a service exception.
517
     *
518
     * @param ServiceException $exception
519
     *
520
     * @return string
521
     */
522
    protected function getErrorCodeFromServiceException(ServiceException $exception)
523
    {
524
        $xml = @simplexml_load_string($exception->getResponse()->getBody());
525
526
        if ($xml && isset($xml->Code)) {
527
            return (string) $xml->Code;
528
        }
529
530
        return $exception->getErrorText();
531
    }
532
533
    /**
534
     * @param string|resource $content
535
     *
536
     * @return string
537
     */
538 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...
539
    {
540
        $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
541
542
        if (is_resource($content)) {
543
            return $fileInfo->file(stream_get_meta_data($content)['uri']);
544
        }
545
546
        return $fileInfo->buffer($content);
547
    }
548
549
    /**
550
     * @param string $key
551
     *
552
     * @return array
553
     * @throws \InvalidArgumentException
554
     */
555
    private function tokenizeKey($key)
556
    {
557
        $containerName = $this->containerName;
558
        if (false === $this->multiContainerMode) {
559
            return [$containerName, $key];
560
        }
561
562
        if (false === ($index = strpos($key, '/'))) {
563
            throw new \InvalidArgumentException(sprintf(
564
                'Failed to establish container name from key "%s", container name is required in multi-container mode',
565
                $key
566
            ));
567
        }
568
        $containerName = substr($key, 0, $index);
569
        $key = substr($key, $index + 1);
570
571
        return [$containerName, $key];
572
    }
573
574
    /**
575
     * @param string $containerName
576
     * @param null   $prefix
577
     *
578
     * @return array
579
     */
580
    private function fetchBlobs($containerName, $prefix = null)
581
    {
582
        $blobList = $this->blobProxy->listBlobs($containerName);
583
584
        return array_map(
585
            function (Blob $blob) use ($prefix) {
586
                $name = $blob->getName();
587
                if (null !== $prefix) {
588
                    $name = $prefix . '/' . $name;
589
                }
590
591
                return $name;
592
            },
593
            $blobList->getBlobs()
594
        );
595
    }
596
}
597