Completed
Pull Request — master (#10)
by
unknown
04:44
created

QiniuAdapter::getUploadToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 4
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/flysystem-qiniu.
5
 * (c) overtrue <[email protected]>
6
 * This source file is subject to the MIT license that is bundled
7
 * with this source code in the file LICENSE.
8
 */
9
10
namespace Overtrue\Flysystem\Qiniu;
11
12
use League\Flysystem\Adapter\AbstractAdapter;
13
use League\Flysystem\Adapter\Polyfill\NotSupportingVisibilityTrait;
14
use League\Flysystem\Config;
15
use Qiniu\Auth;
16
use Qiniu\Cdn\CdnManager;
17
use Qiniu\Storage\BucketManager;
18
use Qiniu\Storage\UploadManager;
19
20
/**
21
 * Class QiniuAdapter.
22
 *
23
 * @author overtrue <[email protected]>
24
 */
25
class QiniuAdapter extends AbstractAdapter
26
{
27
    use NotSupportingVisibilityTrait;
28
29
    /**
30
     * @var string
31
     */
32
    protected $accessKey;
33
34
    /**
35
     * @var string
36
     */
37
    protected $secretKey;
38
39
    /**
40
     * @var string
41
     */
42
    protected $bucket;
43
44
    /**
45
     * @var string
46
     */
47
    protected $domain;
48
49
    /**
50
     * @var \Qiniu\Auth
51
     */
52
    protected $authManager;
53
54
    /**
55
     * @var \Qiniu\Storage\UploadManager
56
     */
57
    protected $uploadManager;
58
59
    /**
60
     * @var \Qiniu\Storage\BucketManager
61
     */
62
    protected $bucketManager;
63
64
    /**
65
     * @var \Qiniu\Cdn\CdnManager
66
     */
67
    protected $cdnManager;
68
69
    /**
70
     * QiniuAdapter constructor.
71
     *
72
     * @param string $accessKey
73
     * @param string $secretKey
74
     * @param string $bucket
75
     * @param string $domain
76
     */
77 1
    public function __construct($accessKey, $secretKey, $bucket, $domain)
78
    {
79 1
        $this->accessKey = $accessKey;
80 1
        $this->secretKey = $secretKey;
81 1
        $this->bucket = $bucket;
82 1
        $this->domain = $domain;
83 1
    }
84
85
    /**
86
     * Write a new file.
87
     *
88
     * @param string $path
89
     * @param string $contents
90
     * @param Config $config   Config object
91
     *
92
     * @return array|false false on failure file meta data on success
93
     */
94 2
    public function write($path, $contents, Config $config)
95
    {
96 2
        $mime = 'application/octet-stream';
97
98 2
        if ($config->has('mime')) {
99 1
            $mime = $config->get('mime');
100 1
        }
101
102 2
        list($response, $error) = $this->getUploadManager()->put(
103 2
            $this->getAuthManager()->uploadToken($this->bucket),
104 2
            $path,
105 2
            $contents,
106 2
            null,
107
            $mime
108 2
        );
109
110 2
        if ($error) {
111 2
            return false;
112
        }
113
114 2
        return $response;
115
    }
116
117
    /**
118
     * Write a new file using a stream.
119
     *
120
     * @param string   $path
121
     * @param resource $resource
122
     * @param Config   $config   Config object
123
     *
124
     * @return array|false false on failure file meta data on success
125
     */
126 1
    public function writeStream($path, $resource, Config $config)
127
    {
128 1
        $contents = '';
129
130 1
        while (!feof($resource)) {
131 1
            $contents .= fread($resource, 1024);
132 1
        }
133
134 1
        $response = $this->write($path, $contents, $config);
135
136 1
        if ($response === false) {
137 1
            return $response;
138
        }
139
140 1
        return compact('path');
141
    }
142
143
    /**
144
     * Update a file.
145
     *
146
     * @param string $path
147
     * @param string $contents
148
     * @param Config $config   Config object
149
     *
150
     * @return array|false false on failure file meta data on success
151
     */
152 1
    public function update($path, $contents, Config $config)
153
    {
154 1
        $this->delete($path);
155
156 1
        return $this->write($path, $contents, $config);
157
    }
158
159
    /**
160
     * Update a file using a stream.
161
     *
162
     * @param string   $path
163
     * @param resource $resource
164
     * @param Config   $config   Config object
165
     *
166
     * @return array|false false on failure file meta data on success
167
     */
168 1
    public function updateStream($path, $resource, Config $config)
169
    {
170 1
        $this->delete($path);
171
172 1
        return $this->writeStream($path, $resource, $config);
173
    }
174
175
    /**
176
     * Rename a file.
177
     *
178
     * @param string $path
179
     * @param string $newPath
180
     *
181
     * @return bool
182
     */
183 1
    public function rename($path, $newPath)
184
    {
185 1
        $response = $this->getBucketManager()->rename($this->bucket, $path, $newPath);
186
187 1
        return is_null($response);
188
    }
189
190
    /**
191
     * Copy a file.
192
     *
193
     * @param string $path
194
     * @param string $newPath
195
     *
196
     * @return bool
197
     */
198 1
    public function copy($path, $newPath)
199
    {
200 1
        $response = $this->getBucketManager()->copy($this->bucket, $path, $this->bucket, $newPath);
201
202 1
        return is_null($response);
203
    }
204
205
    /**
206
     * Delete a file.
207
     *
208
     * @param string $path
209
     *
210
     * @return bool
211
     */
212 1
    public function delete($path)
213
    {
214 1
        $response = $this->getBucketManager()->delete($this->bucket, $path);
215
216 1
        return is_null($response);
217
    }
218
219
    /**
220
     * Delete a directory.
221
     *
222
     * @param string $directory
223
     *
224
     * @return bool
225
     */
226 1
    public function deleteDir($directory)
227
    {
228 1
        return true;
229
    }
230
231
    /**
232
     * Create a directory.
233
     *
234
     * @param string $directory directory name
235
     * @param Config $config
236
     *
237
     * @return array|false
238
     */
239 1
    public function createDir($directory, Config $config)
240
    {
241 1
        return ['path' => $directory, 'type' => 'dir'];
242
    }
243
244
    /**
245
     * Check whether a file exists.
246
     *
247
     * @param string $path
248
     *
249
     * @return array|bool|null
250
     */
251 1
    public function has($path)
252
    {
253 1
        list($response, $error) = $this->getBucketManager()->stat($this->bucket, $path);
254
255 1
        return !$error || is_array($response);
256
    }
257
258
    /**
259
     * Get resource url.
260
     *
261
     * @param string $path
262
     *
263
     * @return string
264
     */
265 3
    public function getUrl($path)
266
    {
267 3
        return $this->normalizeHost($this->domain).ltrim($path, '/');
268
    }
269
270
    /**
271
     * Read a file.
272
     *
273
     * @param string $path
274
     *
275
     * @return array|false
276
     */
277 1
    public function read($path)
278
    {
279 1
        $contents = file_get_contents($this->getUrl($path));
280
281 1
        return compact('contents', 'path');
282
    }
283
284
    /**
285
     * Read a file as a stream.
286
     *
287
     * @param string $path
288
     *
289
     * @return array|false
290
     */
291 1
    public function readStream($path)
292
    {
293 1
        if (ini_get('allow_url_fopen')) {
294 1
            $stream = fopen($this->normalizeHost($this->domain).$path, 'r');
295
296 1
            return compact('stream', 'path');
297
        }
298
299 1
        return false;
300
    }
301
302
    /**
303
     * List contents of a directory.
304
     *
305
     * @param string $directory
306
     * @param bool   $recursive
307
     *
308
     * @return array
309
     */
310 1
    public function listContents($directory = '', $recursive = false)
311
    {
312 1
        $list = [];
313
314 1
        $result = $this->getBucketManager()->listFiles($this->bucket, $directory);
315
316 1
        foreach (isset($result[0]['items']) ? $result[0]['items'] : [] as $files) {
317 1
            $list[] = $this->normalizeFileInfo($files);
318 1
        }
319
320 1
        return $list;
321
    }
322
323
    /**
324
     * Get all the meta data of a file or directory.
325
     *
326
     * @param string $path
327
     *
328
     * @return array|false
329
     */
330 1
    public function getMetadata($path)
331
    {
332 1
        $result = $this->getBucketManager()->stat($this->bucket, $path);
333 1
        $result[0]['key'] = $path;
334
335 1
        return $this->normalizeFileInfo($result[0]);
0 ignored issues
show
Documentation introduced by
$result[0] is of type null|object<Qiniu\Http\Error>, but the function expects a array.

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...
336
    }
337
338
    /**
339
     * Get the size of a file.
340
     *
341
     * @param string $path
342
     *
343
     * @return array|false
344
     */
345 1
    public function getSize($path)
346
    {
347 1
        return $this->getMetadata($path);
348
    }
349
350
    /**
351
     * Fetch url to bucket.
352
     *
353
     * @param string $path
354
     * @param string $url
355
     *
356
     * @return array|false
357
     */
358
    public function fetch($path, $url)
359
    {
360
        list($response, $error) = $this->getBucketManager()->fetch($url, $this->bucket, $path);
361
362
        if ($error) {
363
            return false;
364
        }
365
366
        return $response;
367
    }
368
369
370
    /**
371
     * Get private file download url
372
     *
373
     * @param $path
374
     * @param int $expires
375
     *
376
     * @return string
377
     */
378 1
    public function privateDownloadUrl($path, $expires = 3600)
379
    {
380 1
        $url = $this->getUrl($path);
381
382 1
        return  $this->getAuthManager()->privateDownloadUrl($url, $expires);
383
    }
384
385
386
    /**
387
     * Refresh file cache
388
     *
389
     * @param $path
390
     *
391
     * @return array
392
     */
393 1
    public function refresh($path)
394
    {
395 1
        if (is_string($path)) {
396 1
            $path = [$path];
397 1
        }
398
399
        // 将 $path 变成完整的 url
400 1
        $urls = array_map([$this, 'getUrl'], $path);
401
402 1
        return $this->getCdnManager()->refreshUrls($urls);
403
    }
404
405
    /**
406
     * Get the mime-type of a file.
407
     *
408
     * @param string $path
409
     *
410
     * @return array|false
411
     */
412 1
    public function getMimeType($path)
413
    {
414 1
        $response = $this->getBucketManager()->stat($this->bucket, $path);
415
416 1
        if (empty($response[0]['mimeType'])) {
417 1
            return false;
418
        }
419
420 1
        return ['mimetype' => $response[0]['mimeType']];
421
    }
422
423
    /**
424
     * Get the timestamp of a file.
425
     *
426
     * @param string $path
427
     *
428
     * @return array|false
429
     */
430 1
    public function getTimestamp($path)
431
    {
432 1
        return $this->getMetadata($path);
433
    }
434
435
    /**
436
     * @param \Qiniu\Storage\BucketManager $manager
437
     *
438
     * @return $this
439
     */
440 1
    public function setBucketManager(BucketManager $manager)
441
    {
442 1
        $this->bucketManager = $manager;
443
444 1
        return $this;
445
    }
446
447
    /**
448
     * @param \Qiniu\Storage\UploadManager $manager
449
     *
450
     * @return $this
451
     */
452 1
    public function setUploadManager(UploadManager $manager)
453
    {
454 1
        $this->uploadManager = $manager;
455
456 1
        return $this;
457
    }
458
459
    /**
460
     * @param \Qiniu\Auth $manager
461
     *
462
     * @return $this
463
     */
464 1
    public function setAuthManager(Auth $manager)
465
    {
466 1
        $this->authManager = $manager;
467
468 1
        return $this;
469
    }
470
471
    /**
472
     * @param CdnManager $manager
473
     *
474
     * @return $this
475
     */
476
    public function setCdnManager(CdnManager $manager)
477
    {
478
        $this->cdnManager = $manager;
479
480
        return $this;
481
    }
482
483
    /**
484
     * @return \Qiniu\Storage\BucketManager
485
     */
486 1
    public function getBucketManager()
487
    {
488 1
        return $this->bucketManager ?: $this->bucketManager = new BucketManager($this->getAuthManager());
489
    }
490
491
    /**
492
     * @return \Qiniu\Auth
493
     */
494 1
    public function getAuthManager()
495
    {
496 1
        return $this->authManager ?: $this->authManager = new Auth($this->accessKey, $this->secretKey);
497
    }
498
499
    /**
500
     * @return \Qiniu\Storage\UploadManager
501
     */
502 1
    public function getUploadManager()
503
    {
504 1
        return $this->uploadManager ?: $this->uploadManager = new UploadManager();
505
    }
506
507
    /**
508
     * @return \Qiniu\Cdn\CdnManager
509
     */
510
    public function getCdnManager()
511
    {
512
        return $this->cdnManager ?: $this->cdnManager = new CdnManager($this->getAuthManager());
513
    }
514
515
    /**
516
     * Get the upload token.
517
     *
518
     * @param string|null $key
519
     * @param int         $expires
520
     * @param string|null $policy
521
     * @param string|null $strictPolice
522
     *
523
     * @return string
524
     */
525 1
    public function getUploadToken($key = null, $expires = 3600, $policy = null, $strictPolice = null)
526
    {
527 1
        return $this->getAuthManager()->uploadToken($this->bucket, $key, $expires, $policy, $strictPolice);
0 ignored issues
show
Documentation introduced by
$strictPolice is of type string|null, but the function expects a boolean.

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...
528
    }
529
530
    /**
531
     * @param array $stats
532
     *
533
     * @return array
534
     */
535 2
    protected function normalizeFileInfo(array $stats)
536
    {
537
        return [
538 2
            'type' => 'file',
539 2
            'path' => $stats['key'],
540 2
            'timestamp' => floor($stats['putTime'] / 10000000),
541 2
            'size' => $stats['fsize'],
542 2
        ];
543
    }
544
545
    /**
546
     * @param string $domain
547
     *
548
     * @return string
549
     */
550 4
    protected function normalizeHost($domain)
551
    {
552 4
        if (0 !== stripos($domain, 'https://') && 0 !== stripos($domain, 'http://')) {
553 4
            $domain = "http://{$domain}";
554 4
        }
555
556 4
        return rtrim($domain, '/').'/';
557
    }
558
}
559