Completed
Pull Request — master (#228)
by r
04:17
created

BucketManager::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 2
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 http://developer.qiniu.com/docs/v6/api/reference/rs/
14
 */
15
final class BucketManager
16
{
17
    private $auth;
18
    private $zone;
19
20 42
    public function __construct(Auth $auth, Zone $zone = null)
21
    {
22 42
        $this->auth = $auth;
23 42
        if ($zone === null) {
24 42
            $this->zone = new Zone();
25 42
        }
26 42
    }
27
28
    /**
29
     * 获取指定账号下所有的空间名。
30
     *
31
     * @return string[] 包含所有空间名
32
     */
33 3
    public function buckets()
34
    {
35 3
        return $this->rsGet('/buckets');
36
    }
37
38
    /**
39
     * 列取空间的文件列表
40
     *
41
     * @param $bucket     空间名
42
     * @param $prefix     列举前缀
43
     * @param $marker     列举标识符
44
     * @param $limit      单次列举个数限制
45
     * @param $delimiter  指定目录分隔符
46
     *
47
     * @return array    包含文件信息的数组,类似:[
48
     *                                              {
49
     *                                                 "hash" => "<Hash string>",
50
     *                                                  "key" => "<Key string>",
51
     *                                                  "fsize" => "<file size>",
52
     *                                                  "putTime" => "<file modify time>"
53
     *                                              },
54
     *                                              ...
55
     *                                            ]
56
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
57
     */
58 3
    public function listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null)
59
    {
60 3
        $query = array('bucket' => $bucket);
61 3
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
62 3
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
63 3
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
64 3
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
65 3
        $url = Config::RSF_HOST . '/list?' . http_build_query($query);
66 3
        list($ret, $error) = $this->get($url);
67 3
        if ($ret === null) {
68 3
            return array(null, null, $error);
69
        }
70
        $marker = array_key_exists('marker', $ret) ? $ret['marker'] : null;
71
        return array($ret['items'], $marker, null);
72
    }
73
74
    /**
75
     * 获取资源的元信息,但不返回文件内容
76
     *
77
     * @param $bucket     待获取信息资源所在的空间
78
     * @param $key        待获取资源的文件名
79
     *
80
     * @return array    包含文件信息的数组,类似:
81
     *                                              [
82
     *                                                  "hash" => "<Hash string>",
83
     *                                                  "key" => "<Key string>",
84
     *                                                  "fsize" => <file size>,
85
     *                                                  "putTime" => "<file modify time>"
86
     *                                                  "fileType" => <file type>
87
     *                                              ]
88
     *
89
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
90
     */
91 3
    public function stat($bucket, $key)
92
    {
93 3
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
94 3
        return $this->rsGet($path);
95
    }
96
97
    /**
98
     * 删除指定资源
99
     *
100
     * @param $bucket     待删除资源所在的空间
101
     * @param $key        待删除资源的文件名
102
     *
103
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
104
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
105
     */
106 6
    public function delete($bucket, $key)
107
    {
108 6
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
109 6
        list(, $error) = $this->rsPost($path);
110 6
        return $error;
111
    }
112
113
114
    /**
115
     * 给资源进行重命名,本质为move操作。
116
     *
117
     * @param $bucket     待操作资源所在空间
118
     * @param $oldname    待操作资源文件名
119
     * @param $newname    目标资源文件名
120
     *
121
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
122
     */
123 3
    public function rename($bucket, $oldname, $newname)
124
    {
125 3
        return $this->move($bucket, $oldname, $bucket, $newname);
126
    }
127
128
    /**
129
     * 给资源进行重命名,本质为move操作。
130
     *
131
     * @param $from_bucket     待操作资源所在空间
132
     * @param $from_key        待操作资源文件名
133
     * @param $to_bucket       目标资源空间名
134
     * @param $to_key          目标资源文件名
135
     *
136
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
137
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
138
     */
139 12
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
140
    {
141 12
        $from = \Qiniu\entry($from_bucket, $from_key);
142 12
        $to = \Qiniu\entry($to_bucket, $to_key);
143 12
        $path = '/copy/' . $from . '/' . $to;
144 12
        if ($force) {
145
            $path .= '/force/true';
146
        }
147 12
        list(, $error) = $this->rsPost($path);
148 12
        return $error;
149
    }
150
151
    /**
152
     * 将资源从一个空间到另一个空间
153
     *
154
     * @param $from_bucket     待操作资源所在空间
155
     * @param $from_key        待操作资源文件名
156
     * @param $to_bucket       目标资源空间名
157
     * @param $to_key          目标资源文件名
158
     *
159
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
160
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
161
     */
162 3
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
163
    {
164 3
        $from = \Qiniu\entry($from_bucket, $from_key);
165 3
        $to = \Qiniu\entry($to_bucket, $to_key);
166 3
        $path = '/move/' . $from . '/' . $to;
167 3
        if ($force) {
168
            $path .= '/force/true';
169
        }
170 3
        list(, $error) = $this->rsPost($path);
171 3
        return $error;
172
    }
173
174
    /**
175
     * 主动修改指定资源的文件类型
176
     *
177
     * @param $bucket     待操作资源所在空间
178
     * @param $key        待操作资源文件名
179
     * @param $mime       待操作文件目标mimeType
180
     *
181
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
182
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
183
     */
184 3
    public function changeMime($bucket, $key, $mime)
185
    {
186 3
        $resource = \Qiniu\entry($bucket, $key);
187 3
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
188 3
        $path = '/chgm/' . $resource . '/mime/' .$encode_mime;
189 3
        list(, $error) = $this->rsPost($path);
190 3
        return $error;
191
    }
192
193
194
    /**
195
     * 修改指定资源的存储类型
196
     *
197
     * @param $bucket     待操作资源所在空间
198
     * @param $key        待操作资源文件名
199
     * @param $fileType       待操作文件目标文件类型
200
     *
201
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
202
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
203
     */
204
    public function changeType($bucket, $key, $fileType)
205
    {
206
        $resource=\Qiniu\entry($bucket, $key);
207
        $path='/chtype/'.$resource.'/type/'.$fileType;
208
        list(,$error)=$this->rsPost($path);
209
        return $error;
210
    }
211
212
213
    /**
214
     * 从指定URL抓取资源,并将该资源存储到指定空间中
215
     *
216
     * @param $url        指定的URL
217
     * @param $bucket     目标资源空间
218
     * @param $key        目标资源文件名
219
     *
220
     * @return array    包含已拉取的文件信息。
221
     *                         成功时:  [
222
     *                                          [
223
     *                                              "hash" => "<Hash string>",
224
     *                                              "key" => "<Key string>"
225
     *                                          ],
226
     *                                          null
227
     *                                  ]
228
     *
229
     *                         失败时:  [
230
     *                                          null,
231
     *                                         Qiniu/Http/Error
232
     *                                  ]
233
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
234
     */
235 3
    public function fetch($url, $bucket, $key = null)
236
    {
237
238 3
        $resource = \Qiniu\base64_urlSafeEncode($url);
239 3
        $to = \Qiniu\entry($bucket, $key);
240 3
        $path = '/fetch/' . $resource . '/to/' . $to;
241
242 3
        $ak = $this->auth->getAccessKey();
243 3
        $ioHost = $this->zone->getIoHost($ak, $bucket);
244
245 3
        $url = $ioHost . $path;
246 3
        return $this->post($url, null);
247
    }
248
249
    /**
250
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
251
     *
252
     * @param $bucket     待获取资源所在的空间
253
     * @param $key        代获取资源文件名
254
     *
255
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
256
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
257
     */
258 3
    public function prefetch($bucket, $key)
259
    {
260 3
        $resource = \Qiniu\entry($bucket, $key);
261 3
        $path = '/prefetch/' . $resource;
262
263 3
        $ak = $this->auth->getAccessKey();
264 3
        $ioHost = $this->zone->getIoHost($ak, $bucket);
265
266 3
        $url = $ioHost . $path;
267 3
        list(, $error) = $this->post($url, null);
268 3
        return $error;
269
    }
270
271
    /**
272
     * 在单次请求中进行多个资源管理操作
273
     *
274
     * @param $operations     资源管理操作数组
275
     *
276
     * @return array 每个资源的处理情况,结果类似:
277
     *              [
278
     *                   { "code" => <HttpCode int>, "data" => <Data> },
279
     *                   { "code" => <HttpCode int> },
280
     *                   { "code" => <HttpCode int> },
281
     *                   { "code" => <HttpCode int> },
282
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
283
     *                   ...
284
     *               ]
285
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
286
     */
287 12
    public function batch($operations)
288
    {
289 12
        $params = 'op=' . implode('&op=', $operations);
290 12
        return $this->rsPost('/batch', $params);
291
    }
292
293
    /**
294
     * 设置文件的生命周期
295
     *
296
     * @param $bucket 设置文件生命周期文件所在的空间
297
     * @param $key    设置文件生命周期文件的文件名
298
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
299
     *
300
     * @return Mixed
301
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
302
     */
303 3
    public function deleteAfterDays($bucket, $key, $days)
304
    {
305 3
        $entry = \Qiniu\entry($bucket, $key);
306 3
        $url = "/deleteAfterDays/$entry/$days";
307 3
        list(, $error) = $this->rsPost($url);
308 3
        return $error;
309
    }
310
311 27
    private function rsPost($path, $body = null)
312
    {
313 27
        $url = Config::RS_HOST . $path;
314 27
        return $this->post($url, $body);
315
    }
316
317 6
    private function rsGet($path)
318
    {
319 6
        $url = Config::RS_HOST . $path;
320 6
        return $this->get($url);
321
    }
322
323
    private function ioPost($path, $body = null)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
324
    {
325
        $url = Config::IO_HOST . $path;
326
        return $this->post($url, $body);
327
    }
328
329 9
    private function get($url)
330
    {
331 9
        $headers = $this->auth->authorization($url);
332 9
        $ret = Client::get($url, $headers);
333 9
        if (!$ret->ok()) {
334 9
            return array(null, new Error($url, $ret));
335
        }
336
        return array($ret->json(), null);
337
    }
338
339 33
    private function post($url, $body)
340
    {
341 33
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
342 33
        $ret = Client::post($url, $body, $headers);
343 33
        if (!$ret->ok()) {
344 33
            return array(null, new Error($url, $ret));
345
        }
346
        $r = ($ret->body === null) ? array() : $ret->json();
347
        return array($r, null);
348
    }
349
350 3
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket)
351
    {
352 3
        return self::twoKeyBatch('copy', $source_bucket, $key_pairs, $target_bucket);
353
    }
354
355
356 3
    public static function buildBatchRename($bucket, $key_pairs)
357
    {
358 3
        return self::buildBatchMove($bucket, $key_pairs, $bucket);
359
    }
360
361
362 6
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket)
363
    {
364 6
        return self::twoKeyBatch('move', $source_bucket, $key_pairs, $target_bucket);
365
    }
366
367
368
    public static function buildBatchDelete($bucket, $keys)
369
    {
370
        return self::oneKeyBatch('delete', $bucket, $keys);
371
    }
372
373
374 3
    public static function buildBatchStat($bucket, $keys)
375
    {
376 3
        return self::oneKeyBatch('stat', $bucket, $keys);
377
    }
378
379 3
    private static function oneKeyBatch($operation, $bucket, $keys)
380
    {
381 3
        $data = array();
382 3
        foreach ($keys as $key) {
383 3
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
384 3
        }
385 3
        return $data;
386
    }
387
388 9
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket)
389
    {
390 9
        if ($target_bucket === null) {
391
            $target_bucket = $source_bucket;
392
        }
393 9
        $data = array();
394 9
        foreach ($key_pairs as $from_key => $to_key) {
395 9
            $from = \Qiniu\entry($source_bucket, $from_key);
396 9
            $to = \Qiniu\entry($target_bucket, $to_key);
397 9
            array_push($data, $operation . '/' . $from . '/' . $to);
398 9
        }
399 9
        return $data;
400
    }
401
}
402