Completed
Pull Request — master (#293)
by
unknown
24:19
created

BucketManager   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 505
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 73.18%

Importance

Changes 0
Metric Value
dl 0
loc 505
ccs 131
cts 179
cp 0.7318
rs 6.96
c 0
b 0
f 0
wmc 53
lcom 2
cbo 5

36 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 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 rsPost() 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
     * @return string[] 包含空间绑定的所有域名
84 3
     */
85 3
86 3
    /**
87 3
     * 列取空间的文件列表
88
     *
89
     * @param $bucket     空间名
90
     * @param $prefix     列举前缀
91
     * @param $marker     列举标识符
92
     * @param $limit      单次列举个数限制
93
     * @param $delimiter  指定目录分隔符
94
     *
95
     * @return array    包含文件信息的数组,类似:[
96
     *                                              {
97
     *                                                 "hash" => "<Hash string>",
98
     *                                                  "key" => "<Key string>",
99
     *                                                  "fsize" => "<file size>",
100
     *                                                  "putTime" => "<file modify time>"
101
     *                                              },
102
     *                                              ...
103
     *                                            ]
104
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
105
     */
106
    public function listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null)
107 6
    {
108
        $query = array('bucket' => $bucket);
109 6
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
110 6
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
111
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
112
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
113
        $url = $this->getRsfHost() . '/list?' . http_build_query($query);
114
        return $this->get($url);
115
    }
116
117
    /**
118
     * 获取资源的元信息,但不返回文件内容
119
     *
120
     * @param $bucket     待获取信息资源所在的空间
121
     * @param $key        待获取资源的文件名
122 15
     *
123
     * @return array    包含文件信息的数组,类似:
124 15
     *                                              [
125 15
     *                                                  "hash" => "<Hash string>",
126 15
     *                                                  "key" => "<Key string>",
127
     *                                                  "fsize" => <file size>,
128
     *                                                  "putTime" => "<file modify time>"
129
     *                                                  "fileType" => <file type>
130
     *                                              ]
131
     *
132
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
133
     */
134
    public function stat($bucket, $key)
135
    {
136
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
137
        return $this->rsGet($path);
138
    }
139 3
140
    /**
141 3
     * 删除指定资源
142
     *
143
     * @param $bucket     待删除资源所在的空间
144
     * @param $key        待删除资源的文件名
145
     *
146
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
147
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
148
     */
149
    public function delete($bucket, $key)
150
    {
151
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
152
        list(, $error) = $this->rsPost($path);
153
        return $error;
154
    }
155 15
156
157 15
    /**
158 15
     * 给资源进行重命名,本质为move操作。
159 15
     *
160 15
     * @param $bucket     待操作资源所在空间
161 3
     * @param $oldname    待操作资源文件名
162 3
     * @param $newname    目标资源文件名
163 15
     *
164 15
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
165
     */
166
    public function rename($bucket, $oldname, $newname)
167
    {
168
        return $this->move($bucket, $oldname, $bucket, $newname);
169
    }
170
171
    /**
172
     * 给资源进行重命名,本质为move操作。
173
     *
174
     * @param $from_bucket     待操作资源所在空间
175
     * @param $from_key        待操作资源文件名
176
     * @param $to_bucket       目标资源空间名
177
     * @param $to_key          目标资源文件名
178 3
     *
179
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
180 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
181 3
     */
182 3
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
183 3
    {
184
        $from = \Qiniu\entry($from_bucket, $from_key);
185
        $to = \Qiniu\entry($to_bucket, $to_key);
186 3
        $path = '/copy/' . $from . '/' . $to;
187 3
        if ($force === true) {
188
            $path .= '/force/true';
189
        }
190
        list(, $error) = $this->rsPost($path);
191
        return $error;
192
    }
193
194
    /**
195
     * 将资源从一个空间到另一个空间
196
     *
197
     * @param $from_bucket     待操作资源所在空间
198
     * @param $from_key        待操作资源文件名
199
     * @param $to_bucket       目标资源空间名
200 3
     * @param $to_key          目标资源文件名
201
     *
202 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
203 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
204 3
     */
205 3
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
206 3
    {
207
        $from = \Qiniu\entry($from_bucket, $from_key);
208
        $to = \Qiniu\entry($to_bucket, $to_key);
209
        $path = '/move/' . $from . '/' . $to;
210
        if ($force) {
211
            $path .= '/force/true';
212
        }
213
        list(, $error) = $this->rsPost($path);
214
        return $error;
215
    }
216
217
    /**
218
     * 主动修改指定资源的文件元信息
219
     *
220
     * @param $bucket     待操作资源所在空间
221
     * @param $key        待操作资源文件名
222
     * @param $mime       待操作文件目标mimeType
223
     *
224
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
225
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
226
     */
227
    public function changeMime($bucket, $key, $mime)
228
    {
229
        $resource = \Qiniu\entry($bucket, $key);
230
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
231
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
232
        list(, $error) = $this->rsPost($path);
233
        return $error;
234
    }
235
236
237
    /**
238
     * 修改指定资源的存储类型
239
     *
240
     * @param $bucket     待操作资源所在空间
241
     * @param $key        待操作资源文件名
242
     * @param $fileType       待操作文件目标文件类型
243
     *
244
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
245
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
246
     */
247
    public function changeType($bucket, $key, $fileType)
248
    {
249
        $resource = \Qiniu\entry($bucket, $key);
250
        $path = '/chtype/' . $resource . '/type/' . $fileType;
251
        list(, $error) = $this->rsPost($path);
252
        return $error;
253
    }
254
255
    /**
256
     * 修改文件的存储状态,即禁用状态和启用状态间的的互相转换
257
     *
258
     * @param $bucket     待操作资源所在空间
259
     * @param $key        待操作资源文件名
260
     * @param $status       待操作文件目标文件类型
261
     *
262
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
263
     * @link  https://developer.qiniu.com/kodo/api/4173/modify-the-file-status
264
     */
265
    public function changeStatus($bucket, $key, $status)
266
    {
267
        $resource = \Qiniu\entry($bucket, $key);
268 3
        $path = '/chstatus/' . $resource . '/status/' . $status;
269
        list(, $error) = $this->rsPost($path);
270
        return $error;
271 3
    }
272 3
273 3
    /**
274
     * 从指定URL抓取资源,并将该资源存储到指定空间中
275 3
     *
276 3
     * @param $url        指定的URL
277
     * @param $bucket     目标资源空间
278 3
     * @param $key        目标资源文件名
279 3
     *
280
     * @return array    包含已拉取的文件信息。
281
     *                         成功时:  [
282
     *                                          [
283
     *                                              "hash" => "<Hash string>",
284
     *                                              "key" => "<Key string>"
285
     *                                          ],
286
     *                                          null
287
     *                                  ]
288
     *
289
     *                         失败时:  [
290
     *                                          null,
291 3
     *                                         Qiniu/Http/Error
292
     *                                  ]
293 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
294 3
     */
295
    public function fetch($url, $bucket, $key = null)
296 3
    {
297 3
298
        $resource = \Qiniu\base64_urlSafeEncode($url);
299 3
        $to = \Qiniu\entry($bucket, $key);
300 3
        $path = '/fetch/' . $resource . '/to/' . $to;
301 3
302
        $ak = $this->auth->getAccessKey();
303
        $ioHost = $this->config->getIovipHost($ak, $bucket);
304
305
        $url = $ioHost . $path;
306
        return $this->post($url, null);
307
    }
308
309
    /**
310
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
311
     *
312
     * @param $bucket     待获取资源所在的空间
313
     * @param $key        代获取资源文件名
314
     *
315
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
316
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
317
     */
318
    public function prefetch($bucket, $key)
319
    {
320 12
        $resource = \Qiniu\entry($bucket, $key);
321
        $path = '/prefetch/' . $resource;
322 12
323 12
        $ak = $this->auth->getAccessKey();
324
        $ioHost = $this->config->getIovipHost($ak, $bucket);
325
326
        $url = $ioHost . $path;
327
        list(, $error) = $this->post($url, null);
328
        return $error;
329
    }
330
331
    /**
332
     * 在单次请求中进行多个资源管理操作
333
     *
334
     * @param $operations     资源管理操作数组
335
     *
336 3
     * @return array 每个资源的处理情况,结果类似:
337
     *              [
338 3
     *                   { "code" => <HttpCode int>, "data" => <Data> },
339 3
     *                   { "code" => <HttpCode int> },
340 3
     *                   { "code" => <HttpCode int> },
341 3
     *                   { "code" => <HttpCode int> },
342
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
343
     *                   ...
344 3
     *               ]
345
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
346 3
     */
347 3
    public function batch($operations)
348
    {
349
        $params = 'op=' . implode('&op=', $operations);
350 3
        return $this->rsPost('/batch', $params);
351
    }
352
353 33
    /**
354
     * 设置文件的生命周期
355 33
     *
356 33
     * @param $bucket 设置文件生命周期文件所在的空间
357
     * @param $key    设置文件生命周期文件的文件名
358
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
359 33
     *
360
     * @return Mixed
361
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
362
     */
363
    public function deleteAfterDays($bucket, $key, $days)
364
    {
365
        $entry = \Qiniu\entry($bucket, $key);
366
        $path = "/deleteAfterDays/$entry/$days";
367
        list(, $error) = $this->rsPost($path);
368
        return $error;
369
    }
370
371 27
    private function getRsfHost()
372
    {
373 27
        $scheme = "http://";
374 27
        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...
375
            $scheme = "https://";
376
        }
377
        return $scheme . Config::RSF_HOST;
378
    }
379
380
    private function getRsHost()
381
    {
382
        $scheme = "http://";
383 9
        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...
384
            $scheme = "https://";
385 9
        }
386 9
        return $scheme . Config::RS_HOST;
387
    }
388
389 12
    private function getApiHost()
390
    {
391 12
        $scheme = "http://";
392 12
        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...
393 12
            $scheme = "https://";
394 8
        }
395
        return $scheme . Config::API_HOST;
396 8
    }
397
398
    private function rsPost($path, $body = null)
399 33
    {
400
        $url = $this->getRsHost() . $path;
401 33
        return $this->post($url, $body);
402 33
    }
403 33
404 9
    private function apiGet($path)
405
    {
406 30
        $url = $this->getApiHost() . $path;
407 30
        return $this->get($url);
408
    }
409
410 3
    private function rsGet($path)
411
    {
412 3
        $url = $this->getRsHost() . $path;
413
        return $this->get($url);
414
    }
415
416 3
    private function get($url)
417
    {
418 3
        $headers = $this->auth->authorization($url);
419
        $ret = Client::get($url, $headers);
420
        if (!$ret->ok()) {
421
            return array(null, new Error($url, $ret));
422 6
        }
423
        return array($ret->json(), null);
424 6
    }
425
426
    private function post($url, $body)
427
    {
428 3
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
429
        $ret = Client::post($url, $body, $headers);
430 3
        if (!$ret->ok()) {
431
            return array(null, new Error($url, $ret));
432
        }
433
        $r = ($ret->body === null) ? array() : $ret->json();
434 3
        return array($r, null);
435
    }
436 3
437
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket, $force)
438
    {
439
        return self::twoKeyBatch('/copy', $source_bucket, $key_pairs, $target_bucket, $force);
440
    }
441
442
443
    public static function buildBatchRename($bucket, $key_pairs, $force)
444
    {
445
        return self::buildBatchMove($bucket, $key_pairs, $bucket, $force);
446
    }
447
448
449
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket, $force)
450
    {
451
        return self::twoKeyBatch('/move', $source_bucket, $key_pairs, $target_bucket, $force);
452
    }
453
454
455
    public static function buildBatchDelete($bucket, $keys)
456
    {
457
        return self::oneKeyBatch('/delete', $bucket, $keys);
458
    }
459
460
461
    public static function buildBatchStat($bucket, $keys)
462
    {
463
        return self::oneKeyBatch('/stat', $bucket, $keys);
464
    }
465
466 6
    public static function buildBatchDeleteAfterDays($bucket, $key_day_pairs)
467
    {
468 6
        $data = array();
469 6
        foreach ($key_day_pairs as $key => $day) {
470 6
            array_push($data, '/deleteAfterDays/' . \Qiniu\entry($bucket, $key) . '/' . $day);
471 6
        }
472 6
        return $data;
473
    }
474
475 9
    public static function buildBatchChangeMime($bucket, $key_mime_pairs)
476
    {
477 9
        $data = array();
478
        foreach ($key_mime_pairs as $key => $mime) {
479
            array_push($data, '/chgm/' . \Qiniu\entry($bucket, $key) . '/mime/' . base64_encode($mime));
480 9
        }
481 9
        return $data;
482 9
    }
483 9
484 9
    public static function buildBatchChangeType($bucket, $key_type_pairs)
485 9
    {
486 9
        $data = array();
487 9
        foreach ($key_type_pairs as $key => $type) {
488 9
            array_push($data, '/chtype/' . \Qiniu\entry($bucket, $key) . '/type/' . $type);
489 9
        }
490 9
        return $data;
491
    }
492
493
    private static function oneKeyBatch($operation, $bucket, $keys)
494
    {
495
        $data = array();
496
        foreach ($keys as $key) {
497
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
498
        }
499
        return $data;
500
    }
501
502
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket, $force)
503
    {
504
        if ($target_bucket === null) {
505
            $target_bucket = $source_bucket;
506
        }
507
        $data = array();
508
        $forceOp = "false";
509
        if ($force) {
510
            $forceOp = "true";
511
        }
512
        foreach ($key_pairs as $from_key => $to_key) {
513
            $from = \Qiniu\entry($source_bucket, $from_key);
514
            $to = \Qiniu\entry($target_bucket, $to_key);
515
            array_push($data, $operation . '/' . $from . '/' . $to . "/force/" . $forceOp);
516
        }
517
        return $data;
518
    }
519
}
520