Completed
Pull Request — master (#234)
by
unknown
08:34
created

BucketManager::fetch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

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