Completed
Pull Request — master (#293)
by
unknown
23:27
created

BucketManager   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 553
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 73.18%

Importance

Changes 0
Metric Value
dl 0
loc 553
ccs 131
cts 179
cp 0.7318
rs 4.08
c 0
b 0
f 0
wmc 59
lcom 2
cbo 5

41 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A buckets() 0 8 2
A creatBucket() 0 5 1
A deleteBucket() 0 5 1
A domains() 0 4 1
A bucketInfo() 0 5 1
A bucketInfos() 0 5 1
A listFiles() 0 10 1
A stat() 0 5 1
A delete() 0 6 1
A rename() 0 4 1
A copy() 0 11 2
A move() 0 11 2
A changeMime() 0 8 1
A changeType() 0 7 1
A changeStatus() 0 7 1
A fetch() 0 13 1
A prefetch() 0 12 1
A batch() 0 5 1
A deleteAfterDays() 0 7 1
A getRsfHost() 0 8 2
A getRsHost() 0 8 2
A getApiHost() 0 8 2
A getUcHost() 0 8 2
A rsPost() 0 5 1
A apiPost() 0 5 1
A ucPost() 0 5 1
A apiGet() 0 5 1
A rsGet() 0 5 1
A get() 0 9 2
A post() 0 10 3
A buildBatchCopy() 0 4 1
A buildBatchRename() 0 4 1
A buildBatchMove() 0 4 1
A buildBatchDelete() 0 4 1
A buildBatchStat() 0 4 1
A buildBatchDeleteAfterDays() 0 8 2
A buildBatchChangeMime() 0 8 2
A buildBatchChangeType() 0 8 2
A oneKeyBatch() 0 8 2
A twoKeyBatch() 0 17 4

How to fix   Complexity   

Complex Class

Complex classes like BucketManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BucketManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Qiniu\Storage;
3
4
use Qiniu\Auth;
5
use Qiniu\Config;
6
use Qiniu\Zone;
7
use Qiniu\Http\Client;
8
use Qiniu\Http\Error;
9
10
/**
11
 * 主要涉及了空间资源管理及批量操作接口的实现,具体的接口规格可以参考
12
 *
13
 * @link https://developer.qiniu.com/kodo/api/1274/rs
14
 */
15
final class BucketManager
16
{
17
    private $auth;
18
    private $config;
19
20 42
    public function __construct(Auth $auth, Config $config = null)
21
    {
22 42
        $this->auth = $auth;
23 42
        if ($config == null) {
24 42
            $this->config = new Config();
25 42
        } else {
26
            $this->config = $config;
27
        }
28 42
    }
29
30
    /**
31
     * 获取指定账号下所有的空间名。
32
     *
33
     * @return string[] 包含所有空间名
34
     */
35 3
    public function buckets($shared = true)
36
    {
37 3
        $includeShared = "false";
38 3
        if ($shared === true) {
39 3
            $includeShared = "true";
40 3
        }
41 3
        return $this->rsGet('/buckets?shared=' . $includeShared);
42
    }
43
44
    /**
45
     * 创建空间
46
     *
47
     * @param $name     创建的空间名
48
     * @param $region    创建的区域,默认华东
49
     *
50
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
51
     */
52
    public function creatBucket($name, $region='z0')
53
    {
54
        $path = '/mkbucketv2/'.$name.'/region/' . $region;
55
        return $this->rsPost($path, null);
56
    }
57
58
    /**
59
     * 删除空间
60
     *
61
     * @param $name     删除的空间名
62
     *
63
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
64
     */
65
    public function deleteBucket($name)
66
    {
67
        $path = '/drop/'.$name;
68
        return $this->rsPost($path, null);
69
    }
70
71
    /**
72
     * 获取指定空间绑定的所有的域名
73
     *
74
     * @return string[] 包含所有空间域名
75
     */
76
    public function domains($bucket)
77
    {
78
        return $this->apiGet('/v6/domain/list?tbl=' . $bucket);
79 3
    }
80
81 3
    /**
82 3
     * 获取指定空间的相关信息
83 3
     *
84 3
     * @return string[] 包含空间信息
85 3
     */
86 3
    public function bucketInfo($bucket){
87 3
        $path = '/v2/bucketInfo?bucket=' . $bucket;
88
        $info = $this->ucPost($path);
89
        return $info;
90
    }
91
92
    /**
93
     * 获取指定zone的空间信息列表
94
     * 在Region 未指定且Global 不为 true 时(包含未指定的情况,下同),返回用户的所有空间。
95
     * 在指定了 region 参数且 global 不为 true 时,只列举非全局空间。
96
     * 在指定了global为 true 时,返回所有全局空间,忽略region 参数
97
     * shared 不指定shared参数或指定shared为rw或false时,返回包含具有读写权限空间,指定shared为rd或true时,返回包含具有读权限空间。
98
     * fs:如果为 true,会返回每个空间当前的文件数和存储量(实时数据)。
99
     *
100
     * @return string[] 包含空间信息
101
     */
102
    public function bucketInfos($region=null, $global='false', $shared='false', $fs='false'){
103
        $path = '/v2/bucketInfos?region=' . $region . '&global=' . $global . '&shared=' . $shared . '&fs=' . $fs;
104
        $info = $this->ucPost($path);
105
        return $info;
106
    }
107 6
108
    /**
109 6
     * 获取空间绑定的域名列表
110 6
     * @return string[] 包含空间绑定的所有域名
111
     */
112
113
    /**
114
     * 列取空间的文件列表
115
     *
116
     * @param $bucket     空间名
117
     * @param $prefix     列举前缀
118
     * @param $marker     列举标识符
119
     * @param $limit      单次列举个数限制
120
     * @param $delimiter  指定目录分隔符
121
     *
122 15
     * @return array    包含文件信息的数组,类似:[
123
     *                                              {
124 15
     *                                                 "hash" => "<Hash string>",
125 15
     *                                                  "key" => "<Key string>",
126 15
     *                                                  "fsize" => "<file size>",
127
     *                                                  "putTime" => "<file modify time>"
128
     *                                              },
129
     *                                              ...
130
     *                                            ]
131
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
132
     */
133
    public function listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null)
134
    {
135
        $query = array('bucket' => $bucket);
136
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
137
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
138
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
139 3
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
140
        $url = $this->getRsfHost() . '/list?' . http_build_query($query);
141 3
        return $this->get($url);
142
    }
143
144
    /**
145
     * 获取资源的元信息,但不返回文件内容
146
     *
147
     * @param $bucket     待获取信息资源所在的空间
148
     * @param $key        待获取资源的文件名
149
     *
150
     * @return array    包含文件信息的数组,类似:
151
     *                                              [
152
     *                                                  "hash" => "<Hash string>",
153
     *                                                  "key" => "<Key string>",
154
     *                                                  "fsize" => <file size>,
155 15
     *                                                  "putTime" => "<file modify time>"
156
     *                                                  "fileType" => <file type>
157 15
     *                                              ]
158 15
     *
159 15
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
160 15
     */
161 3
    public function stat($bucket, $key)
162 3
    {
163 15
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
164 15
        return $this->rsGet($path);
165
    }
166
167
    /**
168
     * 删除指定资源
169
     *
170
     * @param $bucket     待删除资源所在的空间
171
     * @param $key        待删除资源的文件名
172
     *
173
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
174
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
175
     */
176
    public function delete($bucket, $key)
177
    {
178 3
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
179
        list(, $error) = $this->rsPost($path);
180 3
        return $error;
181 3
    }
182 3
183 3
184
    /**
185
     * 给资源进行重命名,本质为move操作。
186 3
     *
187 3
     * @param $bucket     待操作资源所在空间
188
     * @param $oldname    待操作资源文件名
189
     * @param $newname    目标资源文件名
190
     *
191
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
192
     */
193
    public function rename($bucket, $oldname, $newname)
194
    {
195
        return $this->move($bucket, $oldname, $bucket, $newname);
196
    }
197
198
    /**
199
     * 给资源进行重命名,本质为move操作。
200 3
     *
201
     * @param $from_bucket     待操作资源所在空间
202 3
     * @param $from_key        待操作资源文件名
203 3
     * @param $to_bucket       目标资源空间名
204 3
     * @param $to_key          目标资源文件名
205 3
     *
206 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
207
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
208
     */
209
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
210
    {
211
        $from = \Qiniu\entry($from_bucket, $from_key);
212
        $to = \Qiniu\entry($to_bucket, $to_key);
213
        $path = '/copy/' . $from . '/' . $to;
214
        if ($force === true) {
215
            $path .= '/force/true';
216
        }
217
        list(, $error) = $this->rsPost($path);
218
        return $error;
219
    }
220
221
    /**
222
     * 将资源从一个空间到另一个空间
223
     *
224
     * @param $from_bucket     待操作资源所在空间
225
     * @param $from_key        待操作资源文件名
226
     * @param $to_bucket       目标资源空间名
227
     * @param $to_key          目标资源文件名
228
     *
229
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
230
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
231
     */
232
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
233
    {
234
        $from = \Qiniu\entry($from_bucket, $from_key);
235
        $to = \Qiniu\entry($to_bucket, $to_key);
236
        $path = '/move/' . $from . '/' . $to;
237
        if ($force) {
238
            $path .= '/force/true';
239
        }
240
        list(, $error) = $this->rsPost($path);
241
        return $error;
242
    }
243
244
    /**
245
     * 主动修改指定资源的文件元信息
246
     *
247
     * @param $bucket     待操作资源所在空间
248
     * @param $key        待操作资源文件名
249
     * @param $mime       待操作文件目标mimeType
250
     *
251
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
252
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
253
     */
254
    public function changeMime($bucket, $key, $mime)
255
    {
256
        $resource = \Qiniu\entry($bucket, $key);
257
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
258
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
259
        list(, $error) = $this->rsPost($path);
260
        return $error;
261
    }
262
263
264
    /**
265
     * 修改指定资源的存储类型
266
     *
267
     * @param $bucket     待操作资源所在空间
268 3
     * @param $key        待操作资源文件名
269
     * @param $fileType       待操作文件目标文件类型
270
     *
271 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
272 3
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
273 3
     */
274
    public function changeType($bucket, $key, $fileType)
275 3
    {
276 3
        $resource = \Qiniu\entry($bucket, $key);
277
        $path = '/chtype/' . $resource . '/type/' . $fileType;
278 3
        list(, $error) = $this->rsPost($path);
279 3
        return $error;
280
    }
281
282
    /**
283
     * 修改文件的存储状态,即禁用状态和启用状态间的的互相转换
284
     *
285
     * @param $bucket     待操作资源所在空间
286
     * @param $key        待操作资源文件名
287
     * @param $status       待操作文件目标文件类型
288
     *
289
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
290
     * @link  https://developer.qiniu.com/kodo/api/4173/modify-the-file-status
291 3
     */
292
    public function changeStatus($bucket, $key, $status)
293 3
    {
294 3
        $resource = \Qiniu\entry($bucket, $key);
295
        $path = '/chstatus/' . $resource . '/status/' . $status;
296 3
        list(, $error) = $this->rsPost($path);
297 3
        return $error;
298
    }
299 3
300 3
    /**
301 3
     * 从指定URL抓取资源,并将该资源存储到指定空间中
302
     *
303
     * @param $url        指定的URL
304
     * @param $bucket     目标资源空间
305
     * @param $key        目标资源文件名
306
     *
307
     * @return array    包含已拉取的文件信息。
308
     *                         成功时:  [
309
     *                                          [
310
     *                                              "hash" => "<Hash string>",
311
     *                                              "key" => "<Key string>"
312
     *                                          ],
313
     *                                          null
314
     *                                  ]
315
     *
316
     *                         失败时:  [
317
     *                                          null,
318
     *                                         Qiniu/Http/Error
319
     *                                  ]
320 12
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
321
     */
322 12
    public function fetch($url, $bucket, $key = null)
323 12
    {
324
325
        $resource = \Qiniu\base64_urlSafeEncode($url);
326
        $to = \Qiniu\entry($bucket, $key);
327
        $path = '/fetch/' . $resource . '/to/' . $to;
328
329
        $ak = $this->auth->getAccessKey();
330
        $ioHost = $this->config->getIovipHost($ak, $bucket);
331
332
        $url = $ioHost . $path;
333
        return $this->post($url, null);
334
    }
335
336 3
    /**
337
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
338 3
     *
339 3
     * @param $bucket     待获取资源所在的空间
340 3
     * @param $key        代获取资源文件名
341 3
     *
342
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
343
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
344 3
     */
345
    public function prefetch($bucket, $key)
346 3
    {
347 3
        $resource = \Qiniu\entry($bucket, $key);
348
        $path = '/prefetch/' . $resource;
349
350 3
        $ak = $this->auth->getAccessKey();
351
        $ioHost = $this->config->getIovipHost($ak, $bucket);
352
353 33
        $url = $ioHost . $path;
354
        list(, $error) = $this->post($url, null);
355 33
        return $error;
356 33
    }
357
358
    /**
359 33
     * 在单次请求中进行多个资源管理操作
360
     *
361
     * @param $operations     资源管理操作数组
362
     *
363
     * @return array 每个资源的处理情况,结果类似:
364
     *              [
365
     *                   { "code" => <HttpCode int>, "data" => <Data> },
366
     *                   { "code" => <HttpCode int> },
367
     *                   { "code" => <HttpCode int> },
368
     *                   { "code" => <HttpCode int> },
369
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
370
     *                   ...
371 27
     *               ]
372
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
373 27
     */
374 27
    public function batch($operations)
375
    {
376
        $params = 'op=' . implode('&op=', $operations);
377
        return $this->rsPost('/batch', $params);
378
    }
379
380
    /**
381
     * 设置文件的生命周期
382
     *
383 9
     * @param $bucket 设置文件生命周期文件所在的空间
384
     * @param $key    设置文件生命周期文件的文件名
385 9
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
386 9
     *
387
     * @return Mixed
388
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
389 12
     */
390
    public function deleteAfterDays($bucket, $key, $days)
391 12
    {
392 12
        $entry = \Qiniu\entry($bucket, $key);
393 12
        $path = "/deleteAfterDays/$entry/$days";
394 8
        list(, $error) = $this->rsPost($path);
395
        return $error;
396 8
    }
397
398
    private function getRsfHost()
399 33
    {
400
        $scheme = "http://";
401 33
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
402 33
            $scheme = "https://";
403 33
        }
404 9
        return $scheme . Config::RSF_HOST;
405
    }
406 30
407 30
    private function getRsHost()
408
    {
409
        $scheme = "http://";
410 3
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
411
            $scheme = "https://";
412 3
        }
413
        return $scheme . Config::RS_HOST;
414
    }
415
416 3
    private function getApiHost()
417
    {
418 3
        $scheme = "http://";
419
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
420
            $scheme = "https://";
421
        }
422 6
        return $scheme . Config::API_HOST;
423
    }
424 6
425
    private function getUcHost()
426
    {
427
        $scheme = "http://";
428 3
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
429
            $scheme = "https://";
430 3
        }
431
        return $scheme . Config::UC_HOST;
432
    }
433
434 3
    private function rsPost($path, $body = null)
435
    {
436 3
        $url = $this->getRsHost() . $path;
437
        return $this->post($url, $body);
438
    }
439
440
    private function apiPost($path, $body = null)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
441
    {
442
        $url = $this->getApiHost() . $path;
443
        return $this->post($url, $body);
444
    }
445
446
    private function ucPost($path, $body = null)
447
    {
448
        $url = $this->getUcHost() . $path;
449
        return $this->post($url, $body);
450
    }
451
452
    private function apiGet($path)
453
    {
454
        $url = $this->getApiHost() . $path;
455
        return $this->get($url);
456
    }
457
458
    private function rsGet($path)
459
    {
460
        $url = $this->getRsHost() . $path;
461
        return $this->get($url);
462
    }
463
464
    private function get($url)
465
    {
466 6
        $headers = $this->auth->authorization($url);
467
        $ret = Client::get($url, $headers);
468 6
        if (!$ret->ok()) {
469 6
            return array(null, new Error($url, $ret));
470 6
        }
471 6
        return array($ret->json(), null);
472 6
    }
473
474
    private function post($url, $body)
475 9
    {
476
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
477 9
        $ret = Client::post($url, $body, $headers);
478
        if (!$ret->ok()) {
479
            return array(null, new Error($url, $ret));
480 9
        }
481 9
        $r = ($ret->body === null) ? array() : $ret->json();
482 9
        return array($r, null);
483 9
    }
484 9
485 9
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket, $force)
486 9
    {
487 9
        return self::twoKeyBatch('/copy', $source_bucket, $key_pairs, $target_bucket, $force);
488 9
    }
489 9
490 9
491
    public static function buildBatchRename($bucket, $key_pairs, $force)
492
    {
493
        return self::buildBatchMove($bucket, $key_pairs, $bucket, $force);
494
    }
495
496
497
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket, $force)
498
    {
499
        return self::twoKeyBatch('/move', $source_bucket, $key_pairs, $target_bucket, $force);
500
    }
501
502
503
    public static function buildBatchDelete($bucket, $keys)
504
    {
505
        return self::oneKeyBatch('/delete', $bucket, $keys);
506
    }
507
508
509
    public static function buildBatchStat($bucket, $keys)
510
    {
511
        return self::oneKeyBatch('/stat', $bucket, $keys);
512
    }
513
514
    public static function buildBatchDeleteAfterDays($bucket, $key_day_pairs)
515
    {
516
        $data = array();
517
        foreach ($key_day_pairs as $key => $day) {
518
            array_push($data, '/deleteAfterDays/' . \Qiniu\entry($bucket, $key) . '/' . $day);
519
        }
520
        return $data;
521
    }
522
523
    public static function buildBatchChangeMime($bucket, $key_mime_pairs)
524
    {
525
        $data = array();
526
        foreach ($key_mime_pairs as $key => $mime) {
527
            array_push($data, '/chgm/' . \Qiniu\entry($bucket, $key) . '/mime/' . base64_encode($mime));
528
        }
529
        return $data;
530
    }
531
532
    public static function buildBatchChangeType($bucket, $key_type_pairs)
533
    {
534
        $data = array();
535
        foreach ($key_type_pairs as $key => $type) {
536
            array_push($data, '/chtype/' . \Qiniu\entry($bucket, $key) . '/type/' . $type);
537
        }
538
        return $data;
539
    }
540
541
    private static function oneKeyBatch($operation, $bucket, $keys)
542
    {
543
        $data = array();
544
        foreach ($keys as $key) {
545
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
546
        }
547
        return $data;
548
    }
549
550
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket, $force)
551
    {
552
        if ($target_bucket === null) {
553
            $target_bucket = $source_bucket;
554
        }
555
        $data = array();
556
        $forceOp = "false";
557
        if ($force) {
558
            $forceOp = "true";
559
        }
560
        foreach ($key_pairs as $from_key => $to_key) {
561
            $from = \Qiniu\entry($source_bucket, $from_key);
562
            $to = \Qiniu\entry($target_bucket, $to_key);
563
            array_push($data, $operation . '/' . $from . '/' . $to . "/force/" . $forceOp);
564
        }
565
        return $data;
566
    }
567
}
568