Completed
Pull Request — master (#472)
by
unknown
02:43
created

AzureBlobStorage::getCreateContainerOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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\CreateContainerOptions;
12
use MicrosoftAzure\Storage\Blob\Models\DeleteContainerOptions;
13
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
14
use MicrosoftAzure\Storage\Common\ServiceException;
15
use Psr\Http\Message\ResponseInterface;
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,
0 ignored issues
show
Coding Style introduced by
The first item in a multi-line implements list must be on the line following the implements keyword
Loading history...
24
                                  MetadataSupporter
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces before interface name; 34 found
Loading history...
25
{
26
    /**
27
     * Error constants.
28
     */
29
    const ERROR_CONTAINER_ALREADY_EXISTS = 'ContainerAlreadyExists';
30
    const ERROR_CONTAINER_NOT_FOUND = 'ContainerNotFound';
31
32
    /**
33
     * @var AzureBlobStorage\BlobProxyFactoryInterface
34
     */
35
    protected $blobProxyFactory;
36
37
    /**
38
     * @var string
39
     */
40
    protected $containerName;
41
42
    /**
43
     * @var bool
44
     */
45
    protected $detectContentType;
46
47
    /**
48
     * @var \MicrosoftAzure\Storage\Blob\Internal\IBlob
49
     */
50
    protected $blobProxy;
51
52
    /**
53
     * @var bool
54
     */
55
    protected $multiContainerMode = false;
56
57
    /**
58
     * @var CreateContainerOptions
59
     */
60
    protected $createContainerOptions;
61
62
    /**
63
     * @param AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
64
     * @param string|null                                $containerName
65
     * @param bool                                       $create
66
     * @param bool                                       $detectContentType
67
     *
68
     * @throws \RuntimeException
69
     */
70
    public function __construct(BlobProxyFactoryInterface $blobProxyFactory, $containerName = null, $create = false, $detectContentType = true)
71
    {
72
        $this->blobProxyFactory = $blobProxyFactory;
73
        $this->containerName = $containerName;
74
        $this->detectContentType = $detectContentType;
75
        if (null === $containerName) {
76
            $this->multiContainerMode = true;
77
        } elseif ($create) {
78
            $this->createContainer($containerName);
79
        }
80
    }
81
82
    /**
83
     * @return CreateContainerOptions
84
     */
85
    public function getCreateContainerOptions()
86
    {
87
        return $this->createContainerOptions;
88
    }
89
90
    /**
91
     * @param CreateContainerOptions $options
92
     */
93
    public function setCreateContainerOptions(CreateContainerOptions $options)
94
    {
95
        $this->createContainerOptions = $options;
96
    }
97
98
    /**
99
     * Creates a new container.
100
     *
101
     * @param string                                                     $containerName
102
     * @param \MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions $options
103
     *
104
     * @throws \RuntimeException if cannot create the container
105
     */
106 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...
107
    {
108
        $this->init();
109
110
        if (null === $options) {
111
            $options = $this->getCreateContainerOptions();
112
        }
113
114
        try {
115
            $this->blobProxy->createContainer($containerName, $options);
116
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
117
            $errorCode = $this->getErrorCodeFromServiceException($e);
118
119
            if ($errorCode !== self::ERROR_CONTAINER_ALREADY_EXISTS) {
120
                throw new \RuntimeException(sprintf(
121
                    'Failed to create the configured container "%s": %s (%s).',
122
                    $containerName,
123
                    $e->getErrorText(),
124
                    $errorCode
125
                ));
126
            }
127
        }
128
    }
129
130
    /**
131
     * Deletes a container.
132
     *
133
     * @param string                 $containerName
134
     * @param DeleteContainerOptions $options
135
     *
136
     * @throws \RuntimeException if cannot delete the container
137
     */
138 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...
139
    {
140
        $this->init();
141
142
        try {
143
            $this->blobProxy->deleteContainer($containerName, $options);
144
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
145
            $errorCode = $this->getErrorCodeFromServiceException($e);
146
147
            if ($errorCode !== self::ERROR_CONTAINER_NOT_FOUND) {
148
                throw new \RuntimeException(sprintf(
149
                    'Failed to delete the configured container "%s": %s (%s).',
150
                    $containerName,
151
                    $e->getErrorText(),
152
                    $errorCode
153
                ), $e->getCode());
154
            }
155
        }
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     * @throws \RuntimeException
161
     * @throws \InvalidArgumentException
162
     */
163 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...
164
    {
165
        $this->init();
166
        list($containerName, $key) = $this->tokenizeKey($key);
167
168
        try {
169
            $blob = $this->blobProxy->getBlob($containerName, $key);
170
171
            return stream_get_contents($blob->getContentStream());
172
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
173
            $this->failIfContainerNotFound($e, sprintf('read key "%s"', $key), $containerName);
174
175
            return false;
176
        }
177
    }
178
179
    /**
180
     * {@inheritdoc}
181
     * @throws \RuntimeException
182
     * @throws \InvalidArgumentException
183
     */
184
    public function write($key, $content)
185
    {
186
        $this->init();
187
        list($containerName, $key) = $this->tokenizeKey($key);
188
189
        $options = new CreateBlobOptions();
190
191
        if ($this->detectContentType) {
192
            $contentType = $this->guessContentType($content);
193
194
            $options->setContentType($contentType);
195
        }
196
197
        try {
198
            if ($this->multiContainerMode) {
199
                $this->createContainer($containerName);
200
            }
201
202
            $this->blobProxy->createBlockBlob($containerName, $key, $content, $options);
203
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
204
            $this->failIfContainerNotFound($e, sprintf('write content for key "%s"', $key), $containerName);
205
206
            return false;
207
        }
208
        if (is_resource($content)) {
209
            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...
210
        }
211
212
        return Util\Size::fromContent($content);
213
    }
214
215
    /**
216
     * {@inheritdoc}
217
     * @throws \RuntimeException
218
     * @throws \InvalidArgumentException
219
     */
220
    public function exists($key)
221
    {
222
        $this->init();
223
        list($containerName, $key) = $this->tokenizeKey($key);
224
225
        $listBlobsOptions = new ListBlobsOptions();
226
        $listBlobsOptions->setPrefix($key);
227
228
        try {
229
            $blobsList = $this->blobProxy->listBlobs($containerName, $listBlobsOptions);
230
231
            foreach ($blobsList->getBlobs() as $blob) {
232
                if ($key === $blob->getName()) {
233
                    return true;
234
                }
235
            }
236
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
237
            $errorCode = $this->getErrorCodeFromServiceException($e);
238
            if ($this->multiContainerMode && self::ERROR_CONTAINER_NOT_FOUND === $errorCode) {
239
                return false;
240
            }
241
            $this->failIfContainerNotFound($e, 'check if key exists', $containerName);
242
243
            throw new \RuntimeException(sprintf(
244
                'Failed to check if key "%s" exists in container "%s": %s (%s).',
245
                $key,
246
                $containerName,
247
                $e->getErrorText(),
248
                $errorCode
249
            ), $e->getCode());
250
        }
251
252
        return false;
253
    }
254
255
    /**
256
     * {@inheritdoc}
257
     * @throws \RuntimeException
258
     */
259
    public function keys()
260
    {
261
        $this->init();
262
263
        try {
264
            if ($this->multiContainerMode) {
265
                $containersList = $this->blobProxy->listContainers();
266
                return call_user_func_array('array_merge', array_map(
267
                    function(Container $container) {
268
                        $containerName = $container->getName();
269
                        return $this->fetchBlobs($containerName, $containerName);
270
                    },
271
                    $containersList->getContainers()
272
                ));
273
            }
274
275
            return $this->fetchBlobs($this->containerName);
276
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
277
            $this->failIfContainerNotFound($e, 'retrieve keys', $this->containerName);
278
            $errorCode = $this->getErrorCodeFromServiceException($e);
279
280
            throw new \RuntimeException(sprintf(
281
                'Failed to list keys for the container "%s": %s (%s).',
282
                $this->containerName,
283
                $e->getErrorText(),
284
                $errorCode
285
            ), $e->getCode());
286
        }
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     * @throws \RuntimeException
292
     * @throws \InvalidArgumentException
293
     */
294 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...
295
    {
296
        $this->init();
297
        list($containerName, $key) = $this->tokenizeKey($key);
298
299
        try {
300
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
301
302
            return $properties->getProperties()->getLastModified()->getTimestamp();
303
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
304
            $this->failIfContainerNotFound($e, sprintf('read mtime for key "%s"', $key), $containerName);
305
306
            return false;
307
        }
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     * @throws \RuntimeException
313
     * @throws \InvalidArgumentException
314
     */
315 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...
316
    {
317
        $this->init();
318
        list($containerName, $key) = $this->tokenizeKey($key);
319
320
        try {
321
            $this->blobProxy->deleteBlob($containerName, $key);
322
323
            return true;
324
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
325
            $this->failIfContainerNotFound($e, sprintf('delete key "%s"', $key), $containerName);
326
327
            return false;
328
        }
329
    }
330
331
    /**
332
     * {@inheritdoc}
333
     * @throws \RuntimeException
334
     * @throws \InvalidArgumentException
335
     */
336
    public function rename($sourceKey, $targetKey)
337
    {
338
        $this->init();
339
340
        list($sourceContainerName, $sourceKey) = $this->tokenizeKey($sourceKey);
341
        list($targetContainerName, $targetKey) = $this->tokenizeKey($targetKey);
342
343
        try {
344
            if ($this->multiContainerMode) {
345
                $this->createContainer($targetContainerName);
346
            }
347
            $this->blobProxy->copyBlob($targetContainerName, $targetKey, $sourceContainerName, $sourceKey);
348
            $this->blobProxy->deleteBlob($sourceContainerName, $sourceKey);
349
350
            return true;
351
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
352
            $this->failIfContainerNotFound($e, sprintf('rename key "%s"', $sourceKey), $sourceContainerName);
353
354
            return false;
355
        }
356
    }
357
358
    /**
359
     * {@inheritdoc}
360
     */
361
    public function isDirectory($key)
362
    {
363
        // Windows Azure Blob Storage does not support directories
364
        return false;
365
    }
366
367
    /**
368
     * {@inheritdoc}
369
     * @throws \RuntimeException
370
     * @throws \InvalidArgumentException
371
     */
372 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...
373
    {
374
        $this->init();
375
        list($containerName, $key) = $this->tokenizeKey($key);
376
377
        try {
378
            $this->blobProxy->setBlobMetadata($containerName, $key, $content);
379
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
380
            $errorCode = $this->getErrorCodeFromServiceException($e);
381
382
            throw new \RuntimeException(sprintf(
383
                'Failed to set metadata for blob "%s" in container "%s": %s (%s).',
384
                $key,
385
                $containerName,
386
                $e->getErrorText(),
387
                $errorCode
388
            ), $e->getCode());
389
        }
390
    }
391
392
    /**
393
     * {@inheritdoc}
394
     * @throws \RuntimeException
395
     * @throws \InvalidArgumentException
396
     */
397 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...
398
    {
399
        $this->init();
400
        list($containerName, $key) = $this->tokenizeKey($key);
401
402
        try {
403
            $properties = $this->blobProxy->getBlobProperties($containerName, $key);
404
405
            return $properties->getMetadata();
406
        } catch (ServiceException $e) {
0 ignored issues
show
Bug introduced by
The class MicrosoftAzure\Storage\Common\ServiceException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
407
            $errorCode = $this->getErrorCodeFromServiceException($e);
408
409
            throw new \RuntimeException(sprintf(
410
                'Failed to get metadata for blob "%s" in container "%s": %s (%s).',
411
                $key,
412
                $containerName,
413
                $e->getErrorText(),
414
                $errorCode
415
            ), $e->getCode());
416
        }
417
    }
418
419
    /**
420
     * Lazy initialization, automatically called when some method is called after construction.
421
     */
422
    protected function init()
423
    {
424
        if ($this->blobProxy === null) {
425
            $this->blobProxy = $this->blobProxyFactory->create();
426
        }
427
    }
428
429
    /**
430
     * Throws a runtime exception if a give ServiceException derived from a "container not found" error.
431
     *
432
     * @param ServiceException $exception
433
     * @param string           $action
434
     * @param string           $containerName
435
     *
436
     * @throws \RuntimeException
437
     */
438
    protected function failIfContainerNotFound(ServiceException $exception, $action, $containerName)
439
    {
440
        $errorCode = $this->getErrorCodeFromServiceException($exception);
441
442
        if ($errorCode === self::ERROR_CONTAINER_NOT_FOUND) {
443
            throw new \RuntimeException(sprintf(
444
                'Failed to %s: container "%s" not found.',
445
                $action,
446
                $containerName
447
            ), $exception->getCode());
448
        }
449
    }
450
451
    /**
452
     * Extracts the error code from a service exception.
453
     *
454
     * @param ServiceException $exception
455
     *
456
     * @return string
457
     */
458
    protected function getErrorCodeFromServiceException(ServiceException $exception)
459
    {
460
        if (method_exists($exception, 'getErrorReason')) {
461
            $xml = @simplexml_load_string($exception->getErrorReason());
462
463
            if ($xml && isset($xml->Code)) {
464
                return (string) $xml->Code;
465
            }
466
467
            return $exception->getErrorReason();
468
        } else {
469
            /** @var ResponseInterface $response */
470
            $response = $exception->getResponse();
471
            return static::parseErrorCode($response);
472
        }
473
    }
474
475
    /**
476
     * @param string|resource $content
477
     *
478
     * @return string
479
     */
480 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...
481
    {
482
        $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
483
484
        if (is_resource($content)) {
485
            return $fileInfo->file(stream_get_meta_data($content)['uri']);
486
        }
487
488
        return $fileInfo->buffer($content);
489
    }
490
491
    /**
492
     * @param string $key
493
     *
494
     * @return array
495
     * @throws \InvalidArgumentException
496
     */
497
    private function tokenizeKey($key)
498
    {
499
        $containerName = $this->containerName;
500
        if (false === $this->multiContainerMode) {
501
            return [$containerName, $key];
502
        }
503
504
        if (false === ($index = strpos($key, '/'))) {
505
            throw new \InvalidArgumentException(sprintf(
506
                'Failed to establish container name from key "%s", container name is required in multi-container mode',
507
                $key
508
            ));
509
        }
510
        $containerName = substr($key, 0, $index);
511
        $key = substr($key, $index + 1);
512
513
        return [$containerName, $key];
514
    }
515
516
    /**
517
     * @param string $containerName
518
     * @param null   $prefix
519
     *
520
     * @return array
521
     */
522
    private function fetchBlobs($containerName, $prefix = null)
523
    {
524
        $blobList = $this->blobProxy->listBlobs($containerName);
525
        return array_map(
526
            function (Blob $blob) use ($prefix) {
527
                $name = $blob->getName();
528
                if (null !== $prefix) {
529
                    $name = $prefix .'/'. $name;
530
                }
531
                return $name;
532
            },
533
            $blobList->getBlobs()
534
        );
535
    }
536
537
    /**
538
     * Error message to be parsed.
539
     *
540
     * @param  ResponseInterface $response The response with a response body.
541
     *
542
     * @return string
543
     */
544
    protected static function parseErrorCode(ResponseInterface $response)
545
    {
546
        $errorCode = $response->getReasonPhrase();
547
548
        //try to parse using xml serializer, if failed, return the whole body
549
        //as the error message.
550
        try {
551
            $body = new \SimpleXMLElement($response->getBody());
552
            $data = static::xmlToArray($body);
0 ignored issues
show
Bug introduced by
Since xmlToArray() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of xmlToArray() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
553
554
            if (array_key_exists('Code', $data)) {
555
                $errorCode = $data['Code'];
556
            }
557
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
558
        }
559
560
        return $errorCode;
561
    }
562
563
    /**
564
     * Converts a SimpleXML object to an Array recursively
565
     * ensuring all sub-elements are arrays as well.
566
     *
567
     * @param string $sxml The SimpleXML object.
568
     * @param array  $arr  The array into which to store results.
569
     *
570
     * @return array
571
     */
572
    private static function xmlToArray($sxml, array $arr = null)
573
    {
574
        foreach ((array) $sxml as $key => $value) {
575
            if (is_object($value) || (is_array($value))) {
576
                $arr[$key] = static::xmlToArray($value);
0 ignored issues
show
Bug introduced by
Since xmlToArray() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of xmlToArray() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
Documentation introduced by
$value is of type object|array, but the function expects a string.

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...
577
            } else {
578
                $arr[$key] = $value;
579
            }
580
        }
581
582
        return $arr;
583
    }
584
}
585