Passed
Push — master ( 06dccb...39b275 )
by frey
04:00
created

Adapter::getCOSClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
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 20
    public function getBucket()
73
    {
74 20
        return preg_replace(
75 20
            "/-{$this->getAppId()}$/",
76 20
            '',
77 20
            $this->config['bucket']
78 20
        );
79
    }
80
81
    /**
82
     * @return string
83
     */
84 20
    public function getAppId()
85
    {
86 20
        return $this->config['credentials']['appId'];
87
    }
88
89
    /**
90
     * @return string
91
     */
92 2
    public function getRegion()
93
    {
94 2
        return array_key_exists($this->config['region'], $this->regionMap)
95 2
            ? $this->regionMap[$this->config['region']] : $this->config['region'];
96
    }
97
98
    /**
99
     * @param $path
100
     *
101
     * @return string
102
     */
103 2
    public function getSourcePath($path)
104
    {
105 2
        return sprintf('%s.cos.%s.myqcloud.com/%s',
106 2
            $this->getBucketWithAppId(), $this->getRegion(), $path
107 2
        );
108
    }
109
110
    /**
111
     * @param string $path
112
     *
113
     * @return string
114
     */
115 5
    public function getUrl($path)
116 4
    {
117 1
        if ($this->config['cdn']) {
118
            return $this->applyPathPrefix($path);
119
        }
120
121
        $options = [
122 5
            'Scheme' => isset($this->config['scheme']) ? $this->config['scheme'] : 'http',
123 1
        ];
124
125 5
        $objectUrl = $this->client->getObjectUrl(
126 1
            $this->getBucket(), $path, null, $options
127 1
        );
128
129 1
        return $objectUrl;
130
    }
131
132
    /**
133
     * @param string             $path
134
     * @param \DateTimeInterface $expiration
135
     * @param array              $options
136
     *
137
     * @return string
138
     */
139 2
    public function getTemporaryUrl($path, DateTimeInterface $expiration, array $options = [])
140
    {
141 2
        $options = array_merge(
142 2
            $options,
143 2
            ['Scheme' => isset($this->config['scheme']) ? $this->config['scheme'] : 'http']
144 2
        );
145
146 2
        $objectUrl = $this->client->getObjectUrl(
147 2
            $this->getBucket(), $path, $expiration->format('c'), $options
148 2
        );
149
150 2
        return $objectUrl;
151
    }
152
153
    /**
154
     * @param string $path
155
     * @param string $contents
156
     * @param Config $config
157
     *
158
     * @return array|false
159
     */
160 2
    public function write($path, $contents, Config $config)
161
    {
162 2
        $options = $this->prepareUploadConfig($config);
163
164 2
        return $this->client->upload($this->getBucket(), $path, $contents, $options);
165
    }
166
167
    /**
168
     * @param string   $path
169
     * @param resource $resource
170
     * @param Config   $config
171
     *
172
     * @return array|false
173
     */
174 4
    public function writeStream($path, $resource, Config $config)
175
    {
176 2
        $options = $this->prepareUploadConfig($config);
177
178 2
        return $this->client->upload(
179 2
            $this->getBucket(),
180 4
            $path,
181 2
            stream_get_contents($resource, -1, 0),
182 2
            $options
183 2
        );
184
    }
185
186
    /**
187
     * @param string $path
188
     * @param string $contents
189
     * @param Config $config
190
     *
191
     * @return array|false
192
     */
193 1
    public function update($path, $contents, Config $config)
194
    {
195 1
        return $this->write($path, $contents, $config);
196
    }
197
198
    /**
199
     * @param string   $path
200
     * @param resource $resource
201
     * @param Config   $config
202
     *
203
     * @return array|false
204
     */
205 1
    public function updateStream($path, $resource, Config $config)
206
    {
207 1
        return $this->writeStream($path, $resource, $config);
208
    }
209
210
    /**
211
     * @param string $path
212
     * @param string $newpath
213
     *
214
     * @return bool
215
     */
216 1
    public function rename($path, $newpath)
217
    {
218 1
        $result = $this->copy($path, $newpath);
219
220 1
        $this->delete($path);
221
222 1
        return $result;
223
    }
224
225
    /**
226
     * @param string $path
227
     * @param string $newpath
228
     *
229
     * @return bool
230
     */
231 2
    public function copy($path, $newpath)
232
    {
233 2
        $source = $this->getSourcePath($path);
234
235 2
        return (bool) $this->client->copy($this->getBucket(), $newpath, $source);
236
    }
237
238
    /**
239
     * @param string $path
240
     *
241
     * @return bool
242
     */
243 2
    public function delete($path)
244
    {
245 2
        $result = $this->client->deleteObject([
246 2
            'Bucket' => $this->getBucket(),
247 2
            'Key'    => $path,
248 2
        ]);
249
250 2
        return (bool) $result;
251
    }
252
253
    /**
254
     * @param string $dirname
255
     *
256
     * @return bool
257
     */
258 1
    public function deleteDir($dirname)
259
    {
260 1
        $result = $this->client->deleteObject([
261 1
            'Bucket' => $this->getBucket(),
262 1
            'Key'    => $dirname.'/',
263 1
        ]);
264
265 1
        return (bool) $result;
266
    }
267
268
    /**
269
     * @param string $dirname
270
     * @param Config $config
271
     *
272
     * @return array|false
273
     */
274 1
    public function createDir($dirname, Config $config)
275
    {
276 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...
277 1
            'Bucket' => $this->getBucket(),
278 1
            'Key'    => $dirname.'/',
279 1
            'Body'   => '',
280 1
        ]);
281
    }
282
283
    /**
284
     * @param string $path
285
     * @param string $visibility
286
     *
287
     * @return bool
288
     */
289 1
    public function setVisibility($path, $visibility)
290
    {
291 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...
292 1
            'Bucket' => $this->getBucket(),
293 1
            'Key'    => $path,
294 1
            'ACL'    => $this->normalizeVisibility($visibility),
295 1
        ]);
296
    }
297
298
    /**
299
     * @param string $path
300
     *
301
     * @return bool
302
     */
303 1
    public function has($path)
304
    {
305
        try {
306 1
            return (bool) $this->getMetadata($path);
307
        } catch (NoSuchKeyException $e) {
308
            return false;
309
        }
310
    }
311
312
    /**
313
     * @param string $path
314
     *
315
     * @return array|bool
316
     */
317 1
    public function read($path)
318
    {
319
        try {
320 1
            $response = $this->forceReadFromCDN()
321 1
                ? $this->readFromCDN($path)
322 1
                : $this->readFromSource($path);
323
324 1
            return ['contents' => (string) $response];
325
        } catch (NoSuchKeyException $e) {
326
            return false;
327
        } catch (\GuzzleHttp\Exception\ClientException $e) {
328
            return false;
329
        }
330
    }
331
332
    /**
333
     * @return bool
334
     */
335 1
    protected function forceReadFromCDN()
336
    {
337 1
        return $this->config['cdn']
338 1
            && isset($this->config['read_from_cdn'])
339 1
            && $this->config['read_from_cdn'];
340
    }
341
342
    /**
343
     * @param $path
344
     *
345
     * @return string
346
     */
347
    protected function readFromCDN($path)
348
    {
349
        return $this->getHttpClient()
350
            ->get($this->applyPathPrefix($path))
351
            ->getBody()
352
            ->getContents();
353
    }
354
355
    /**
356
     * @param $path
357
     *
358
     * @return string
359
     */
360 1
    protected function readFromSource($path)
361
    {
362 1
        return $this->client->getObject([
363 1
            'Bucket' => $this->getBucket(),
364 1
            'Key'    => $path,
365 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

365
        ])->/** @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...
366
    }
367
368
    /**
369
     * @return \GuzzleHttp\Client
370
     */
371 1
    public function getHttpClient()
372
    {
373 1
        return new \GuzzleHttp\Client([
374 1
            'timeout'         => $this->config['timeout'],
375 1
            'connect_timeout' => $this->config['connect_timeout'],
376 1
        ]);
377
    }
378
379
    /**
380
     * @param string $path
381
     *
382
     * @return array|bool
383
     */
384 1
    public function readStream($path)
385
    {
386
        try {
387 1
            $temporaryUrl = $this->getTemporaryUrl($path, Carbon::now()->addMinutes(5));
388
389 1
            $stream = $this->getHttpClient()
390 1
                           ->get($temporaryUrl, ['stream' => true])
391 1
                           ->getBody()
392 1
                           ->detach();
393
394 1
            return ['stream' => $stream];
395
        } catch (NoSuchKeyException $e) {
396
            return false;
397
        } catch (\GuzzleHttp\Exception\ClientException $e) {
398
            return false;
399
        }
400
    }
401
402
    /**
403
     * @param string $directory
404
     * @param bool   $recursive
405
     *
406
     * @return array|bool
407
     */
408 1
    public function listContents($directory = '', $recursive = false)
409
    {
410 1
        $list = [];
411
412 1
        $response = $this->listObjects($directory, $recursive);
413
414 1
        foreach ((array) $response->get('Contents') as $content) {
415 1
            $list[] = $this->normalizeFileInfo($content);
416 1
        }
417
418 1
        return $list;
419
    }
420
421
    /**
422
     * @param string $path
423
     *
424
     * @return array|bool
425
     */
426 5
    public function getMetadata($path)
427
    {
428 5
        return $this->client->headObject([
429 5
            'Bucket' => $this->getBucket(),
430 5
            'Key'    => $path,
431 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

431
        ])->/** @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...
432
    }
433
434
    /**
435
     * @param string $path
436
     *
437
     * @return array|bool
438
     */
439 1
    public function getSize($path)
440
    {
441 1
        $meta = $this->getMetadata($path);
442
443 1
        return isset($meta['ContentLength'])
444 1
            ? ['size' => $meta['ContentLength']] : false;
445
    }
446
447
    /**
448
     * @param string $path
449
     *
450
     * @return array|bool
451
     */
452 1
    public function getMimetype($path)
453
    {
454 1
        $meta = $this->getMetadata($path);
455
456 1
        return isset($meta['ContentType'])
457 1
            ? ['mimetype' => $meta['ContentType']] : false;
458
    }
459
460
    /**
461
     * @param string $path
462
     *
463
     * @return array|bool
464
     */
465 1
    public function getTimestamp($path)
466
    {
467 1
        $meta = $this->getMetadata($path);
468
469 1
        return isset($meta['LastModified'])
470 1
            ? ['timestamp' => strtotime($meta['LastModified'])] : false;
471
    }
472
473
    /**
474
     * @param string $path
475
     *
476
     * @return array|bool
477
     */
478 1
    public function getVisibility($path)
479
    {
480 1
        $meta = $this->client->getObjectAcl([
481 1
            'Bucket' => $this->getBucket(),
482 1
            'Key'    => $path,
483 1
        ]);
484
485 1
        foreach ($meta->get('Grants') as $grant) {
486 1
            if (isset($grant['Grantee']['URI'])
487 1
                && $grant['Permission'] === 'READ'
488 1
                && strpos($grant['Grantee']['URI'], 'global/AllUsers') !== false
489 1
            ) {
490
                return ['visibility' => AdapterInterface::VISIBILITY_PUBLIC];
491
            }
492 1
        }
493
494 1
        return ['visibility' => AdapterInterface::VISIBILITY_PRIVATE];
495
    }
496
497
    /**
498
     * @param array $content
499
     *
500
     * @return array
501
     */
502 1
    private function normalizeFileInfo(array $content)
503
    {
504 1
        $path = pathinfo($content['Key']);
505
506
        return [
507 1
            'type'      => substr($content['Key'], -1) === '/' ? 'dir' : 'file',
508 1
            'path'      => $content['Key'],
509 1
            'timestamp' => Carbon::parse($content['LastModified'])->getTimestamp(),
510 1
            'size'      => (int) $content['Size'],
511 1
            'dirname'   => (string) $path['dirname'],
512 1
            'basename'  => (string) $path['basename'],
513 1
            'extension' => isset($path['extension']) ? $path['extension'] : '',
514 1
            'filename'  => (string) $path['filename'],
515 1
        ];
516
    }
517
518
    /**
519
     * @param string $directory
520
     * @param bool   $recursive
521
     *
522
     * @return mixed
523
     */
524 1
    private function listObjects($directory = '', $recursive = false)
525
    {
526 1
        return $this->client->listObjects([
527 1
            'Bucket'    => $this->getBucket(),
528 1
            'Prefix'    => ((string) $directory === '') ? '' : ($directory.'/'),
529 1
            'Delimiter' => $recursive ? '' : '/',
530 1
        ]);
531
    }
532
533
    /**
534
     * @param Config $config
535
     *
536
     * @return array
537
     */
538 4
    private function prepareUploadConfig(Config $config)
539
    {
540 4
        $options = [];
541
542 4
        if (isset($this->config['encrypt']) && $this->config['encrypt']) {
543
            $options['params']['ServerSideEncryption'] = 'AES256';
544
        }
545
546 4
        if ($config->has('params')) {
547
            $options['params'] = $config->get('params');
548
        }
549
550 4
        if ($config->has('visibility')) {
551
            $options['params']['ACL'] = $this->normalizeVisibility($config->get('visibility'));
552
        }
553
554 4
        return $options;
555
    }
556
557
    /**
558
     * @param $visibility
559
     *
560
     * @return string
561
     */
562 1
    private function normalizeVisibility($visibility)
563
    {
564
        switch ($visibility) {
565 1
            case AdapterInterface::VISIBILITY_PUBLIC:
566
                $visibility = 'public-read';
567
                break;
568
        }
569
570 1
        return $visibility;
571
    }
572
573
    /**
574
     * @return Client
575
     */
576
    public function getCOSClient()
577
    {
578
        return $this->client;
579
    }
580
}
581