Completed
Pull Request — master (#398)
by Aurélien
02:53
created

AzureBlobStorage::write()   B

Complexity

Conditions 4
Paths 16

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.5806
cc 4
eloc 16
nc 16
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 WindowsAzure\Blob\Models\CreateBlobOptions;
9
use WindowsAzure\Blob\Models\CreateContainerOptions;
10
use WindowsAzure\Blob\Models\DeleteContainerOptions;
11
use WindowsAzure\Blob\Models\ListBlobsOptions;
12
use WindowsAzure\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 \WindowsAzure\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 \WindowsAzure\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);
0 ignored issues
show
Bug introduced by
It seems like $options defined by parameter $options on line 73 can also be of type object<WindowsAzure\Blob...CreateContainerOptions>; however, WindowsAzure\Blob\Intern...Blob::createContainer() does only seem to accept object<WindowsAzure\Blob...eContainerOptions>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
79
        } catch (ServiceException $e) {
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);
0 ignored issues
show
Bug introduced by
It seems like $options defined by parameter $options on line 101 can also be of type object<WindowsAzure\Blob...DeleteContainerOptions>; however, WindowsAzure\Blob\Intern...Blob::deleteContainer() does only seem to accept object<WindowsAzure\Blob...eContainerOptions>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
107
        } catch (ServiceException $e) {
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) {
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
                $fileInfo = new \finfo(FILEINFO_MIME_TYPE);
151
                if (is_resource($content)) {
152
                    $contentType = $fileInfo->file(stream_get_meta_data($content)['uri']);
153
                } else {
154
                    $contentType = $fileInfo->buffer($content);
155
                }
156
                $options->setContentType($contentType);
157
            }
158
159
            $this->blobProxy->createBlockBlob($this->containerName, $key, $content, $options);
0 ignored issues
show
Documentation introduced by
$options is of type object<WindowsAzure\Blob...dels\CreateBlobOptions>, but the function expects a object<WindowsAzure\Blob...CreateBlobOptions>|null.

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...
Bug introduced by
It seems like $content can also be of type resource; however, WindowsAzure\Blob\Intern...Blob::createBlockBlob() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
160
161
            return Util\Size::fromContent($content);
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type resource; however, Gaufrette\Util\Size::fromContent() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
162
        } catch (ServiceException $e) {
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);
0 ignored issues
show
Documentation introduced by
$listBlobsOptions is of type object<WindowsAzure\Blob\Models\ListBlobsOptions>, but the function expects a object<WindowsAzure\Blob...\ListBlobsOptions>|null.

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...
181
182
            foreach ($blobsList->getBlobs() as $blob) {
183
                if ($key === $blob->getName()) {
184
                    return true;
185
                }
186
            }
187
        } catch (ServiceException $e) {
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) {
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) {
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) {
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) {
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) {
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) {
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