Passed
Push — master ( 38e5c5...adb06a )
by frey
48s
created

Adapter::write()   B

Complexity

Conditions 3
Paths 7

Size

Total Lines 24
Code Lines 13

Duplication

Lines 24
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 3.2621

Importance

Changes 0
Metric Value
dl 24
loc 24
ccs 9
cts 13
cp 0.6923
rs 8.9713
c 0
b 0
f 0
cc 3
eloc 13
nc 7
nop 3
crap 3.2621
1
<?php
2
3
namespace Freyo\Flysystem\QcloudCOSv4;
4
5
use Freyo\Flysystem\QcloudCOSv4\Client\Conf;
6
use Freyo\Flysystem\QcloudCOSv4\Client\Cosapi;
7
use Freyo\Flysystem\QcloudCOSv4\Exceptions\RuntimeException;
8
use League\Flysystem\Adapter\AbstractAdapter;
9
use League\Flysystem\AdapterInterface;
10
use League\Flysystem\Config;
11
use League\Flysystem\Util;
12
13
/**
14
 * Class Adapter.
15
 */
16
class Adapter extends AbstractAdapter
17
{
18
    /**
19
     * @var
20
     */
21
    protected $bucket;
22
23
    /**
24
     * Adapter constructor.
25
     *
26
     * @param $config
27
     */
28
    public function __construct($config)
29
    {
30
        Conf::setAppId($config['app_id']);
31
        Conf::setSecretId($config['secret_id']);
32
        Conf::setSecretKey($config['secret_key']);
33
34
        $this->bucket = $config['bucket'];
35
36
        $this->setPathPrefix($config['protocol'].'://'.$config['domain'].'/');
37
38
        Cosapi::setTimeout($config['timeout']);
39
        Cosapi::setRegion($config['region']);
40
    }
41
42
    /**
43
     * @return mixed
44
     */
45 22
    public function getBucket()
46
    {
47 22
        return $this->bucket;
48
    }
49
50
    /**
51
     * @param $path
52
     *
53
     * @return string
54
     */
55 3
    public function getUrl($path)
56
    {
57 3
        return $this->applyPathPrefix($path);
58
    }
59
60
    /**
61
     * @param string $path
62
     * @param string $contents
63
     * @param Config $config
64
     *
65
     * @throws RuntimeException
66
     *
67
     * @return bool
68
     */
69 1 View Code Duplication
    public function write($path, $contents, Config $config)
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...
70
    {
71 1
        $tmpfname = $this->writeTempFile($contents);
72
73
        try {
74 1
            $response = $this->normalizeResponse(
75 1
                Cosapi::upload($this->getBucket(), $tmpfname, $path)
0 ignored issues
show
Bug introduced by
It seems like $tmpfname defined by $this->writeTempFile($contents) on line 71 can also be of type boolean; however, Freyo\Flysystem\QcloudCO...Client\Cosapi::upload() 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...
76 1
            );
77
78 1
            $this->deleteTempFile($tmpfname);
79
80 1
            $this->setContentType($path, $contents);
81 1
        } catch (RuntimeException $exception) {
82
            $this->deleteTempFile($tmpfname);
83
84
            if ($exception->getCode() == -4018) {
85
                return $this->getMetadata($path);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getMetadata($path); (boolean) is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::write of type array|false.

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...
86
            }
87
88
            throw $exception;
89
        }
90
91 1
        return $response;
92
    }
93
94
    /**
95
     * @param string   $path
96
     * @param resource $resource
97
     * @param Config   $config
98
     *
99
     * @return bool
100
     */
101 1 View Code Duplication
    public function writeStream($path, $resource, Config $config)
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 1
        $uri = stream_get_meta_data($resource)['uri'];
104
105
        try {
106 1
            $response = $this->normalizeResponse(
107 1
                Cosapi::upload($this->getBucket(), $uri, $path)
108 1
            );
109
110
            $this->setContentType($path, stream_get_contents($resource));
111 1
        } catch (RuntimeException $exception) {
112 1
            if ($exception->getCode() == -4018) {
113 1
                return $this->getMetadata($path);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getMetadata($path); (boolean) is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::writeStream of type array|false.

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...
114
            }
115
116
            throw $exception;
117
        }
118
119
        return $response;
120
    }
121
122
    /**
123
     * @param string $path
124
     * @param string $contents
125
     * @param Config $config
126
     *
127
     * @return bool
128
     */
129 1 View Code Duplication
    public function update($path, $contents, Config $config)
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...
130
    {
131 1
        $tmpfname = $this->writeTempFile($contents);
132
133
        try {
134 1
            $response = $this->normalizeResponse(
135 1
                Cosapi::upload($this->getBucket(), $tmpfname, $path, null, null, 0)
0 ignored issues
show
Bug introduced by
It seems like $tmpfname defined by $this->writeTempFile($contents) on line 131 can also be of type boolean; however, Freyo\Flysystem\QcloudCO...Client\Cosapi::upload() 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...
136 1
            );
137
138 1
            $this->deleteTempFile($tmpfname);
139
140 1
            $this->setContentType($path, $contents);
141 1
        } catch (RuntimeException $exception) {
142
            $this->deleteTempFile($tmpfname);
143
144
            if ($exception->getCode() == -4018) {
145
                return $this->getMetadata($path);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getMetadata($path); (boolean) is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::update of type array|false.

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...
146
            }
147
148
            throw $exception;
149
        }
150
151 1
        return $response;
152
    }
153
154
    /**
155
     * @param string   $path
156
     * @param resource $resource
157
     * @param Config   $config
158
     *
159
     * @return bool
160
     */
161 2 View Code Duplication
    public function updateStream($path, $resource, Config $config)
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...
162
    {
163 1
        $uri = stream_get_meta_data($resource)['uri'];
164
165
        try {
166 1
            $response = $this->normalizeResponse(
167 1
                Cosapi::upload($this->getBucket(), $uri, $path, null, null, 0)
168 1
            );
169
170 1
            $this->setContentType($path, stream_get_contents($resource));
171 1
        } catch (RuntimeException $exception) {
172
            if ($exception->getCode() == -4018) {
173
                return $this->getMetadata($path);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getMetadata($path); (boolean) is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::updateStream of type array|false.

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...
174
            }
175
176
            throw $exception;
177
        }
178
179 2
        return $response;
180
    }
181
182
    /**
183
     * @param string $path
184
     * @param string $newpath
185
     *
186
     * @return bool
187
     */
188 2
    public function rename($path, $newpath)
189
    {
190 2
        return $this->normalizeResponse(
191 2
            Cosapi::moveFile($this->getBucket(), $path, $newpath)
192 2
        );
193
    }
194
195
    /**
196
     * @param string $path
197
     * @param string $newpath
198
     *
199
     * @return bool
200
     */
201 2
    public function copy($path, $newpath)
202
    {
203 2
        return $this->normalizeResponse(
204 2
            Cosapi::copyFile($this->getBucket(), $path, $newpath)
205 2
        );
206
    }
207
208
    /**
209
     * @param string $path
210
     *
211
     * @return bool
212
     */
213 2
    public function delete($path)
214
    {
215 2
        return $this->normalizeResponse(
216 2
            Cosapi::delFile($this->getBucket(), $path)
217 2
        );
218
    }
219
220
    /**
221
     * @param string $dirname
222
     *
223
     * @return bool
224
     */
225 2
    public function deleteDir($dirname)
226
    {
227 2
        return $this->normalizeResponse(
228 2
            Cosapi::delFolder($this->getBucket(), $dirname)
229 2
        );
230
    }
231
232
    /**
233
     * @param string $dirname
234
     * @param Config $config
235
     *
236
     * @return bool
237
     */
238 2
    public function createDir($dirname, Config $config)
239
    {
240 2
        return $this->normalizeResponse(
241 2
            Cosapi::createFolder($this->getBucket(), $dirname)
242 2
        );
243
    }
244
245
    /**
246
     * @param string $path
247
     * @param string $visibility
248
     *
249
     * @return mixed
250
     */
251 1
    public function setVisibility($path, $visibility)
252
    {
253 1
        $visibility = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? 'eWPrivateRPublic' : 'eWRPrivate';
254
255 1
        return $this->normalizeResponse(
256 1
            Cosapi::update($this->getBucket(), $path, null, $visibility)
257 1
        );
258
    }
259
260
    /**
261
     * @param string $path
262
     *
263
     * @return bool
264
     */
265 1
    public function has($path)
266
    {
267
        try {
268 1
            $this->getMetadata($path);
269 1
        } catch (RuntimeException $exception) {
270
            return false;
271
        }
272
273 1
        return true;
274
    }
275
276
    /**
277
     * @param string $path
278
     *
279
     * @return array
280
     */
281 1
    public function read($path)
282
    {
283 1
        return ['contents' => file_get_contents($this->getUrl($path))];
284
    }
285
286
    /**
287
     * @param string $path
288
     *
289
     * @return array
290
     */
291 1
    public function readStream($path)
292
    {
293 1
        return ['stream' => fopen($this->getUrl($path), 'r')];
294
    }
295
296
    /**
297
     * @param string $directory
298
     * @param bool   $recursive
299
     *
300
     * @return bool
301
     */
302 1
    public function listContents($directory = '', $recursive = false)
303
    {
304 1
        return $this->normalizeResponse(
305 1
            Cosapi::listFolder($this->getBucket(), $directory)
306 1
        );
307
    }
308
309
    /**
310
     * @param string $path
311
     *
312
     * @return bool
313
     */
314 7
    public function getMetadata($path)
315
    {
316 7
        return $this->normalizeResponse(
317 7
            Cosapi::stat($this->getBucket(), $path)
318 7
        );
319
    }
320
321
    /**
322
     * @param string $path
323
     *
324
     * @return array
325
     */
326 1
    public function getSize($path)
327
    {
328 1
        $stat = $this->getMetadata($path);
329
330 1
        if ($stat) {
331 1
            return ['size' => $stat['filesize']];
332
        }
333
334
        return ['size' => 0];
335
    }
336
337
    /**
338
     * @param string $path
339
     *
340
     * @return array
341
     */
342 1
    public function getMimetype($path)
343
    {
344 1
        $stat = $this->getMetadata($path);
345
346 1
        if ($stat && !empty($stat['custom_headers']) && !empty($stat['custom_headers']['Content-Type'])) {
347 1
            return ['mimetype' => $stat['custom_headers']['Content-Type']];
348
        }
349
350
        return ['mimetype' => ''];
351
    }
352
353
    /**
354
     * @param string $path
355
     *
356
     * @return array
357
     */
358 1
    public function getTimestamp($path)
359
    {
360 1
        $stat = $this->getMetadata($path);
361
362 1
        if ($stat) {
363 1
            return ['timestamp' => $stat['ctime']];
364
        }
365
366
        return ['timestamp' => 0];
367
    }
368
369
    /**
370
     * @param string $path
371
     *
372
     * @return array
373
     */
374 1
    public function getVisibility($path)
375
    {
376 1
        $stat = $this->getMetadata($path);
377
378 1
        $visibility = AdapterInterface::VISIBILITY_PRIVATE;
379
380 1
        if ($stat && $stat['authority'] === 'eWPrivateRPublic') {
381
            $visibility = AdapterInterface::VISIBILITY_PUBLIC;
382
        }
383
384 1
        return ['visibility' => $visibility];
385
    }
386
387
    /**
388
     * @param $content
389
     *
390
     * @return bool|string
391
     */
392 2
    private function writeTempFile($content)
393
    {
394 2
        $tmpfname = tempnam('/tmp', 'dir');
395
396 2
        chmod($tmpfname, 0777);
397
398 2
        file_put_contents($tmpfname, $content);
399
400 2
        return $tmpfname;
401
    }
402
403
    /**
404
     * @param $tmpfname
405
     */
406 2
    private function deleteTempFile($tmpfname)
407
    {
408 2
        return unlink($tmpfname);
409
    }
410
411
    /**
412
     * @param $path
413
     * @param $content
414
     *
415
     * @return bool
416
     */
417 3
    protected function setContentType($path, $content)
418
    {
419
        $custom_headers = [
420 3
            'Content-Type' => Util::guessMimeType($path, $content),
421 3
        ];
422
423 3
        return $this->normalizeResponse(
424 3
            Cosapi::update($this->getBucket(), $path, null, null, $custom_headers)
425 3
        );
426
    }
427
428
    /**
429
     * @param $response
430
     *
431
     * @throws RuntimeException
432
     *
433
     * @return mixed
434
     */
435 22
    protected function normalizeResponse($response)
436
    {
437 22
        $response = is_array($response) ? $response : json_decode($response, true);
438
439 22
        if ($response['code'] == 0) {
440 17
            return isset($response['data']) ? $response['data'] : true;
441
        }
442
443 6
        throw new RuntimeException($response['message'], $response['code']);
444
    }
445
}
446