Completed
Push — master ( 00c013...730b37 )
by frey
05:22
created

Adapter::getUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 6.087

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 17
ccs 3
cts 10
cp 0.3
crap 6.087
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Freyo\Flysystem\QcloudCOSv5;
4
5
use Carbon\Carbon;
6
use DateTimeInterface;
7
use League\Flysystem\Adapter\AbstractAdapter;
8
use League\Flysystem\Adapter\CanOverwriteFiles;
9
use League\Flysystem\AdapterInterface;
10
use League\Flysystem\Config;
11
use Qcloud\Cos\Client;
12
use Qcloud\Cos\Exception\NoSuchKeyException;
13
14
/**
15
 * Class Adapter.
16
 */
17
class Adapter extends AbstractAdapter implements CanOverwriteFiles
18
{
19
    /**
20
     * @var Client
21
     */
22
    protected $client;
23
24
    /**
25
     * @var array
26
     */
27
    protected $config = [];
28
29
    /**
30
     * @var array
31
     */
32
    protected $regionMap = [
33
        'cn-east'      => 'ap-shanghai',
34
        'cn-sorth'     => 'ap-guangzhou',
35
        'cn-north'     => 'ap-beijing-1',
36
        'cn-south-2'   => 'ap-guangzhou-2',
37
        'cn-southwest' => 'ap-chengdu',
38
        'sg'           => 'ap-singapore',
39
        'tj'           => 'ap-beijing-1',
40
        'bj'           => 'ap-beijing',
41
        'sh'           => 'ap-shanghai',
42
        'gz'           => 'ap-guangzhou',
43
        'cd'           => 'ap-chengdu',
44
        'sgp'          => 'ap-singapore',
45
    ];
46
47
    /**
48
     * Adapter constructor.
49
     *
50
     * @param Client $client
51
     * @param array  $config
52
     */
53
    public function __construct(Client $client, array $config)
54
    {
55
        $this->client = $client;
56
        $this->config = $config;
57
58
        $this->setPathPrefix($config['cdn']);
59
    }
60
    
61
    /**
62
     * @return string
63
     */
64 2
    public function getBucketWithAppId()
65 1
    {
66 2
        return $this->getBucket().'-'.$this->getAppId();
67
    }
68
    
69
    /**
70
     * @return string
71
     */
72 19
    public function getBucket()
73
    {
74 19
        return str_replace('-'.$this->getAppId(), '', $this->config['bucket']);
75
    }
76
77
    /**
78
     * @return string
79
     */
80 19
    public function getAppId()
81
    {
82 19
        return $this->config['credentials']['appId'];
83
    }
84
85
    /**
86
     * @return string
87
     */
88 2
    public function getRegion()
89
    {
90 2
        return array_key_exists($this->config['region'], $this->regionMap)
91 2
            ? $this->regionMap[$this->config['region']] : $this->config['region'];
92
    }
93
94
    /**
95
     * @param $path
96
     *
97
     * @return string
98
     */
99 2
    public function getSourcePath($path)
100
    {
101 2
        return sprintf('%s.cos.%s.myqcloud.com/%s',
102 2
            $this->getBucketWithAppId(), $this->getRegion(), $path
103 2
        );
104
    }
105
106
    /**
107
     * @param string $path
108
     *
109
     * @return string
110
     */
111 3
    public function getUrl($path)
112
    {
113 3
        if ($this->config['cdn']) {
114 3
            return $this->applyPathPrefix($path);
115
        }
116
117
        $options = [
118
            'Scheme' => isset($this->config['scheme']) ? $this->config['scheme'] : 'http'
119
        ];
120
121
        $objectUrl = $this->client->getObjectUrl(
122
            $this->getBucket(), $path, null, $options
123
        );
124
125
        $url = parse_url($objectUrl);
126
127
        return sprintf('%s://%s%s', $url['scheme'], $url['host'], urldecode($url['path']));
128
    }
129
130
    /**
131
     * @param string             $path
132
     * @param \DateTimeInterface $expiration
133
     * @param array              $options
134
     *
135
     * @return string
136
     */
137 5
    public function getTemporaryUrl($path, DateTimeInterface $expiration, array $options = [])
138
    {
139 1
        $options = array_merge($options,
140 1
            ['Scheme' => isset($this->config['scheme']) ? $this->config['scheme'] : 'http']);
141
142 1
        $objectUrl = $this->client->getObjectUrl(
143 5
            $this->getBucket(), $path, $expiration->format('c'), $options
144 1
        );
145
146 5
        $url = parse_url($objectUrl);
147
148 1
        if ($this->config['cdn']) {
149 1
            return $this->config['cdn'].urldecode($url['path']).'?'.$url['query'];
150
        }
151
152
        return sprintf('%s://%s%s?%s', $url['scheme'], $url['host'], urldecode($url['path']), $url['query']);
153
    }
154
155
    /**
156
     * @param string $path
157
     * @param string $contents
158
     * @param Config $config
159
     *
160
     * @return array|false
161
     */
162 2
    public function write($path, $contents, Config $config)
163
    {
164 2
        $options = $this->prepareUploadConfig($config);
165
166 2
        return $this->client->upload($this->getBucket(), $path, $contents, $options);
167
    }
168
169
    /**
170
     * @param string   $path
171
     * @param resource $resource
172
     * @param Config   $config
173
     *
174
     * @return array|false
175
     */
176 2
    public function writeStream($path, $resource, Config $config)
177
    {
178 2
        $options = $this->prepareUploadConfig($config);
179
180 2
        return $this->client->upload(
181 2
            $this->getBucket(),
182 2
            $path,
183 2
            stream_get_contents($resource, -1, 0),
184
            $options
185 2
        );
186
    }
187
188
    /**
189
     * @param string $path
190
     * @param string $contents
191
     * @param Config $config
192
     *
193
     * @return array|false
194
     */
195 1
    public function update($path, $contents, Config $config)
196
    {
197 1
        return $this->write($path, $contents, $config);
198
    }
199
200
    /**
201
     * @param string   $path
202
     * @param resource $resource
203
     * @param Config   $config
204
     *
205
     * @return array|false
206
     */
207 3
    public function updateStream($path, $resource, Config $config)
208
    {
209 3
        return $this->writeStream($path, $resource, $config);
210
    }
211
212
    /**
213
     * @param string $path
214
     * @param string $newpath
215
     *
216
     * @return bool
217
     */
218 1
    public function rename($path, $newpath)
219
    {
220 1
        $result = $this->copy($path, $newpath);
221
222 1
        $this->delete($path);
223
224 1
        return $result;
225
    }
226
227
    /**
228
     * @param string $path
229
     * @param string $newpath
230
     *
231
     * @return bool
232
     */
233 2
    public function copy($path, $newpath)
234
    {
235 2
        $source = $this->getSourcePath($path);
236
237 2
        return (bool) $this->client->copy($this->getBucket(), $newpath, $source);
238
    }
239
240
    /**
241
     * @param string $path
242
     *
243
     * @return bool
244
     */
245 2
    public function delete($path)
246
    {
247 2
        return (bool) $this->client->deleteObject([
248 2
            'Bucket' => $this->getBucket(),
249 2
            'Key'    => $path,
250 2
        ]);
251
    }
252
253
    /**
254
     * @param string $dirname
255
     *
256
     * @return bool
257
     */
258 1
    public function deleteDir($dirname)
259
    {
260 1
        $response = $this->listObjects($dirname);
261
262 1
        if (!isset($response['Contents'])) {
263
            return true;
264
        }
265
266 1
        $keys = array_map(function ($item) {
267 1
            return ['Key' => $item['Key']];
268 1
        }, (array) $response['Contents']);
269
270 1
        return (bool) $this->client->deleteObjects([
271 1
            'Bucket'  => $this->getBucket(),
272 1
            'Objects' => $keys,
273 1
        ]);
274
    }
275
276
    /**
277
     * @param string $dirname
278
     * @param Config $config
279
     *
280
     * @return array|false
281
     */
282 1
    public function createDir($dirname, Config $config)
283
    {
284 1
        return $this->client->putObject([
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->client->pu...e . '/', 'Body' => '')) returns the type Guzzle\Http\Message\Response which is incompatible with the documented return type array|false.
Loading history...
285 1
            'Bucket' => $this->getBucket(),
286 1
            'Key'    => $dirname.'/',
287 1
            'Body'   => '',
288 1
        ]);
289
    }
290
291
    /**
292
     * @param string $path
293
     * @param string $visibility
294
     *
295
     * @return bool
296
     */
297 1
    public function setVisibility($path, $visibility)
298
    {
299 1
        return (bool) $this->client->PutObjectAcl([
0 ignored issues
show
Bug Best Practice introduced by
The expression return (bool)$this->clie...sibility($visibility))) returns the type boolean which is incompatible with the return type mandated by League\Flysystem\AdapterInterface::setVisibility() of array|false.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
300 1
            'Bucket' => $this->getBucket(),
301 1
            'Key'    => $path,
302 1
            'ACL'    => $this->normalizeVisibility($visibility),
303 1
        ]);
304
    }
305
306
    /**
307
     * @param string $path
308
     *
309
     * @return bool
310
     */
311 1
    public function has($path)
312
    {
313
        try {
314 1
            return (bool) $this->getMetadata($path);
315
        } catch (NoSuchKeyException $e) {
316
            return false;
317
        }
318
    }
319
320
    /**
321
     * @param string $path
322
     *
323
     * @return array|bool
324
     */
325 1
    public function read($path)
326
    {
327
        try {
328 1
            if (isset($this->config['read_from_cdn']) && $this->config['read_from_cdn']) {
329
                $response = $this->getHttpClient()
330
                                 ->get($this->getTemporaryUrl($path, Carbon::now()->addMinutes(5)))
331
                                 ->getBody()
332
                                 ->getContents();
333
            } else {
334 1
                $response = $this->client->getObject([
335 1
                    'Bucket' => $this->getBucket(),
336 1
                    'Key'    => $path,
337 1
                ])->get('Body');
0 ignored issues
show
Bug introduced by
The method get() does not exist on Guzzle\Http\Message\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

337
                ])->/** @scrutinizer ignore-call */ get('Body');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
338
            }
339
340 1
            return ['contents' => (string)$response];
341
        } catch (NoSuchKeyException $e) {
342
            return false;
343
        } catch (\GuzzleHttp\Exception\ClientException $e) {
344
            return false;
345
        }
346
    }
347
348
    /**
349
     * @return \GuzzleHttp\Client
350
     */
351 1
    public function getHttpClient()
352
    {
353 1
        return new \GuzzleHttp\Client([
354 1
            'verify'          => false,
355 1
            'timeout'         => $this->config['timeout'],
356 1
            'connect_timeout' => $this->config['connect_timeout'],
357 1
        ]);
358
    }
359
360
    /**
361
     * @param string $path
362
     *
363
     * @return array|bool
364
     */
365 1
    public function readStream($path)
366
    {
367
        try {
368 1
            $temporaryUrl = $this->getTemporaryUrl($path, Carbon::now()->addMinutes(5));
369
370 1
            $stream = $this->getHttpClient()
371 1
                           ->get($temporaryUrl, ['stream' => true])
372 1
                           ->getBody()
373 1
                           ->detach();
374
375 1
            return ['stream' => $stream];
376
        } catch (NoSuchKeyException $e) {
377
            return false;
378
        } catch (\GuzzleHttp\Exception\ClientException $e) {
379
            return false;
380
        }
381
    }
382
383
    /**
384
     * @param string $directory
385
     * @param bool   $recursive
386
     *
387
     * @return array|bool
388
     */
389 1
    public function listContents($directory = '', $recursive = false)
390
    {
391 1
        $list = [];
392
393 1
        $response = $this->listObjects($directory, $recursive);
394
395 1
        foreach ((array) $response->get('Contents') as $content) {
396 1
            $list[] = $this->normalizeFileInfo($content);
397 1
        }
398
399 1
        return $list;
400
    }
401
402
    /**
403
     * @param string $path
404
     *
405
     * @return array|bool
406
     */
407 5
    public function getMetadata($path)
408
    {
409 5
        return $this->client->headObject([
410 5
            'Bucket' => $this->getBucket(),
411 5
            'Key'    => $path,
412 5
        ])->toArray();
0 ignored issues
show
Bug introduced by
The method toArray() does not exist on Guzzle\Http\Message\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

412
        ])->/** @scrutinizer ignore-call */ toArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
413
    }
414
415
    /**
416
     * @param string $path
417
     *
418
     * @return array|bool
419
     */
420 1
    public function getSize($path)
421
    {
422 1
        $meta = $this->getMetadata($path);
423
424 1
        return isset($meta['ContentLength'])
425 1
            ? ['size' => $meta['ContentLength']] : false;
426
    }
427
428
    /**
429
     * @param string $path
430
     *
431
     * @return array|bool
432
     */
433 1
    public function getMimetype($path)
434
    {
435 1
        $meta = $this->getMetadata($path);
436
437 1
        return isset($meta['ContentType'])
438 1
            ? ['mimetype' => $meta['ContentType']] : false;
439
    }
440
441
    /**
442
     * @param string $path
443
     *
444
     * @return array|bool
445
     */
446 1
    public function getTimestamp($path)
447
    {
448 1
        $meta = $this->getMetadata($path);
449
450 1
        return isset($meta['LastModified'])
451 1
            ? ['timestamp' => strtotime($meta['LastModified'])] : false;
452
    }
453
454
    /**
455
     * @param string $path
456
     *
457
     * @return array|bool
458
     */
459 1
    public function getVisibility($path)
460
    {
461 1
        $meta = $this->client->getObjectAcl([
462 1
            'Bucket' => $this->getBucket(),
463 1
            'Key'    => $path,
464 1
        ]);
465
466 1
        foreach ($meta->get('Grants') as $grant) {
467 1
            if (isset($grant['Grantee']['URI'])
468 1
                && $grant['Permission'] === 'READ'
469 1
                && strpos($grant['Grantee']['URI'], 'global/AllUsers') !== false
470 1
            ) {
471
                return ['visibility' => AdapterInterface::VISIBILITY_PUBLIC];
472
            }
473 1
        }
474
475 1
        return ['visibility' => AdapterInterface::VISIBILITY_PRIVATE];
476
    }
477
478
    /**
479
     * @param array $content
480
     *
481
     * @return array
482
     */
483 1
    private function normalizeFileInfo(array $content)
484
    {
485 1
        $path = pathinfo($content['Key']);
486
487
        return [
488 1
            'type'      => substr($content['Key'], -1) === '/' ? 'dir' : 'file',
489 1
            'path'      => $content['Key'],
490 1
            'timestamp' => Carbon::parse($content['LastModified'])->getTimestamp(),
491 1
            'size'      => (int) $content['Size'],
492 1
            'dirname'   => (string) $path['dirname'],
493 1
            'basename'  => (string) $path['basename'],
494 1
            'extension' => isset($path['extension']) ? $path['extension'] : '',
495 1
            'filename'  => (string) $path['filename'],
496 1
        ];
497
    }
498
499
    /**
500
     * @param string $directory
501
     * @param bool   $recursive
502
     *
503
     * @return mixed
504
     */
505 2
    private function listObjects($directory = '', $recursive = false)
506
    {
507 2
        return $this->client->listObjects([
508 2
            'Bucket'    => $this->getBucket(),
509 2
            'Prefix'    => ((string) $directory === '') ? '' : ($directory.'/'),
510 2
            'Delimiter' => $recursive ? '' : '/',
511 2
        ]);
512
    }
513
514
    /**
515
     * @param Config $config
516
     *
517
     * @return array
518
     */
519 4
    private function prepareUploadConfig(Config $config)
520
    {
521 4
        $options = [];
522
523 4
        if ($config->has('params')) {
524
            $options['params'] = $config->get('params');
525
        }
526
527 4
        if ($config->has('visibility')) {
528
            $options['params']['ACL'] = $this->normalizeVisibility($config->get('visibility'));
529
        }
530
531 4
        return $options;
532
    }
533
534
    /**
535
     * @param $visibility
536
     *
537
     * @return string
538
     */
539 1
    private function normalizeVisibility($visibility)
540
    {
541
        switch ($visibility) {
542 1
            case AdapterInterface::VISIBILITY_PUBLIC:
543
                $visibility = 'public-read';
544
                break;
545
        }
546
547 1
        return $visibility;
548
    }
549
}
550