Completed
Push — master ( c76d77...71e7c5 )
by Pierre
10:28
created

AzureBlobStorage::rename()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 2
eloc 9
nc 3
nop 2
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\CreateBlobOptions;
9
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
10
use MicrosoftAzure\Storage\Blob\Models\DeleteContainerOptions;
11
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
12
use MicrosoftAzure\Storage\Common\ServiceException;
13
14
/**
15
 * Microsoft Azure Blob Storage adapter.
16
 *
17
 * @author Luciano Mammino <[email protected]>
18
 * @author Paweł Czyżewski <[email protected]>
19
 */
20
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...
21
                                  MetadataSupporter
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces before interface name; 34 found
Loading history...
22
{
23
    /**
24
     * Error constants.
25
     */
26
    const ERROR_CONTAINER_ALREADY_EXISTS = 'ContainerAlreadyExists';
27
    const ERROR_CONTAINER_NOT_FOUND = 'ContainerNotFound';
28
29
    /**
30
     * @var AzureBlobStorage\BlobProxyFactoryInterface
31
     */
32
    protected $blobProxyFactory;
33
34
    /**
35
     * @var string
36
     */
37
    protected $containerName;
38
39
    /**
40
     * @var bool
41
     */
42
    protected $detectContentType;
43
44
    /**
45
     * @var \MicrosoftAzure\Storage\Blob\Internal\IBlob
46
     */
47
    protected $blobProxy;
48
49
    /**
50
     * @param AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
51
     * @param string                                     $containerName
52
     * @param bool                                       $create
53
     * @param bool                                       $detectContentType
54
     */
55
    public function __construct(BlobProxyFactoryInterface $blobProxyFactory, $containerName, $create = false, $detectContentType = true)
56
    {
57
        $this->blobProxyFactory = $blobProxyFactory;
58
        $this->containerName = $containerName;
59
        $this->detectContentType = $detectContentType;
60
        if ($create) {
61
            $this->createContainer($containerName);
62
        }
63
    }
64
65
    /**
66
     * Creates a new container.
67
     *
68
     * @param string                                                     $containerName
69
     * @param \MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions $options
70
     *
71
     * @throws \RuntimeException if cannot create the container
72
     */
73 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...
74
    {
75
        $this->init();
76
77
        try {
78
            $this->blobProxy->createContainer($containerName, $options);
79
        } 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...
80
            $errorCode = $this->getErrorCodeFromServiceException($e);
81
82
            if ($errorCode != self::ERROR_CONTAINER_ALREADY_EXISTS) {
83
                throw new \RuntimeException(sprintf(
84
                    'Failed to create the configured container "%s": %s (%s).',
85
                    $containerName,
86
                    $e->getErrorText(),
87
                    $errorCode
88
                ));
89
            }
90
        }
91
    }
92
93
    /**
94
     * Deletes a container.
95
     *
96
     * @param string                 $containerName
97
     * @param DeleteContainerOptions $options
98
     *
99
     * @throws \RuntimeException if cannot delete the container
100
     */
101 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...
102
    {
103
        $this->init();
104
105
        try {
106
            $this->blobProxy->deleteContainer($containerName, $options);
107
        } 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...
108
            $errorCode = $this->getErrorCodeFromServiceException($e);
109
110
            if ($errorCode != self::ERROR_CONTAINER_NOT_FOUND) {
111
                throw new \RuntimeException(sprintf(
112
                    'Failed to delete the configured container "%s": %s (%s).',
113
                    $containerName,
114
                    $e->getErrorText(),
115
                    $errorCode
116
                ), $e->getCode());
117
            }
118
        }
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124 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...
125
    {
126
        $this->init();
127
128
        try {
129
            $blob = $this->blobProxy->getBlob($this->containerName, $key);
130
131
            return stream_get_contents($blob->getContentStream());
132
        } 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...
133
            $this->failIfContainerNotFound($e, sprintf('read key "%s"', $key));
134
135
            return false;
136
        }
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function write($key, $content)
143
    {
144
        $this->init();
145
146
        try {
147
            $options = new CreateBlobOptions();
148
149
            if ($this->detectContentType) {
150
                $contentType = $this->guessContentType($content);
151
152
                $options->setBlobContentType($contentType);
153
            }
154
155
            $this->blobProxy->createBlockBlob($this->containerName, $key, $content, $options);
156
157
            if (is_resource($content)) {
158
                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...
159
            }
160
161
            return Util\Size::fromContent($content);
162
        } 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...
163
            $this->failIfContainerNotFound($e, sprintf('write content for key "%s"', $key));
164
165
            return false;
166
        }
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function exists($key)
173
    {
174
        $this->init();
175
176
        $listBlobsOptions = new ListBlobsOptions();
177
        $listBlobsOptions->setPrefix($key);
178
179
        try {
180
            $blobsList = $this->blobProxy->listBlobs($this->containerName, $listBlobsOptions);
181
182
            foreach ($blobsList->getBlobs() as $blob) {
183
                if ($key === $blob->getName()) {
184
                    return true;
185
                }
186
            }
187
        } 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...
188
            $this->failIfContainerNotFound($e, 'check if key exists');
189
            $errorCode = $this->getErrorCodeFromServiceException($e);
190
191
            throw new \RuntimeException(sprintf(
192
                'Failed to check if key "%s" exists in container "%s": %s (%s).',
193
                $key,
194
                $this->containerName,
195
                $e->getErrorText(),
196
                $errorCode
197
            ), $e->getCode());
198
        }
199
200
        return false;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function keys()
207
    {
208
        $this->init();
209
210
        try {
211
            $blobList = $this->blobProxy->listBlobs($this->containerName);
212
213
            return array_map(
214
                function ($blob) {
215
                    return $blob->getName();
216
                },
217
                $blobList->getBlobs()
218
            );
219
        } 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...
220
            $this->failIfContainerNotFound($e, 'retrieve keys');
221
            $errorCode = $this->getErrorCodeFromServiceException($e);
222
223
            throw new \RuntimeException(sprintf(
224
                'Failed to list keys for the container "%s": %s (%s).',
225
                $this->containerName,
226
                $e->getErrorText(),
227
                $errorCode
228
            ), $e->getCode());
229
        }
230
    }
231
232
    /**
233
     * {@inheritdoc}
234
     */
235
    public function mtime($key)
236
    {
237
        $this->init();
238
239
        try {
240
            $properties = $this->blobProxy->getBlobProperties($this->containerName, $key);
241
242
            return $properties->getProperties()->getLastModified()->getTimestamp();
243
        } 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...
244
            $this->failIfContainerNotFound($e, sprintf('read mtime for key "%s"', $key));
245
246
            return false;
247
        }
248
    }
249
250
    /**
251
     * {@inheritdoc}
252
     */
253 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...
254
    {
255
        $this->init();
256
257
        try {
258
            $this->blobProxy->deleteBlob($this->containerName, $key);
259
260
            return true;
261
        } 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...
262
            $this->failIfContainerNotFound($e, sprintf('delete key "%s"', $key));
263
264
            return false;
265
        }
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271
    public function rename($sourceKey, $targetKey)
272
    {
273
        $this->init();
274
275
        try {
276
            $this->blobProxy->copyBlob($this->containerName, $targetKey, $this->containerName, $sourceKey);
277
            $this->blobProxy->deleteBlob($this->containerName, $sourceKey);
278
279
            return true;
280
        } 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...
281
            $this->failIfContainerNotFound($e, sprintf('rename key "%s"', $sourceKey));
282
283
            return false;
284
        }
285
    }
286
287
    /**
288
     * {@inheritdoc}
289
     */
290
    public function isDirectory($key)
291
    {
292
        // Windows Azure Blob Storage does not support directories
293
        return false;
294
    }
295
296
    /**
297
     * {@inheritdoc}
298
     */
299 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...
300
    {
301
        $this->init();
302
303
        try {
304
            $this->blobProxy->setBlobMetadata($this->containerName, $key, $content);
305
        } 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...
306
            $errorCode = $this->getErrorCodeFromServiceException($e);
307
308
            throw new \RuntimeException(sprintf(
309
                'Failed to set metadata for blob "%s" in container "%s": %s (%s).',
310
                $key,
311
                $this->containerName,
312
                $e->getErrorText(),
313
                $errorCode
314
            ), $e->getCode());
315
        }
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321 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...
322
    {
323
        $this->init();
324
325
        try {
326
            $properties = $this->blobProxy->getBlobProperties($this->containerName, $key);
327
328
            return $properties->getMetadata();
329
        } 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...
330
            $errorCode = $this->getErrorCodeFromServiceException($e);
331
332
            throw new \RuntimeException(sprintf(
333
                'Failed to get metadata for blob "%s" in container "%s": %s (%s).',
334
                $key,
335
                $this->containerName,
336
                $e->getErrorText(),
337
                $errorCode
338
            ), $e->getCode());
339
        }
340
    }
341
342
    /**
343
     * Lazy initialization, automatically called when some method is called after construction.
344
     */
345
    protected function init()
346
    {
347
        if ($this->blobProxy == null) {
348
            $this->blobProxy = $this->blobProxyFactory->create();
349
        }
350
    }
351
352
    /**
353
     * Throws a runtime exception if a give ServiceException derived from a "container not found" error.
354
     *
355
     * @param ServiceException $exception
356
     * @param string           $action
357
     *
358
     * @throws \RuntimeException
359
     */
360
    protected function failIfContainerNotFound(ServiceException $exception, $action)
361
    {
362
        $errorCode = $this->getErrorCodeFromServiceException($exception);
363
364
        if ($errorCode == self::ERROR_CONTAINER_NOT_FOUND) {
365
            throw new \RuntimeException(sprintf(
366
                'Failed to %s: container "%s" not found.',
367
                $action,
368
                $this->containerName
369
            ), $exception->getCode());
370
        }
371
    }
372
373
    /**
374
     * Extracts the error code from a service exception.
375
     *
376
     * @param ServiceException $exception
377
     *
378
     * @return string
379
     */
380
    protected function getErrorCodeFromServiceException(ServiceException $exception)
381
    {
382
        $xml = @simplexml_load_string($exception->getErrorReason());
383
384
        if ($xml && isset($xml->Code)) {
385
            return (string) $xml->Code;
386
        }
387
388
        return $exception->getErrorReason();
389
    }
390
391
    /**
392
     * @param string $content
393
     *
394
     * @return string
395
     */
396 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...
397
    {
398
        $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
399
400
        if (is_resource($content)) {
401
            return $fileInfo->file(stream_get_meta_data($content)['uri']);
402
        }
403
404
        return $fileInfo->buffer($content);
405
    }
406
}
407