Completed
Push — master ( a3d8ca...3dabab )
by frey
06:20
created

Adapter::prepareUploadConfig()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.7898

Importance

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

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

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